Wolverine: renderer threading, caches, AMPR/AJM and shader recompiler fixes #937

Open
github-bot wants to merge 54 commits from github-bot/gh-937 into main AGit
Owner

@⁠itsmemac on GitHub · 2026-09-30 00:03 UTC · original
itsmemac:wolverine → main · +7166 −1038 · 118 files · 54 commits · open

Summary

Work that gets Marvel's Wolverine (PPSA03671) running, as 54 single-topic commits so any subset can
be cherry-picked. Each commit keeps its own author. The branch is rebased on current upstream/main
(e51de54e) and no longer depends on #780. The research diagnostics are stripped out.

  • Mac: 27 commits
  • Senaxx: 24 commits
  • Ali Almohaya: 3 commits (integer render-target exports, DRAW_INDIRECT_MULTI draw index,
    ShaderFunctions scalar-call expansion)

Earlier versions of this PR carried about 30 more commits (bindless, mesh culling and clip/cull
distances, GPU-read indirect draws, the software BVH path and others). They were dropped in this
rebase because upstream now has an equivalent or conflicting implementation. See "Not included".

Commits, by area

Renderer and GPU thread

  • Command buffers are submitted from a queue thread and recorded on a recording thread
  • New graphics pipelines are compiled on worker threads
  • Images and buffers are released between guest command buffers only after the GPU is done with
    them, which fixes sampling of freed memory after a guest unmap
  • A dispatch marks only the bytes its stores can reach as GPU-written
  • A scalar read that overlaps its own dispatch's write is logged once per shader pair instead of
    exiting
  • The GPU and recording threads prefer the fast cores of hybrid CPUs
  • Unmapped buffer descriptors and guest page 0 bind as null; uploads and unreadable image backing
    read as zero
  • Integer render targets export uint/sint; R32 image atomics go through an R32Uint view
  • Device loss is reported with VK_EXT_device_fault and NV checkpoints; a symbolized host stack is
    printed on fatal errors
  • Texture cache: per-frame eviction budget, with write-back of GPU-written tiled images
  • Buffer cache: entries age by presented frames
  • Vulkan: images fall back to host memory when device memory is exhausted; GPUs that cannot report
    surface capabilities are skipped
  • Video out: extra 10-bit and FP16 format policies on top of upstream's HDR table
  • EOP labels published once the GPU has executed the work (opt-in)

Shader recompiler

  • IEEE float min/max, denormal flush on output modifiers, ordered LDS accesses, gather LOD, constant
    vertex fetches
  • Wave64 branches, wave-size pipelines, device-clock S_MEMREALTIME, coherent loads and
    block-compressed volumes on AMD
  • Scalar calls expanded before translation (ShaderFunctions)
  • Native subgroup reductions for DPP scans; DPP16 leaves the destination alone for missing or
    inactive sources
  • SRT reads only from committed pages; reads past num_records return zero
  • The decoder gives up on the shader instead of exiting on unmodelled scalar operands; CDBG branches;
    SDWA byte destinations
  • Programs the recompiler cannot translate are skipped instead of exiting
  • NGG shaders with fewer than 3 GS/ES input VGPRs are accepted
  • Dominators are solved in reverse postorder (structurizing 2k-block shaders drops from 21-84 s to
    0.8 s)
  • IMAGE_SAMPLE*_CL applies the LOD clamp: MinLod where supported, otherwise a raised explicit LOD

Kernel, memory, libraries

  • Memory tracker: per-region clean bitmap, lazy direct-memory commit, cached mapping and range
    lookups
  • AMPR: map commands, counters, async engines, per-unit locks, cheap APR destination check
  • AJM: ATRAC9 config checks, partial superframes and vibration configs; Opus mapping family 1
  • AvPlayer file-replacement callbacks, savedata Convert, NpEntitlementAccess, sceAcmBatchJobPriority,
    fsync, equeue timeouts, timed condition waits

Not included

Dropped from earlier versions of this PR, because upstream has overlapping infrastructure or the
change depends on code that was removed:

  • Bindless textures and samplers (--bindless)
  • Mesh primitive culling, clip/cull distances, subgroup passes
  • GPU-read DrawIndirect and GPU-side indirect thread counts
  • Software IMAGE_BVH_INTERSECT_RAY, 64-bit compare/arith opcodes
  • FLAT shared/private apertures, GPU-selected buffer descriptors through BDA, bound-length storage
    buffers
  • Dispatch rollback on unmapped BDA pages and the other opt-in env switches
    (KYTY_IGNORE_WRITTEN_OVERLAP and similar)

Testing

  • Builds with MSVC 2022 / clang-cl on Windows. The emulator and test targets build with no errors.
  • shader_cfg and resource_tracking pass.

AI was used in development

**@⁠itsmemac** on GitHub · 2026-09-30 00:03 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/937) `itsmemac:wolverine` → `main` · +7166 −1038 · 118 files · 54 commits · open ## Summary Work that gets Marvel's Wolverine (PPSA03671) running, as 54 single-topic commits so any subset can be cherry-picked. Each commit keeps its own author. The branch is rebased on current upstream/main (e51de54e) and no longer depends on #780. The research diagnostics are stripped out. - Mac: 27 commits - Senaxx: 24 commits - Ali Almohaya: 3 commits (integer render-target exports, DRAW_INDIRECT_MULTI draw index, ShaderFunctions scalar-call expansion) Earlier versions of this PR carried about 30 more commits (bindless, mesh culling and clip/cull distances, GPU-read indirect draws, the software BVH path and others). They were dropped in this rebase because upstream now has an equivalent or conflicting implementation. See "Not included". ## Commits, by area **Renderer and GPU thread** - Command buffers are submitted from a queue thread and recorded on a recording thread - New graphics pipelines are compiled on worker threads - Images and buffers are released between guest command buffers only after the GPU is done with them, which fixes sampling of freed memory after a guest unmap - A dispatch marks only the bytes its stores can reach as GPU-written - A scalar read that overlaps its own dispatch's write is logged once per shader pair instead of exiting - The GPU and recording threads prefer the fast cores of hybrid CPUs - Unmapped buffer descriptors and guest page 0 bind as null; uploads and unreadable image backing read as zero - Integer render targets export uint/sint; R32 image atomics go through an R32Uint view - Device loss is reported with VK_EXT_device_fault and NV checkpoints; a symbolized host stack is printed on fatal errors - Texture cache: per-frame eviction budget, with write-back of GPU-written tiled images - Buffer cache: entries age by presented frames - Vulkan: images fall back to host memory when device memory is exhausted; GPUs that cannot report surface capabilities are skipped - Video out: extra 10-bit and FP16 format policies on top of upstream's HDR table - EOP labels published once the GPU has executed the work (opt-in) **Shader recompiler** - IEEE float min/max, denormal flush on output modifiers, ordered LDS accesses, gather LOD, constant vertex fetches - Wave64 branches, wave-size pipelines, device-clock S_MEMREALTIME, coherent loads and block-compressed volumes on AMD - Scalar calls expanded before translation (ShaderFunctions) - Native subgroup reductions for DPP scans; DPP16 leaves the destination alone for missing or inactive sources - SRT reads only from committed pages; reads past num_records return zero - The decoder gives up on the shader instead of exiting on unmodelled scalar operands; CDBG branches; SDWA byte destinations - Programs the recompiler cannot translate are skipped instead of exiting - NGG shaders with fewer than 3 GS/ES input VGPRs are accepted - Dominators are solved in reverse postorder (structurizing 2k-block shaders drops from 21-84 s to 0.8 s) - IMAGE_SAMPLE*_CL applies the LOD clamp: MinLod where supported, otherwise a raised explicit LOD **Kernel, memory, libraries** - Memory tracker: per-region clean bitmap, lazy direct-memory commit, cached mapping and range lookups - AMPR: map commands, counters, async engines, per-unit locks, cheap APR destination check - AJM: ATRAC9 config checks, partial superframes and vibration configs; Opus mapping family 1 - AvPlayer file-replacement callbacks, savedata Convert, NpEntitlementAccess, sceAcmBatchJobPriority, fsync, equeue timeouts, timed condition waits ## Not included Dropped from earlier versions of this PR, because upstream has overlapping infrastructure or the change depends on code that was removed: - Bindless textures and samplers (`--bindless`) - Mesh primitive culling, clip/cull distances, subgroup passes - GPU-read DrawIndirect and GPU-side indirect thread counts - Software IMAGE_BVH_INTERSECT_RAY, 64-bit compare/arith opcodes - FLAT shared/private apertures, GPU-selected buffer descriptors through BDA, bound-length storage buffers - Dispatch rollback on unmapped BDA pages and the other opt-in env switches (`KYTY_IGNORE_WRITTEN_OVERLAP` and similar) ## Testing - Builds with MSVC 2022 / clang-cl on Windows. The emulator and test targets build with no errors. - shader_cfg and resource_tracking pass. AI was used in development
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, ResourceTracking and the
  tessellation analysis and lowering record the reason, log it once and unwind
  instead of calling EXIT. TrackResources and the tessellation entry points
  return success.
- The pipeline cache remembers unsupported programs and rejected tessellation
  pairs so they are not translated again on every draw.
- PrepareDrawRenderState skips a draw whose vertex or pixel program is missing,
  and a tessellated draw is skipped when any of its three stages is missing;
  DispatchDirect skips a dispatch whose program is missing.
- A resource-materialization failure (a descriptor source not mapped or filled
  yet) skips the draw and is logged, at most sixteen times.
- resource_tracking_tests links common for the logging.
S_MEMREALTIME (SMEM opcode 0x25) reads a free-running 100 MHz counter; it
decoded to a UINT64_MAX placeholder. It is now translated to a new
ReadClockRealtime64 value opcode and emitted as
OpReadClockKHR at device scope, read once as a uvec2 so the halves cannot tear
and shifted right by three: a ~1 GHz device clock lands near 125 MHz without a
64-bit divide, so guest timeouts expire slightly early rather than ten times
early. A 56-instruction program the Spider-Man menu dispatches ~400 times a
frame polls it and had been skipped.

VK_KHR_shader_clock with shaderDeviceClock is enabled when the device offers
it. On a device without it, a program that reads the clock is skipped like any
other program the recompiler cannot translate.

ScalarMemRealtimeCapturedPlaceholder becomes ScalarMemRealtimeReadsDeviceClock:
the same decode checks, and the translation must read the device clock
(OpReadClockKHR); a clock has no fixed value to read back.
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.
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.
- 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.
When the device heap refuses an image, it is created again allowing
host-visible memory instead of failing. The Spider-Man menu needs about thirty
such images on a 6 GB card. The first 32 spills are logged.
Adds video-out pixel format encodings titles register beside the ones already
listed:

- 0x8100000622000000, 0x8100070422000000: A2B10G10R10
- 0x8100000600000000, 0x8100070400000000: A2R10G10B10
- 0xc001070722000000, 0xc001070700000000: R16G16B16A16 float (the second with
  swapped channels, as for 0xc001000600000000)
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.
Enough of AMPR for Spider-Man to load its world.

- APR mapBegin and mapDirectBegin append real AMM map records. They are AMM map
  commands placed in an APR buffer; as no-ops, the level load read into
  MEM_RESERVE pages and failed with EFAULT.
- The AMPR counter bank from the SDK's command_buffer.h: writeCounter,
  waitOnCounter with masks and every compare operation, writeAddressFromCounter
  and its pair form.
- Submissions run on engine threads, one per (unit, priority ring): APR 1-6 and
  AMM 0-2, taken from the submit call. A single in-order queue deadlocked a
  waitOnAddress against the higher-priority writer of the value it waited for.
- APR file reads go through a host chunk and memcpy: ReadFile into a page the
  memory tracker protects fails silently with ERROR_NOACCESS and the data
  landed as zeros. A committed-range check precedes the read; a short read is
  logged instead of failing the command.
- A free-interval pool for automatic AMM addresses; unmapping part of an
  automatic mapping returns only that part. Wide-string path lists, whose
  entries are read only from committed pages, and WaitOnAddress.
- A submission that fails to enqueue is discarded instead of waited on, and
  resetting a command buffer drops its counter commands.
The ATRAC9 decoder keeps a partial superframe across decode jobs, as the
hardware does, instead of reporting partial input and dropping it. A RIFF
header split across jobs is kept the same way, and Initialize with a new
configuration drops what was kept.

Spider-Man's recap audio thread had been resubmitting the same bytes forever.
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.
Makes a GPU hang diagnosable from one run.

- On ErrorDeviceLost, VK_EXT_device_fault is queried and its description,
  address and vendor records are logged; the vendor binary is written to
  _device_fault.nv-gpudmp (on NVIDIA an Aftermath dump behind a 0x38-byte
  header, which names the hung shader and the program counters of its warps).
- VK_NV_device_diagnostic_checkpoints markers are recorded from each command
  buffer's debug info, and VK_NV_device_diagnostics_config is enabled with
  shader debug info, resource tracking and error reporting when offered.
- MasterSemaphore names the vk::Result of a failed wait instead of
  EXIT_NOT_IMPLEMENTED.

This is how the coherence hang and Astro Bot's shadow-stage hang were found.
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.
Co-authored-by: Senaxx <[email protected]>
Co-authored-by: Ali Almohaya <[email protected]>
Co-authored-by: Mac <[email protected]>
Co-authored-by: Mac <[email protected]>
Co-authored-by: Senaxx <[email protected]>
Co-authored-by: Mac <[email protected]>
Co-authored-by: Senaxx <[email protected]>
Co-authored-by: Senaxx <[email protected]>
Co-authored-by: Mac <[email protected]>
Co-authored-by: Mac <[email protected]>
Co-authored-by: Mac <[email protected]>
Co-authored-by: Senaxx <[email protected]>
Co-authored-by: Senaxx <[email protected]>
Co-authored-by: Mac <[email protected]>
Co-authored-by: Mac <[email protected]>
Co-authored-by: Mac <[email protected]>
Co-authored-by: Ali Almohaya <[email protected]>
Co-authored-by: Senaxx <[email protected]>
Co-authored-by: Senaxx <[email protected]>
Resource tracking gives a shader up by throwing, and the Linux and macOS
builds turn exceptions off for clang and GCC, so every target that compiles
the file needs them on.
The SDK concatenates prefix and path without a separator. A UTF-16 path
read as 8-bit text counts as UTF-16 only when it is longer and all ASCII.
Windows times condition-variable waits in whole milliseconds, so a short
wait could wake up to about 1 ms late. The last 2.5 ms are now timed with
the high-resolution timer in short slices.
Resource materialization bounds the address of each store to a written
buffer (immediates, host-evaluated values, compute invocation IDs and a few
integer operations on them). Only that range becomes GPU-written, so a
heap-wide descriptor no longer makes every CPU access to the heap drain
the GPU. Without a bound the whole descriptor range counts, as before.
The driver compiled on the GPU thread, which stopped the emulated GPU for
seconds per new pipeline. Creation is split into PrepareGraphicsPipeline
and CreateGraphicsPipeline, and the latter runs on a small worker pool. A
draw that writes no memory is skipped until its pipeline is ready; one that
writes buffers or storage images waits for it.
- vkQueueSubmit, and the queue lock that present also holds, run off the GPU
  thread. Frames reach the presenter only after their flip tick completed;
  the presenter's own scheduler stays synchronous.
- A Vulkan recording thread begins, records, ends and submits the command
  buffers in order. The GPU thread queues the Vulkan commands of the hot
  recording paths through CommandRecorder, which has the names and arguments
  of vk::CommandBuffer. Code that records through the raw
  CommandBuffer::Handle() first waits for the thread to catch up.
- The recording thread is a port of IDXTRI's d9958e28 and ad1e1396.
Tracker:
- A per-region bitmap answers whether a buffer range is CPU-clean; read-only
  uploads visit only the CPU-dirty regions instead of every region.
- A watched range whose host protection was replaced behind the tracker
  (views mapped again after a partial unmap, rolled-back unmaps, guest
  mprotect) gets the tracker's protection back.

Guest memory:
- Windows: direct memory is reserved at start and committed when the guest
  maps it, instead of charging all of it to the commit limit at boot.
- A thread remembers its recent backing lookups until the mapping table
  changes.
- TryClampRangeSize remembers recent answers until the guest mappings change,
  and ClampRangeSize answers from merged committed spans.

Timed waits use microsecond deadlines instead of whole milliseconds.
With file replacement callbacks, the AVIO reader passed FFmpeg's buffer (host
heap) to the game's read_offset callback. A callback that reads through AMPR
accepts only guest memory, so the read failed with EFAULT and the game
asserted.

The reader now allocates its 64 KB read buffer with the game's
memory_replacement allocator, lets the callback read into it and copies the
bytes to FFmpeg. Without an allocator it keeps the old behaviour.
AvPlayerFileTests checks that every callback read lands in a buffer of the
game's allocator and that the buffer is freed.
- V_MIN/V_MAX_F32 and the median use GLSL NMin/NMax with the signed-zero
  rule (two zeros give the AND or OR of their bits) and OpIsNan, under
  SignedZeroInfNanPreserve.
- VOP3 output modifiers flush denormal and negative-zero results to +0.
- Compute: a barrier keeps one guest wave's LDS accesses in order across
  host invocations (workgroup scope for a single-wave workgroup, subgroup
  scope when one host subgroup holds one guest wave).
- Explicit-LOD gathers with linear mip filtering gather the nearest level.
- Vertex input: embedded fetches the shader only reads as constants get no
  attribute and no buffer.
- S_MEMREALTIME counts at the device clock's real rate, taken from the
  timestamp period and shifted to the guest's 100 MHz; depth feedback loops
  work without the extension.
- Native wave64 scalar branches decide for the whole wave, and branches on
  VCC and EXEC ballot only those conditions, not SCC.
- Pixel and mesh pipelines require the guest's wave size where the driver
  allows it.
- Coherent buffer loads are followed by a device-scope acquire barrier on
  every vendor but NVIDIA, so a value polled from another workgroup is seen.
- V_MBCNT wraps the lane index at 32 in wave32 vertex shaders on 64-wide host
  subgroups, which kept NGG strand geometry from exporting positions.
- Block-compressed volumes get 2D views only where the device allows them,
  and drop optional create flags until the device accepts the image.
TextureCache::DeleteImage and BufferCache::DeleteBuffer destroyed their resource at once when no
guest command buffer was active, which is where a guest memory unmap runs. Command buffers
submitted just before could still be sampling the destroyed images.

CommandScheduler::DeferRelease queues an operation without requiring an active command buffer; it
runs once the GPU has finished the current tick. Both caches release through it, and keep a
resource that was bound again in a tick the GPU has not finished.
A shader's scalar resource reads (the inputs the host evaluated to choose its reachable blocks)
can overlap a buffer a bound shader writes. The host evaluates those inputs from the state before
the dispatch, so the overlap is logged once per shader pair instead of exiting. A written range
bounded by the dispatch's own stores (BufferWriteExtent) is used instead of the whole descriptor,
so a heap-wide descriptor alone does not count as an overlap.
The _CL clamp is the last address component of the instruction. Implicit and gradient samples
take it as the MinLod image operand where shaderResourceMinLod is supported; explicit-LOD forms
raise their LOD to it.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:37:36 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-30 00:19 UTC · original · edited 2026-10-11 20:31 UTC

Review in Change Stack →

📝 Walkthrough
📝 Walkthrough
📝 Walkthrough
📝 Walkthrough

Walkthrough

The pull request adds GPU bindless image and sampler handling, indirect draw and dispatch paths, GPU memory-fault recovery, and device-loss diagnostics. It expands shader decoding, translation, resource tracking, and SPIR-V emission, including multi-pass mesh work and shader-function expansion. It also changes kernel and library services for file flushing, save-data conversion, audio queue tracking, and command-buffer submission. Tests cover the updated graphics, shader, audio, and Windows x64 load-emulation paths.

Suggested reviewers: nmzik








Priority: ➖ Normal

Merge Risk: 🟠 High · up to 41c7b

This change touches core rendering and shader compilation, and several default-on paths can cause incorrect rendering, stale data, or crashes. Some of these paths also affect titles other than the target game. Fix the listed issues before merging.

Security Architecture Review

Security architecture risk: 🟡 Moderate · up to 3fa2b

The change expands how guest workloads access memory and publish completion state. Address and mapping checks constrain the inspected read path, but ownership and recovery guarantees for delayed writes remain unresolved. No privilege escalation or isolation escape was established.

Retained concerns

  • Medium · security · inferred: Optional deferred label publication adds a completion callback that queues a later GPU-thread memcpy to a captured raw address. Sequence matching protects pending-entry cleanup, not destination mapping identity. Unmapping waits for priority callbacks, but the inspected code does not establish that the second queued write is completed or canceled before mapping reuse. Rejected enqueue also has no local pending-entry cleanup. This leaves an unresolved ownership and terminal-state contract that could allow stale writes or process faults; exploitation was not established.
Security review details

Security Blast Radius

  • inferred — The inspected paths affect guest memory and execution state within the emulator process. The read path is constrained by current guest mappings and backing-allocation bounds. No cross-tenant, cross-service or elevated-privilege attack path was established; the complete independently attackable scope remains unverified.

Security Findings and Attack Paths

  • inferred — A mapping-reuse or cancellation interleaving could become relevant to deferred label writes because the later memcpy retains only a raw destination address. Scheduler tick ordering and unmap draining are countercontrols, so this remains an unresolved lifecycle concern rather than a verified arbitrary-write vulnerability.

Trust Boundaries and Controls

  • observed — Backing transfers validate every mapping segment and backing offset before copying, holding the backing mapping mutex through validation and transfer. Unsupported instructions, mismatched fault addresses and failed reads reject emulation instead of completing the load.
  • inferred — Whether default clean-read authorization fully covers texture writers and guest protection policy remains unresolved. The inspected predicate checks buffer-modified and downloading ranges, while direct backing transfer does not consult mapping protection mode. Neither observation alone establishes a newly introduced bypass.

Resilience and Maintainability Implications

  • observed — Guest GPU shutdown stops accepting external commands and drains accepted work before joining. Scheduler shutdown drains callbacks separately. Deferred label enqueue rejection is ignored locally, leaving its pending-entry cleanup dependent on successful execution rather than an explicit cancellation transition.

Hardening Proposals

  • proposed — Bind deferred destination writes to a mapping lifetime or generation, and define completion and cancellation across both callback and GPU-command queues, including unmap, reuse and shutdown.










Pre-merge checks | Passed 4 | Inconclusive 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage Inconclusive Docstring coverage is 10.21% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 529 functions across 78 files. (71 skippe… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Title check Passed The title clearly summarizes the main areas changed: renderer threading, caches, AMPR/AJM support, and shader recompiler fixes.
Description check Passed The description is detailed and directly related to the changeset, including renderer, shader recompiler, kernel, memory, AMPR, AJM, and testing changes.

Full details: Docstring Coverage

Explanation

Docstring coverage is 10.21% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 529 functions across 78 files. (71 skipped: 7 unsupported, 64 over the file limit.)



Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

**@⁠coderabbitai[bot]** on GitHub · 2026-09-30 00:19 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/937#issuecomment-5901558367) · edited 2026-10-11 20:31 UTC <!-- This is an auto-generated comment: summarize by coderabbit.ai --> <!-- review_stack_entry_start --> <a href="https://app.coderabbit.ai/change-stack/KytyPS5/KytyPS5/pull/937?scope=ghh_OusAJGA4HG8ljoOV0wJvVx8NmnZIjc2DdjmxOu0xZWA&amp;cs_source=review_comment"><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui-dark.svg?v=3"><source media="(prefers-color-scheme: light)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg?v=3"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg?v=3" alt="Review in Change Stack →" height="32"></picture></a> <!-- review_stack_entry_end --> <!-- walkthrough_start --> <details> <summary><strong>📝 Walkthrough</strong></summary> <dl> <dd> <details> <summary><strong>📝 Walkthrough</strong></summary> <dl> <dd> <details> <summary><strong>📝 Walkthrough</strong></summary> <dl> <dd> <dl> <dd> <details> <summary><strong>📝 Walkthrough</strong></summary> <dl> <dd> <dl> <dd> <dl> <dd> ## Walkthrough The pull request adds GPU bindless image and sampler handling, indirect draw and dispatch paths, GPU memory-fault recovery, and device-loss diagnostics. It expands shader decoding, translation, resource tracking, and SPIR-V emission, including multi-pass mesh work and shader-function expansion. It also changes kernel and library services for file flushing, save-data conversion, audio queue tracking, and command-buffer submission. Tests cover the updated graphics, shader, audio, and Windows x64 load-emulation paths. **Suggested reviewers:** `nmzik` <hr> </dd> </dl> <hr> </dd> </dl> <hr> </dd> </dl> </details> <hr> </dd> </dl> <hr> </dd> </dl> </details> <hr> </dd> </dl> </details> <hr> </dd> </dl> </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ➖ Normal <!-- change_assessment_commit:"41c7b27b738ce882c93108e8b882405e33a78d8d" --> <!-- change_assessment_end --> <!-- final_review_risk_start --> **Merge Risk:** **🟠 High** · up to `41c7b` <!-- final_review_risk_coverage:{"sourceCommitId":"41c7b27b738ce882c93108e8b882405e33a78d8d","coveredCommitId":"41c7b27b738ce882c93108e8b882405e33a78d8d","kind":"reviewed"} --> This change touches core rendering and shader compilation, and several default-on paths can cause incorrect rendering, stale data, or crashes. Some of these paths also affect titles other than the target game. Fix the listed issues before merging. <!-- final_review_risk_end --> <!-- architecture_review_start --> <details> <summary><strong>Security Architecture Review</strong></summary> <dl> <dd> <dl> <dd> <dl> <dd> <dl> <dd> <dl> <dd> <dl> <dd> **Security architecture risk:** _🟡 Moderate_ · up to `3fa2b` The change expands how guest workloads access memory and publish completion state. Address and mapping checks constrain the inspected read path, but ownership and recovery guarantees for delayed writes remain unresolved. No privilege escalation or isolation escape was established. **Retained concerns** - **Medium · security · inferred:** Optional deferred label publication adds a completion callback that queues a later GPU-thread memcpy to a captured raw address. Sequence matching protects pending-entry cleanup, not destination mapping identity. Unmapping waits for priority callbacks, but the inspected code does not establish that the second queued write is completed or canceled before mapping reuse. Rejected enqueue also has no local pending-entry cleanup. This leaves an unresolved ownership and terminal-state contract that could allow stale writes or process faults; exploitation was not established. <details> <summary><strong>Security review details</strong></summary> <dl> <dd> <dl> <dd> <dl> <dd> <dl> <dd> <dl> <dd> **Security Blast Radius** - _inferred_ — The inspected paths affect guest memory and execution state within the emulator process. The read path is constrained by current guest mappings and backing-allocation bounds. No cross-tenant, cross-service or elevated-privilege attack path was established; the complete independently attackable scope remains unverified. **Security Findings and Attack Paths** - _inferred_ — A mapping-reuse or cancellation interleaving could become relevant to deferred label writes because the later memcpy retains only a raw destination address. Scheduler tick ordering and unmap draining are countercontrols, so this remains an unresolved lifecycle concern rather than a verified arbitrary-write vulnerability. **Trust Boundaries and Controls** - _observed_ — Backing transfers validate every mapping segment and backing offset before copying, holding the backing mapping mutex through validation and transfer. Unsupported instructions, mismatched fault addresses and failed reads reject emulation instead of completing the load. - _inferred_ — Whether default clean-read authorization fully covers texture writers and guest protection policy remains unresolved. The inspected predicate checks buffer-modified and downloading ranges, while direct backing transfer does not consult mapping protection mode. Neither observation alone establishes a newly introduced bypass. **Resilience and Maintainability Implications** - _observed_ — Guest GPU shutdown stops accepting external commands and drains accepted work before joining. Scheduler shutdown drains callbacks separately. Deferred label enqueue rejection is ignored locally, leaving its pending-entry cleanup dependent on successful execution rather than an explicit cancellation transition. **Hardening Proposals** - _proposed_ — Bind deferred destination writes to a mapping lifetime or generation, and define completion and cancellation across both callback and GPU-command queues, including unmap, reuse and shutdown. <hr> </dd> </dl> <hr> </dd> </dl> <hr> </dd> </dl> <hr> </dd> </dl> <hr> </dd> </dl> </details> </dd> </dl> <hr> </dd> </dl> <hr> </dd> </dl> <hr> </dd> </dl> <hr> </dd> </dl> <hr> </dd> </dl> </details> <!-- architecture_review_end --> <!-- 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-v1.svg" width="14" height="17" align="middle" alt="Passed" title="Passed"></picture></sup> 4 | <sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-inconclusive-14-v1.svg" width="14" height="17" align="middle" alt="Inconclusive" title="Inconclusive"></picture></sup> 1</strong></summary> <dl> <dd> ### ❌ Failed checks (1 inconclusive) | Check name | Status | Explanation | Resolution | | :---------------- | :--------------------------------------------------------------------------------------------------------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------- | | Docstring Coverage | ![Inconclusive](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-inconclusive.svg) | Docstring coverage is 10.21% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 529 functions across 78 files. (71 skippe… | Write docstrings for the functions missing them to satisfy the coverage threshold. | <details> <summary><strong>✅ Passed checks (4 passed)</strong></summary> <dl> <dd> | Check name | Status | Explanation | | :------------------------ | :--------------------------------------------------------------------------------------------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------- | | Linked Issues check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | Check skipped because no linked issues were found for this pull request. | | Out of Scope Changes check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | Check skipped because no linked issues were found for this pull request. | | Title check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The title clearly summarizes the main areas changed: renderer threading, caches, AMPR/AJM support, and shader recompiler fixes. | | Description check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The description is detailed and directly related to the changeset, including renderer, shader recompiler, kernel, memory, AMPR, AJM, and testing changes. | <hr> </dd> </dl> </details> <details> <summary><strong>Full details: Docstring Coverage</strong></summary> <dl> <dd> **Explanation** Docstring coverage is 10.21% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 529 functions across 78 files. (71 skipped: 7 unsupported, 64 over the file limit.) </dd> </dl> </details> <hr> </dd> </dl> </details> <!-- pre_merge_checks_walkthrough_end --> <!-- tips_start --> --- Thanks for using [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=KytyPS5/KytyPS5&utm_content=937)! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. <details> <summary><strong>❤️ Share</strong></summary> <dl> <dd> - [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai) - [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai) - [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai) - [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code) <hr> </dd> </dl> </details> <sub>Comment `@coderabbitai help` to get the list of available commands.</sub> <!-- tips_end -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-30 00:19 UTC · original
On src/graphics/guest_gpu/graphicsRun.cpp line 1090 (outdated):

@@ -907,6 +1069,25 @@ void CommandProcessor::DrawIndirect(uint32_t data_offset, uint32_t draw_initiato
 	const auto* args_addr =
 	    reinterpret_cast<const void*>(m_draw_indirect_args_base_addr + data_offset);
 
+	// Research: the GPU reads its own arguments. A CPU read of arguments an earlier GPU pass
+	// wrote faults on the tracked page and drains the whole queue, once per draw. 8-bit indices
+	// (expanded on the host) and an unknown index buffer size keep the CPU read.
+	if (!indexed) {
+		DrawIndexAuto({.vertex_count   = 1,
+		               .instance_count = 1,
+		               .offset_source  = DrawOffsetSource::IndirectArgs,
+		               .gpu_args       = reinterpret_cast<uint64_t>(args_addr)});
+		return;
+	}
+	if (m_index_buffer_size != 0 && (m_index_type_and_size == 0 || m_index_type_and_size == 1)) {
+		DrawIndex({.index_count    = m_index_buffer_size,
+		           .index_addr     = reinterpret_cast<const void*>(m_index_base_addr),
+		           .instance_count = 1,
+		           .offset_source  = DrawOffsetSource::IndirectArgs,
+		           .gpu_args       = reinterpret_cast<uint64_t>(args_addr)});
+		return;
+	}
+

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
rg -nP -C3 '\bm_num_instances\b' src/graphics/guest_gpu

Repository: KytyPS5/KytyPS5

Length of output: 4811


🏁 Script executed:

#!/bin/bash
printf '%s\n' '--- graphicsRun.cpp 920-1160 ---'
sed -n '920,1160p' src/graphics/guest_gpu/graphicsRun.cpp
printf '%s\n' '--- graphicsRun.cpp 1160-1320 ---'
sed -n '1160,1320p' src/graphics/guest_gpu/graphicsRun.cpp
printf '%s\n' '--- commandProcessor.h 155-185 ---'
sed -n '155,185p' src/graphics/guest_gpu/command_processor/commandProcessor.h
printf '%s\n' '--- diff base..head for relevant file ---'
git diff --unified=35 05057c9441dbf3972d49f9143b90213a43a01a00 d6ec3a42ed19d0f16bb3e184ca57e20cce8d5176 -- src/graphics/guest_gpu/graphicsRun.cpp src/graphics/guest_gpu/command_processor/commandProcessor.h

Repository: KytyPS5/KytyPS5

Length of output: 42875


Preserve the persistent instance count for GPU indirect draws.

The GPU branches pass instance_count = 1 and return without updating m_num_instances. A later DrawIndex or DrawIndexAuto with instance_count == 0 can therefore use the count from before the indirect draw. Preserve the state update, or retain the CPU path when the GPU path cannot provide it. Remove the unreachable non-indexed CPU branch.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-30 00:19 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/937#discussion_r4139620591) On `src/graphics/guest_gpu/graphicsRun.cpp` line 1090 (outdated): ```diff @@ -907,6 +1069,25 @@ void CommandProcessor::DrawIndirect(uint32_t data_offset, uint32_t draw_initiato const auto* args_addr = reinterpret_cast<const void*>(m_draw_indirect_args_base_addr + data_offset); + // Research: the GPU reads its own arguments. A CPU read of arguments an earlier GPU pass + // wrote faults on the tracked page and drains the whole queue, once per draw. 8-bit indices + // (expanded on the host) and an unknown index buffer size keep the CPU read. + if (!indexed) { + DrawIndexAuto({.vertex_count = 1, + .instance_count = 1, + .offset_source = DrawOffsetSource::IndirectArgs, + .gpu_args = reinterpret_cast<uint64_t>(args_addr)}); + return; + } + if (m_index_buffer_size != 0 && (m_index_type_and_size == 0 || m_index_type_and_size == 1)) { + DrawIndex({.index_count = m_index_buffer_size, + .index_addr = reinterpret_cast<const void*>(m_index_base_addr), + .instance_count = 1, + .offset_source = DrawOffsetSource::IndirectArgs, + .gpu_args = reinterpret_cast<uint64_t>(args_addr)}); + return; + } + ``` _🎯 Functional Correctness_ | _🟡 Minor_ | _⚡ Quick win_ <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash #!/bin/bash rg -nP -C3 '\bm_num_instances\b' src/graphics/guest_gpu ``` Repository: KytyPS5/KytyPS5 Length of output: 4811 --- 🏁 Script executed: ```bash #!/bin/bash printf '%s\n' '--- graphicsRun.cpp 920-1160 ---' sed -n '920,1160p' src/graphics/guest_gpu/graphicsRun.cpp printf '%s\n' '--- graphicsRun.cpp 1160-1320 ---' sed -n '1160,1320p' src/graphics/guest_gpu/graphicsRun.cpp printf '%s\n' '--- commandProcessor.h 155-185 ---' sed -n '155,185p' src/graphics/guest_gpu/command_processor/commandProcessor.h printf '%s\n' '--- diff base..head for relevant file ---' git diff --unified=35 05057c9441dbf3972d49f9143b90213a43a01a00 d6ec3a42ed19d0f16bb3e184ca57e20cce8d5176 -- src/graphics/guest_gpu/graphicsRun.cpp src/graphics/guest_gpu/command_processor/commandProcessor.h ``` Repository: KytyPS5/KytyPS5 Length of output: 42875 --- </details> **Preserve the persistent instance count for GPU indirect draws.** The GPU branches pass `instance_count = 1` and return without updating `m_num_instances`. A later `DrawIndex` or `DrawIndexAuto` with `instance_count == 0` can therefore use the count from before the indirect draw. Preserve the state update, or retain the CPU path when the GPU path cannot provide it. Remove the unreachable non-indexed CPU branch. <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:c5f2d95457a8178a9ef14098 --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -1433,0 +1581,4 @@
LibKernel::Memory::WriteBacking(reinterpret_cast<uint64_t>(dst), &data, bytes);
renderer.GetGpu().Wake();
});
}
Author
Owner

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

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Deferred label callbacks can run after GuestGpu is destroyed.

Two callbacks run on the scheduler priority thread and use GuestGpu:

  • PublishLabelAtCompletion calls renderer.GetGpu().Wake().
  • DeferLabelWrite (Lines 179-188) captures this and calls TrySendCommand.

RenderContext::ShutdownGpu (src/graphics/host_gpu/renderer/renderContext.cpp, Lines 37-49) calls m_gpu->Shutdown() and then m_gpu.reset(). It calls m_command_scheduler.DrainPriorityOperations() only after that. ThreadRun stops with BufferWait() → Finish(), and Finish() does not wait for priority operations.

A label callback that is queued or running when m_gpu.reset() executes has two outcomes:

  • GetGpu() exits because m_gpu == nullptr.
  • TrySendCommand runs on a freed GuestGpu (use-after-free).

This happens at shutdown whenever KYTY_LABELS_AFTER_GPU or KYTY_LABELS_AT_COMPLETION is set. Drain the priority operations after the GPU thread joins and before m_gpu.reset(). TrySendCommand already returns false once m_accepting is false, so a late label write is dropped safely.

🐛 Proposed fix (src/graphics/host_gpu/renderer/renderContext.cpp)
 void RenderContext::ShutdownGpu() {
 	if (m_gpu != nullptr) {
 		m_gpu->Shutdown();
+		// Label publications capture the GuestGpu; finish them before it is destroyed.
+		m_command_scheduler.DrainPriorityOperations();
 		m_gpu.reset();
 	}
**@⁠coderabbitai[bot]** on GitHub · 2026-09-30 00:19 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/937#discussion_r4139620594) _🩺 Stability & Availability_ | _🟠 Major_ | _⚡ Quick win_ **Deferred label callbacks can run after `GuestGpu` is destroyed.** Two callbacks run on the scheduler priority thread and use `GuestGpu`: - `PublishLabelAtCompletion` calls `renderer.GetGpu().Wake()`. - `DeferLabelWrite` (Lines 179-188) captures `this` and calls `TrySendCommand`. `RenderContext::ShutdownGpu` (`src/graphics/host_gpu/renderer/renderContext.cpp`, Lines 37-49) calls `m_gpu->Shutdown()` and then `m_gpu.reset()`. It calls `m_command_scheduler.DrainPriorityOperations()` only after that. `ThreadRun` stops with `BufferWait()` → `Finish()`, and `Finish()` does not wait for priority operations. A label callback that is queued or running when `m_gpu.reset()` executes has two outcomes: - `GetGpu()` exits because `m_gpu == nullptr`. - `TrySendCommand` runs on a freed `GuestGpu` (use-after-free). This happens at shutdown whenever `KYTY_LABELS_AFTER_GPU` or `KYTY_LABELS_AT_COMPLETION` is set. Drain the priority operations after the GPU thread joins and before `m_gpu.reset()`. `TrySendCommand` already returns false once `m_accepting` is false, so a late label write is dropped safely. <details> <summary>🐛 Proposed fix (src/graphics/host_gpu/renderer/renderContext.cpp)</summary> ```diff void RenderContext::ShutdownGpu() { if (m_gpu != nullptr) { m_gpu->Shutdown(); + // Label publications capture the GuestGpu; finish them before it is destroyed. + m_command_scheduler.DrainPriorityOperations(); m_gpu.reset(); } ``` </details> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:e63fb9b79bd5db2ee7b4aa5b --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-30 00:19 UTC · original
On src/graphics/host_gpu/memoryTracker.h line 41 (outdated):

@@ -29,6 +29,16 @@ class MemoryTracker final {
 	void               MarkRegionAsGpuModified(uint64_t vaddr, uint64_t size);
 	void               UnmarkRegionAsGpuModified(uint64_t vaddr, uint64_t size);
 	void               UntrackMemory(uint64_t vaddr, uint64_t size);
+	// Calls func(address, bytes) for each part of the range, one per tracker region, that may
+	// hold CPU-dirty pages (lock-free summaries: false is exact, true is conservative).
+	template <typename Func>
+	void ForEachMaybeCpuDirtyRegion(uint64_t vaddr, uint64_t size, Func&& func) {
+		Iterate<false>(vaddr, size, [&](RegionManager* manager, uint64_t offset, uint64_t bytes) {
+			if (manager->MaybeModified<DirtySource::Cpu>()) {
+				func(manager->GetCpuAddr() + offset, bytes);
+			}
+		});
+	}

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

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
rg -nP -B3 -A40 'bool\s+create_region_on_fail|Iterate\s*\(' src/graphics/host_gpu/memoryTracker.h

Repository: KytyPS5/KytyPS5

Length of output: 1748


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- memoryTracker.h ---'
cat -n src/graphics/host_gpu/memoryTracker.h | sed -n '1,180p'
printf '%s\n' '--- relevant symbols ---'
rg -n -S -B5 -A20 'ForEachMaybeCpuDirtyRegion|ForEachUploadRange|SynchronizeCpuDirtyBuffersInRange|PrepareBda|BufferCache::Register|RegionManager|FindBuffer' src/graphics/host_gpu
printf '%s\n' '--- PR diff ---'
git diff --stat 05057c9441dbf3972d49f9143b90213a43a01a00 d6ec3a42ed19d0f16bb3e184ca57e20cce8d5176 -- src/graphics/host_gpu
git diff --unified=35 05057c9441dbf3972d49f9143b90213a43a01a00 d6ec3a42ed19d0f16bb3e184ca57e20cce8d5176 -- src/graphics/host_gpu/memoryTracker.h src/graphics/host_gpu/memoryTracker.cpp src/graphics/host_gpu/bufferCache.cpp src/graphics/host_gpu/bufferCache.h | sed -n '1,1000p'

Repository: KytyPS5/KytyPS5

Length of output: 42296


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- regionManager.h ---'
cat -n src/graphics/host_gpu/regionManager.h | sed -n '1,260p'
printf '%s\n' '--- buffer cache synchronization and registration ---'
rg -n -S -B12 -A45 'Register\(|SynchronizeCpuDirtyBuffersInRange|SynchronizeBuffersInRange|ForEachMaybeCpuDirtyRegion|ForEachUploadRange|PrepareBda' src/graphics/host_gpu/renderer/cache/bufferCache.cpp src/graphics/host_gpu/renderer/cache/bufferCache.h src/graphics/host_gpu/renderer/context.cpp
printf '%s\n' '--- context PrepareBda callers ---'
rg -n -S -B15 -A35 'PrepareBda\(' src/graphics/host_gpu/renderer src/graphics/host_gpu/graphicContext.h

Repository: KytyPS5/KytyPS5

Length of output: 42040


🏁 Script executed:

#!/bin/bash
set -e
rg -n -S -B12 -A55 'SynchronizeCpuDirtyBuffersInRange|SynchronizeBuffersInRange|FindBuffer\(' src/graphics/host_gpu/renderer/cache/bufferCache.cpp

Repository: KytyPS5/KytyPS5

Length of output: 12256


Create missing tracker regions in ForEachMaybeCpuDirtyRegion.

When ForEachMaybeCpuDirtyRegion encounters an uncreated region, it skips that region. BufferCache::Register does not create a tracker region, while a new RegionManager starts with all CPU pages dirty. Therefore, PrepareBda can miss a newly registered buffer and mark the CPU-dirty epoch as synchronized without uploading its contents.

Use Iterate<true> so the helper creates missing regions and processes their initial CPU-dirty state.

🐛 Suggested fix
-		Iterate<false>(vaddr, size, [&](RegionManager* manager, uint64_t offset, uint64_t bytes) {
+		Iterate<true>(vaddr, size, [&](RegionManager* manager, uint64_t offset, uint64_t bytes) {
📝 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.

	// Calls func(address, bytes) for each part of the range, one per tracker region, that may
	// hold CPU-dirty pages (lock-free summaries: false is exact, true is conservative).
	template <typename Func>
	void ForEachMaybeCpuDirtyRegion(uint64_t vaddr, uint64_t size, Func&& func) {
		Iterate<true>(vaddr, size, [&](RegionManager* manager, uint64_t offset, uint64_t bytes) {
			if (manager->MaybeModified<DirtySource::Cpu>()) {
				func(manager->GetCpuAddr() + offset, bytes);
			}
		});
	}
**@⁠coderabbitai[bot]** on GitHub · 2026-09-30 00:19 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/937#discussion_r4139620599) On `src/graphics/host_gpu/memoryTracker.h` line 41 (outdated): ```diff @@ -29,6 +29,16 @@ class MemoryTracker final { void MarkRegionAsGpuModified(uint64_t vaddr, uint64_t size); void UnmarkRegionAsGpuModified(uint64_t vaddr, uint64_t size); void UntrackMemory(uint64_t vaddr, uint64_t size); + // Calls func(address, bytes) for each part of the range, one per tracker region, that may + // hold CPU-dirty pages (lock-free summaries: false is exact, true is conservative). + template <typename Func> + void ForEachMaybeCpuDirtyRegion(uint64_t vaddr, uint64_t size, Func&& func) { + Iterate<false>(vaddr, size, [&](RegionManager* manager, uint64_t offset, uint64_t bytes) { + if (manager->MaybeModified<DirtySource::Cpu>()) { + func(manager->GetCpuAddr() + offset, bytes); + } + }); + } ``` _🗄️ Data Integrity & Integration_ | _🟠 Major_ | _⚡ Quick win_ <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash #!/bin/bash rg -nP -B3 -A40 'bool\s+create_region_on_fail|Iterate\s*\(' src/graphics/host_gpu/memoryTracker.h ``` Repository: KytyPS5/KytyPS5 Length of output: 1748 --- 🏁 Script executed: ```bash #!/bin/bash set -e printf '%s\n' '--- memoryTracker.h ---' cat -n src/graphics/host_gpu/memoryTracker.h | sed -n '1,180p' printf '%s\n' '--- relevant symbols ---' rg -n -S -B5 -A20 'ForEachMaybeCpuDirtyRegion|ForEachUploadRange|SynchronizeCpuDirtyBuffersInRange|PrepareBda|BufferCache::Register|RegionManager|FindBuffer' src/graphics/host_gpu printf '%s\n' '--- PR diff ---' git diff --stat 05057c9441dbf3972d49f9143b90213a43a01a00 d6ec3a42ed19d0f16bb3e184ca57e20cce8d5176 -- src/graphics/host_gpu git diff --unified=35 05057c9441dbf3972d49f9143b90213a43a01a00 d6ec3a42ed19d0f16bb3e184ca57e20cce8d5176 -- src/graphics/host_gpu/memoryTracker.h src/graphics/host_gpu/memoryTracker.cpp src/graphics/host_gpu/bufferCache.cpp src/graphics/host_gpu/bufferCache.h | sed -n '1,1000p' ``` Repository: KytyPS5/KytyPS5 Length of output: 42296 --- 🏁 Script executed: ```bash #!/bin/bash set -e printf '%s\n' '--- regionManager.h ---' cat -n src/graphics/host_gpu/regionManager.h | sed -n '1,260p' printf '%s\n' '--- buffer cache synchronization and registration ---' rg -n -S -B12 -A45 'Register\(|SynchronizeCpuDirtyBuffersInRange|SynchronizeBuffersInRange|ForEachMaybeCpuDirtyRegion|ForEachUploadRange|PrepareBda' src/graphics/host_gpu/renderer/cache/bufferCache.cpp src/graphics/host_gpu/renderer/cache/bufferCache.h src/graphics/host_gpu/renderer/context.cpp printf '%s\n' '--- context PrepareBda callers ---' rg -n -S -B15 -A35 'PrepareBda\(' src/graphics/host_gpu/renderer src/graphics/host_gpu/graphicContext.h ``` Repository: KytyPS5/KytyPS5 Length of output: 42040 --- 🏁 Script executed: ```bash #!/bin/bash set -e rg -n -S -B12 -A55 'SynchronizeCpuDirtyBuffersInRange|SynchronizeBuffersInRange|FindBuffer\(' src/graphics/host_gpu/renderer/cache/bufferCache.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 12256 --- </details> **Create missing tracker regions in `ForEachMaybeCpuDirtyRegion`.** When `ForEachMaybeCpuDirtyRegion` encounters an uncreated region, it skips that region. `BufferCache::Register` does not create a tracker region, while a new `RegionManager` starts with all CPU pages dirty. Therefore, `PrepareBda` can miss a newly registered buffer and mark the CPU-dirty epoch as synchronized without uploading its contents. Use `Iterate<true>` so the helper creates missing regions and processes their initial CPU-dirty state. <details> <summary>🐛 Suggested fix</summary> ```diff - Iterate<false>(vaddr, size, [&](RegionManager* manager, uint64_t offset, uint64_t bytes) { + Iterate<true>(vaddr, size, [&](RegionManager* manager, uint64_t offset, uint64_t bytes) { ``` </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 // Calls func(address, bytes) for each part of the range, one per tracker region, that may // hold CPU-dirty pages (lock-free summaries: false is exact, true is conservative). template <typename Func> void ForEachMaybeCpuDirtyRegion(uint64_t vaddr, uint64_t size, Func&& func) { Iterate<true>(vaddr, size, [&](RegionManager* manager, uint64_t offset, uint64_t bytes) { if (manager->MaybeModified<DirtySource::Cpu>()) { func(manager->GetCpuAddr() + offset, bytes); } }); } ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:a7b009f67413a30aed326a93 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-30 00:19 UTC · original
On src/graphics/host_gpu/pageManager.cpp line 300 (outdated):

@@ -290,6 +290,15 @@ void PageManager::UpdatePageWatchers(uint64_t vaddr, uint64_t size) {
 template void PageManager::UpdatePageWatchers<true>(uint64_t, uint64_t);
 template void PageManager::UpdatePageWatchers<false>(uint64_t, uint64_t);
 
+bool PageManager::IsReadWatched(uint64_t vaddr) const noexcept {
+	const auto* region = m_impl->FindRegion(vaddr);
+	if (region == nullptr) {
+		return false;
+	}
+	const auto index = static_cast<size_t>((vaddr % REGION_SIZE) / PAGE_SIZE);
+	return region->pages[index].access_watchers != 0;
+}

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Read access_watchers atomically; the unlocked read is a data race.

CanServeCleanRead is documented as callable from any thread. It calls IsReadWatched, which reads the access_watchers bit-field without region->lock.

UpdateRegionWatchers changes the same byte under SpinGuard on another thread. The byte also holds write_watchers. The header comment calls the result "a hint", but a concurrent non-atomic read and write of the same memory location is undefined behavior in C++. It is not only a stale value.

Read the whole PageState byte with std::atomic_ref<uint8_t> (relaxed) and extract the bit. Make every writer use the same atomic view, or do all writes under the lock while readers use atomic_ref. Do not take the spin lock here, because the function can run inside a fault handler.

Based on learnings: "when a non-atomic type ... is written by one thread and read by another without a mutex, atomic wrapper, or other explicit synchronization, this is a genuine data race (undefined behavior)".

Source: Learnings

**@⁠coderabbitai[bot]** on GitHub · 2026-09-30 00:19 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/937#discussion_r4139620625) On `src/graphics/host_gpu/pageManager.cpp` line 300 (outdated): ```diff @@ -290,6 +290,15 @@ void PageManager::UpdatePageWatchers(uint64_t vaddr, uint64_t size) { template void PageManager::UpdatePageWatchers<true>(uint64_t, uint64_t); template void PageManager::UpdatePageWatchers<false>(uint64_t, uint64_t); +bool PageManager::IsReadWatched(uint64_t vaddr) const noexcept { + const auto* region = m_impl->FindRegion(vaddr); + if (region == nullptr) { + return false; + } + const auto index = static_cast<size_t>((vaddr % REGION_SIZE) / PAGE_SIZE); + return region->pages[index].access_watchers != 0; +} ``` _🩺 Stability & Availability_ | _🟡 Minor_ | _⚡ Quick win_ **Read `access_watchers` atomically; the unlocked read is a data race.** `CanServeCleanRead` is documented as callable from any thread. It calls `IsReadWatched`, which reads the `access_watchers` bit-field without `region->lock`. `UpdateRegionWatchers` changes the same byte under `SpinGuard` on another thread. The byte also holds `write_watchers`. The header comment calls the result "a hint", but a concurrent non-atomic read and write of the same memory location is undefined behavior in C++. It is not only a stale value. Read the whole `PageState` byte with `std::atomic_ref<uint8_t>` (relaxed) and extract the bit. Make every writer use the same atomic view, or do all writes under the lock while readers use `atomic_ref`. Do not take the spin lock here, because the function can run inside a fault handler. Based on learnings: "when a non-atomic type ... is written by one thread and read by another without a mutex, atomic wrapper, or other explicit synchronization, this is a genuine data race (undefined behavior)". <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:c3e2a91fb8259307d6b24c8f --> _Source: Learnings_ <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-30 00:19 UTC · original
On src/graphics/host_gpu/renderer/pipeline/bindlessTable.cpp line 601 (outdated):

@@ -0,0 +1,603 @@
+#include "graphics/host_gpu/renderer/pipeline/bindlessTable.h"
+
+#include "common/assert.h"
+#include "common/logging/log.h"
+#include "common/threads.h"
+#include "graphics/host_gpu/graphicContext.h"
+#include "graphics/host_gpu/renderer/cache/samplerCache.h"
+#include "graphics/host_gpu/renderer/commandScheduler.h"
+#include "graphics/host_gpu/vulkanCommon.h"
+#include "graphics/shader/shaderBindings.h"
+
+#include <algorithm>
+#include <atomic>
+#include <cinttypes>
+#include <array>
+#include <atomic>
+#include <fmt/format.h>
+#include <string>
+#include <cstdlib>
+
+namespace Libs::Graphics {
+
+BindlessTable::BindlessTable(GraphicContext& graphics, CommandScheduler& scheduler)
+    : m_graphics(graphics) {
+	if (!graphics.bindless_enabled) {
+		return;
+	}
+	m_images_per_array =
+	    std::min(MaxImagesPerArray, graphics.bindless_max_sampled_images / ImageArrays);
+	if (m_images_per_array == 0) {
+		LOGF("Bindless table: the device allows no update-after-bind sampled images\n");
+		return;
+	}
+
+	constexpr auto image_flags = vk::DescriptorBindingFlagBits::ePartiallyBound |
+	                             vk::DescriptorBindingFlagBits::eUpdateAfterBind |
+	                             vk::DescriptorBindingFlagBits::eUpdateUnusedWhilePending;
+	// The buffers are written once, here, so they need no update-after-bind.
+	constexpr auto buffer_flags = vk::DescriptorBindingFlags {};
+	// A device without update-after-bind samplers still gets a one-entry array, holding the
+	// default sampler, so every bindless pipeline sees the same layout.
+	m_samplers_per_array = std::min(MaxSamplers, graphics.bindless_max_samplers);
+	const std::array<vk::DescriptorSetLayoutBinding, 7> bindings {{
+	    {Images2D, vk::DescriptorType::eSampledImage, m_images_per_array, vk::ShaderStageFlagBits::eAll,
+	     nullptr},
+	    {Images2DArray, vk::DescriptorType::eSampledImage, m_images_per_array,
+	     vk::ShaderStageFlagBits::eAll, nullptr},
+	    {ImagesCube, vk::DescriptorType::eSampledImage, m_images_per_array,
+	     vk::ShaderStageFlagBits::eAll, nullptr},
+	    {Images3D, vk::DescriptorType::eSampledImage, m_images_per_array, vk::ShaderStageFlagBits::eAll,
+	     nullptr},
+	    {Translation, vk::DescriptorType::eStorageBuffer, 1, vk::ShaderStageFlagBits::eAll, nullptr},
+	    {Feedback, vk::DescriptorType::eStorageBuffer, 1, vk::ShaderStageFlagBits::eAll, nullptr},
+	    {Samplers, vk::DescriptorType::eSampler, std::max(m_samplers_per_array, 1u),
+	     vk::ShaderStageFlagBits::eAll, nullptr},
+	}};
+	const std::array<vk::DescriptorBindingFlags, 7> binding_flags {
+	    image_flags, image_flags, image_flags, image_flags, buffer_flags, buffer_flags, image_flags};
+	vk::DescriptorSetLayoutBindingFlagsCreateInfo flags_info {};
+	flags_info.bindingCount  = static_cast<uint32_t>(binding_flags.size());
+	flags_info.pBindingFlags = binding_flags.data();
+	vk::DescriptorSetLayoutCreateInfo layout_info {};
+	layout_info.pNext        = &flags_info;
+	layout_info.flags        = vk::DescriptorSetLayoutCreateFlagBits::eUpdateAfterBindPool;
+	layout_info.bindingCount = static_cast<uint32_t>(bindings.size());
+	layout_info.pBindings    = bindings.data();
+	RequireVulkanSuccess(graphics.device.createDescriptorSetLayout(&layout_info, nullptr, &m_layout),
+	                     "create bindless descriptor layout");
+
+	const std::array<vk::DescriptorPoolSize, 3> sizes {{
+	    {vk::DescriptorType::eSampledImage, m_images_per_array * ImageArrays},
+	    {vk::DescriptorType::eStorageBuffer, 2},
+	    {vk::DescriptorType::eSampler, std::max(m_samplers_per_array, 1u)},
+	}};
+	vk::DescriptorPoolCreateInfo pool_info {};
+	pool_info.flags         = vk::DescriptorPoolCreateFlagBits::eUpdateAfterBind;
+	pool_info.maxSets       = 1;
+	pool_info.poolSizeCount = static_cast<uint32_t>(sizes.size());
+	pool_info.pPoolSizes    = sizes.data();
+	RequireVulkanSuccess(graphics.device.createDescriptorPool(&pool_info, nullptr, &m_pool),
+	                     "create bindless descriptor pool");
+
+	vk::DescriptorSetAllocateInfo allocate_info {};
+	allocate_info.descriptorPool     = m_pool;
+	allocate_info.descriptorSetCount = 1;
+	allocate_info.pSetLayouts        = &m_layout;
+	RequireVulkanSuccess(graphics.device.allocateDescriptorSets(&allocate_info, &m_set),
+	                     "allocate bindless descriptor set");
+
+	// Both live in host-visible device memory: the host writes translations and clears feedback
+	// flags directly, while shaders access them at device speed. The host reads the flags from
+	// a host-cached snapshot (RecordFeedbackSnapshot).
+	m_translation = std::make_unique<Buffer>(graphics, scheduler, MemoryUsage::Stream, 0,
+	                                         AllFlags, TranslationEntries * sizeof(uint32_t));
+	m_feedback    = std::make_unique<Buffer>(graphics, scheduler, MemoryUsage::Stream, 0,
+	                                         AllFlags, TranslationEntries * sizeof(uint32_t));
+	m_feedback_snapshot = std::make_unique<Buffer>(graphics, scheduler, MemoryUsage::Download, 0,
+	                                               AllFlags, TranslationEntries * sizeof(uint32_t));
+	EXIT_IF(m_translation->Mapped().empty() || m_feedback->Mapped().empty() ||
+	        m_feedback_snapshot->Mapped().empty());
+	// A region allocated after a snapshot was recorded reads as "no requests" until the next.
+	std::fill(m_feedback_snapshot->Mapped().begin(), m_feedback_snapshot->Mapped().end(),
+	          uint8_t {0});
+	m_feedback_snapshot->Flush(0, m_feedback_snapshot->Size());
+	SetVulkanObjectNameF(graphics.device, m_translation->Handle(), "Bindless Translation");
+	SetVulkanObjectNameF(graphics.device, m_feedback->Handle(), "Bindless Feedback");
+
+	const std::array<vk::DescriptorBufferInfo, 2> buffer_infos {{
+	    {m_translation->Handle(), 0, VK_WHOLE_SIZE},
+	    {m_feedback->Handle(), 0, VK_WHOLE_SIZE},
+	}};
+	std::array<vk::WriteDescriptorSet, 2> writes {};
+	for (uint32_t i = 0; i < writes.size(); i++) {
+		writes[i].dstSet          = m_set;
+		writes[i].dstBinding      = Translation + i;
+		writes[i].descriptorCount = 1;
+		writes[i].descriptorType  = vk::DescriptorType::eStorageBuffer;
+		writes[i].pBufferInfo     = &buffer_infos[i];
+	}
+	graphics.device.updateDescriptorSets(static_cast<uint32_t>(writes.size()), writes.data(), 0,
+	                                     nullptr);
+	CreatePlaceholders(scheduler);
+	graphics.bindless_layout = m_layout;
+	graphics.bindless_set    = m_set;
+	LOGF("Bindless table: %u images per array, %u translation entries, %u samplers\n",
+	     m_images_per_array, TranslationEntries, m_samplers_per_array);
+}
+
+BindlessTable::SamplerHeap* BindlessTable::FindOrCreateSamplerHeap(uint64_t base,
+                                                                   uint32_t table_offset,
+                                                                   uint32_t flags) {
+	for (auto& heap: m_sampler_heaps) {
+		if (heap.base == base && heap.table_offset == table_offset && heap.flags == flags) {
+			return &heap;
+		}
+	}
+	auto& heap        = m_sampler_heaps.emplace_back();
+	heap.base         = base;
+	heap.table_offset = table_offset;
+	heap.flags        = flags;
+	return &heap;
+}
+
+void BindlessTable::WriteDefaultSampler(vk::Sampler sampler) {
+	if (m_default_sampler_written || m_set == nullptr) {
+		return;
+	}
+	vk::DescriptorImageInfo info {sampler, nullptr, vk::ImageLayout::eUndefined};
+	vk::WriteDescriptorSet  write {};
+	write.dstSet          = m_set;
+	write.dstBinding      = Samplers;
+	write.dstArrayElement = 0;
+	write.descriptorCount = 1;
+	write.descriptorType  = vk::DescriptorType::eSampler;
+	write.pImageInfo      = &info;
+	m_graphics.device.updateDescriptorSets(1, &write, 0, nullptr);
+	m_default_sampler_written = true;
+}
+
+bool BindlessTable::MirrorSamplerHeap(SamplerHeap&                              heap,
+                                      std::span<const std::array<uint32_t, 4>> records,
+                                      SamplerCache&                             cache) {
+	const auto same_prefix =
+	    records.size() >= heap.records.size() &&
+	    std::equal(heap.records.begin(), heap.records.end(), records.begin());
+	if (same_prefix && records.size() == heap.records.size()) {
+		return true;
+	}
+	uint32_t first = static_cast<uint32_t>(heap.records.size());
+	if (!same_prefix || records.size() > heap.capacity || heap.region == 0) {
+		const auto capacity = std::max<uint32_t>(64u, static_cast<uint32_t>(records.size()) * 2u);
+		if (m_samplers_per_array <= 1u || capacity > m_samplers_per_array - m_next_sampler_slot) {
+			static std::atomic<uint32_t> reported = 0;
+			if (reported.fetch_add(1) < 8) {
+				LOGF("Bindless samplers: array full (%u of %u slots), heap 0x%016" PRIx64
+				     " keeps %zu records\n",
+				     m_next_sampler_slot, m_samplers_per_array, heap.base, heap.records.size());
+			}
+			return false;
+		}
+		heap.region   = m_next_sampler_slot;
+		heap.capacity = capacity;
+		m_next_sampler_slot += capacity;
+		first = 0;
+	}
+	std::vector<vk::DescriptorImageInfo> infos;
+	infos.reserve(records.size() - first);
+	for (size_t key = first; key < records.size(); key++) {
+		ShaderSamplerResource descriptor;
+		std::copy(records[key].begin(), records[key].end(), descriptor.fields);
+		if ((heap.flags & SamplerDepthCompare) == 0u) {
+			descriptor.fields[0] &= ~(0x7u << 12u);
+		}
+		if ((heap.flags & SamplerPointFiltering) != 0u) {
+			descriptor.SetPointFiltering();
+		}
+		infos.push_back({cache.GetSampler(descriptor, (heap.flags & SamplerIntegerBorder) != 0u),
+		                 nullptr, vk::ImageLayout::eUndefined});
+	}
+	if (!infos.empty()) {
+		vk::WriteDescriptorSet write {};
+		write.dstSet          = m_set;
+		write.dstBinding      = Samplers;
+		write.dstArrayElement = heap.region + first;
+		write.descriptorCount = static_cast<uint32_t>(infos.size());
+		write.descriptorType  = vk::DescriptorType::eSampler;
+		write.pImageInfo      = infos.data();
+		m_graphics.device.updateDescriptorSets(1, &write, 0, nullptr);
+	}
+	static std::atomic<uint32_t> logged = 0;
+	if (logged.fetch_add(1) < 32) {
+		LOGF("Bindless samplers: heap 0x%016" PRIx64 "+0x%x flags=%u region=%u records=%zu"
+		     " (%u new)\n",
+		     heap.base, heap.table_offset, heap.flags, heap.region, records.size(),
+		     static_cast<uint32_t>(infos.size()));
+	}
+	heap.records.assign(records.begin(), records.end());
+	return true;
+}
+
+void BindlessTable::CreatePlaceholders(CommandScheduler& /*scheduler*/) {
+	struct Kind {
+		vk::ImageType        type;
+		vk::ImageViewType    view;
+		uint32_t             layers;
+		vk::ImageCreateFlags flags;
+	};
+	const std::array<Kind, ImageArrays> kinds {{
+	    {vk::ImageType::e2D, vk::ImageViewType::e2D, 1, {}},
+	    {vk::ImageType::e2D, vk::ImageViewType::e2DArray, 1, {}},
+	    {vk::ImageType::e2D, vk::ImageViewType::eCube, 6, vk::ImageCreateFlagBits::eCubeCompatible},
+	    {vk::ImageType::e3D, vk::ImageViewType::e3D, 1, {}},
+	}};
+	for (uint32_t i = 0; i < Placeholders; i++) {
+		vk::ImageCreateInfo info {};
+		info.flags         = kinds[i % ImageArrays].flags;
+		info.imageType     = kinds[i % ImageArrays].type;
+		info.format        = vk::Format::eR8G8B8A8Unorm;
+		info.extent        = vk::Extent3D {1, 1, 1};
+		info.mipLevels     = 1;
+		info.arrayLayers   = kinds[i % ImageArrays].layers;
+		info.samples       = vk::SampleCountFlagBits::e1;
+		info.tiling        = vk::ImageTiling::eOptimal;
+		info.usage         = vk::ImageUsageFlagBits::eSampled | vk::ImageUsageFlagBits::eTransferDst;
+		info.initialLayout = vk::ImageLayout::eUndefined;
+		EXIT_IF(!m_graphics.CreateImage(info, m_placeholders[i]));
+		vk::ImageViewCreateInfo view {};
+		view.image            = m_placeholders[i].image;
+		view.viewType         = kinds[i % ImageArrays].view;
+		view.format           = info.format;
+		view.subresourceRange = {vk::ImageAspectFlagBits::eColor, 0, 1, 0, kinds[i % ImageArrays].layers};
+		RequireVulkanSuccess(
+		    m_graphics.device.createImageView(&view, nullptr, &m_placeholder_views[i]),
+		    "create bindless placeholder view");
+	}
+
+	// One fenced submission, before any rendering: clears and a buffer fill are not allowed
+	// inside the render passes draws record into.
+	vk::CommandPoolCreateInfo pool_info {};
+	pool_info.flags            = vk::CommandPoolCreateFlagBits::eTransient;
+	pool_info.queueFamilyIndex = m_graphics.queue_family;
+	vk::CommandPool pool       = nullptr;
+	RequireVulkanSuccess(m_graphics.device.createCommandPool(&pool_info, nullptr, &pool),
+	                     "create bindless init pool");
+	vk::CommandBufferAllocateInfo allocate {};
+	allocate.commandPool        = pool;
+	allocate.level              = vk::CommandBufferLevel::ePrimary;
+	allocate.commandBufferCount = 1;
+	vk::CommandBuffer command   = nullptr;
+	RequireVulkanSuccess(m_graphics.device.allocateCommandBuffers(&allocate, &command),
+	                     "allocate bindless init command buffer");
+	vk::CommandBufferBeginInfo begin {};
+	begin.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit;
+	RequireVulkanSuccess(command.begin(&begin), "begin bindless init command buffer");
+
+	std::array<vk::ImageMemoryBarrier, Placeholders> to_transfer {};
+	std::array<vk::ImageMemoryBarrier, Placeholders> to_read {};
+	for (uint32_t i = 0; i < Placeholders; i++) {
+		const vk::ImageSubresourceRange range {vk::ImageAspectFlagBits::eColor, 0, 1, 0,
+		                                       kinds[i % ImageArrays].layers};
+		to_transfer[i].srcAccessMask       = {};
+		to_transfer[i].dstAccessMask       = vk::AccessFlagBits::eTransferWrite;
+		to_transfer[i].oldLayout           = vk::ImageLayout::eUndefined;
+		to_transfer[i].newLayout           = vk::ImageLayout::eTransferDstOptimal;
+		to_transfer[i].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
+		to_transfer[i].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
+		to_transfer[i].image               = m_placeholders[i].image;
+		to_transfer[i].subresourceRange    = range;
+		to_read[i]                         = to_transfer[i];
+		to_read[i].srcAccessMask           = vk::AccessFlagBits::eTransferWrite;
+		to_read[i].dstAccessMask           = vk::AccessFlagBits::eShaderRead;
+		to_read[i].oldLayout               = vk::ImageLayout::eTransferDstOptimal;
+		to_read[i].newLayout               = vk::ImageLayout::eShaderReadOnlyOptimal;
+	}
+	command.pipelineBarrier(vk::PipelineStageFlagBits::eTopOfPipe,
+	                        vk::PipelineStageFlagBits::eTransfer, {}, 0, nullptr, 0, nullptr,
+	                        Placeholders, to_transfer.data());
+	// Transparent black by default. KYTY_BINDLESS_DEBUG_COLORS=1: slot 0 grey (not resident), slot
+	// 1 red (key outside its heap), slot 2 blue (pending), to see which case a surface is in.
+	const bool debug_colors = std::getenv("KYTY_BINDLESS_DEBUG_COLORS") != nullptr;
+	const auto color        = [debug_colors](float r, float g, float b) {
+        return debug_colors ? vk::ClearColorValue {std::array<float, 4> {r, g, b, 1.0f}}
+		                           : vk::ClearColorValue {std::array<float, 4> {0.0f, 0.0f, 0.0f, 0.0f}};
+	};
+	const std::array<vk::ClearColorValue, PlaceholderColors> colors {
+	    color(0.5f, 0.5f, 0.5f), color(0.8f, 0.1f, 0.1f), color(0.1f, 0.2f, 0.8f)};
+	for (uint32_t i = 0; i < Placeholders; i++) {
+		command.clearColorImage(m_placeholders[i].image, vk::ImageLayout::eTransferDstOptimal,
+		                        &colors[i / ImageArrays], 1, &to_transfer[i].subresourceRange);
+	}
+	// translation[0], the entry of keys outside their heap, is the red slot.
+	command.fillBuffer(m_translation->Handle(), 4, VK_WHOLE_SIZE, 0u);
+	command.fillBuffer(m_translation->Handle(), 0, 4, 1u);
+	command.fillBuffer(m_feedback->Handle(), 0, VK_WHOLE_SIZE, 0u);
+	vk::BufferMemoryBarrier translation_ready {};
+	translation_ready.srcAccessMask       = vk::AccessFlagBits::eTransferWrite;
+	translation_ready.dstAccessMask       = vk::AccessFlagBits::eShaderRead;
+	translation_ready.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
+	translation_ready.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
+	translation_ready.buffer              = m_translation->Handle();
+	translation_ready.offset              = 0;
+	translation_ready.size                = VK_WHOLE_SIZE;
+	auto feedback_ready                   = translation_ready;
+	feedback_ready.dstAccessMask          = vk::AccessFlagBits::eShaderRead |
+	                                        vk::AccessFlagBits::eShaderWrite |
+	                                        vk::AccessFlagBits::eHostRead;
+	feedback_ready.buffer                 = m_feedback->Handle();
+	const std::array<vk::BufferMemoryBarrier, 2> buffers_ready {translation_ready, feedback_ready};
+	command.pipelineBarrier(vk::PipelineStageFlagBits::eTransfer,
+	                        vk::PipelineStageFlagBits::eAllCommands |
+	                            vk::PipelineStageFlagBits::eHost,
+	                        {}, 0, nullptr, static_cast<uint32_t>(buffers_ready.size()),
+	                        buffers_ready.data(), Placeholders, to_read.data());
+	RequireVulkanSuccess(command.end(), "end bindless init command buffer");
+
+	vk::FenceCreateInfo fence_info {};
+	vk::Fence           fence = nullptr;
+	RequireVulkanSuccess(m_graphics.device.createFence(&fence_info, nullptr, &fence),
+	                     "create bindless init fence");
+	vk::SubmitInfo submit {};
+	submit.commandBufferCount = 1;
+	submit.pCommandBuffers    = &command;
+	{
+		Common::LockGuard lock(m_graphics.queue_mutex);
+		RequireVulkanSuccess(m_graphics.queue.submit(1, &submit, fence), "submit bindless init");
+	}
+	RequireVulkanSuccess(m_graphics.device.waitForFences(1, &fence, VK_TRUE, UINT64_MAX),
+	                     "wait for bindless init");
+	m_graphics.device.destroyFence(fence, nullptr);
+	m_graphics.device.destroyCommandPool(pool, nullptr);
+
+	std::array<vk::DescriptorImageInfo, Placeholders> infos {};
+	std::array<vk::WriteDescriptorSet, Placeholders> writes {};
+	for (uint32_t i = 0; i < Placeholders; i++) {
+		infos[i]                  = {nullptr, m_placeholder_views[i],
+		                             vk::ImageLayout::eShaderReadOnlyOptimal};
+		writes[i].dstSet          = m_set;
+		writes[i].dstBinding      = Images2D + i % ImageArrays;
+		writes[i].dstArrayElement = i / ImageArrays;
+		writes[i].descriptorCount = 1;
+		writes[i].descriptorType  = vk::DescriptorType::eSampledImage;
+		writes[i].pImageInfo      = &infos[i];
+	}
+	m_graphics.device.updateDescriptorSets(Placeholders, writes.data(), 0, nullptr);
+}
+
+BindlessTable::~BindlessTable() {
+	for (uint32_t i = 0; i < Placeholders; i++) {
+		if (m_placeholder_views[i] != nullptr) {
+			m_graphics.device.destroyImageView(m_placeholder_views[i], nullptr);
+		}
+		if (m_placeholders[i].image != nullptr) {
+			m_graphics.DeleteImage(m_placeholders[i]);
+		}
+	}
+	m_translation.reset();
+	m_feedback.reset();
+	m_feedback_snapshot.reset();
+	if (m_pool != nullptr) {
+		m_graphics.device.destroyDescriptorPool(m_pool, nullptr);
+	}
+	if (m_layout != nullptr) {
+		m_graphics.device.destroyDescriptorSetLayout(m_layout, nullptr);
+	}
+}
+
+bool BindlessTable::AllocateRegion(Heap& heap, uint32_t entries) {
+	// Headroom so a growing heap rarely moves; a move re-writes the keys resolved so far.
+	const auto capacity = std::max(entries, std::min<uint32_t>(entries * 2u, 1u << 16u));
+	if (capacity > ShaderRecompiler::IR::WatchdogReportBase - m_next_region) {
+		return false;
+	}
+	const auto old_region  = heap.region;
+	const auto old_entries = heap.entries;
+	heap.region            = m_next_region;
+	heap.entries           = capacity;
+	m_next_region += capacity;
+	heap.slots.resize(capacity, 0u);
+	heap.settled.resize(capacity, 0u);
+	auto* translation = reinterpret_cast<uint32_t*>(m_translation->Mapped().data());
+	auto* feedback    = reinterpret_cast<uint32_t*>(m_feedback->Mapped().data());
+	for (uint32_t key = 0; key < capacity; key++) {
+		uint32_t value = ShaderRecompiler::IR::BindlessPending;
+		if (key < old_entries && heap.settled[key] != 0) {
+			value = heap.slots[key];
+		}
+		translation[heap.region + key] = value;
+		feedback[heap.region + key]    = 0;
+	}
+	if (!m_translation->IsCoherent()) {
+		m_translation->Flush(heap.region * sizeof(uint32_t), capacity * sizeof(uint32_t));
+	}
+	LOGF("Bindless heap region: base=0x%016" PRIx64 " binding=%u region=%u entries=%u (was %u at "
+	     "%u)\n",
+	     heap.base, heap.binding, heap.region, capacity, old_entries, old_region);
+	return true;
+}
+
+BindlessTable::Heap* BindlessTable::FindOrCreateHeap(
+    uint64_t base, uint32_t table_offset, uint32_t binding, uint32_t entries,
+    const ShaderRecompiler::IR::ImageResource& resource) {
+	if (entries == 0) {
+		return nullptr;
+	}
+	for (auto& heap: m_heaps) {
+		if (heap.base == base && heap.table_offset == table_offset && heap.binding == binding) {
+			if (entries > heap.entries && !AllocateRegion(heap, entries)) {
+				return nullptr;
+			}
+			return &heap;
+		}
+	}
+	auto& heap        = m_heaps.emplace_back();
+	heap.base         = base;
+	heap.table_offset = table_offset;
+	heap.binding      = binding;
+	heap.resource     = resource;
+	if (!AllocateRegion(heap, std::max(entries, 1u << 14u))) {
+		m_heaps.pop_back();
+		return nullptr;
+	}
+	return &heap;
+}
+
+uint32_t BindlessTable::AllocateSlot(uint32_t binding) {
+	if (binding >= ImageArrays || m_next_slot[binding] >= m_images_per_array) {
+		return 0;
+	}
+	return m_next_slot[binding]++;
+}
+
+void BindlessTable::WriteSlot(uint32_t binding, uint32_t slot, vk::ImageView view,
+                              vk::ImageLayout layout) {
+	const vk::DescriptorImageInfo info {nullptr, view, layout};
+	vk::WriteDescriptorSet        write {};
+	write.dstSet          = m_set;
+	write.dstBinding      = binding;
+	write.dstArrayElement = slot;
+	write.descriptorCount = 1;
+	write.descriptorType  = vk::DescriptorType::eSampledImage;
+	write.pImageInfo      = &info;
+	m_graphics.device.updateDescriptorSets(1, &write, 0, nullptr);
+}
+
+void BindlessTable::SetTranslation(const Heap& heap, uint32_t key, uint32_t slot) {
+	auto* translation = reinterpret_cast<uint32_t*>(m_translation->Mapped().data());
+	translation[heap.region + key] = slot;
+	if (!m_translation->IsCoherent()) {
+		m_translation->Flush((heap.region + key) * sizeof(uint32_t), sizeof(uint32_t));
+	}
+}
+
+void BindlessTable::RecordFeedbackSnapshot(CommandScheduler& scheduler) {
+	// Regions are allocated contiguously after word 0, so one copy covers every heap.
+	const vk::DeviceSize size = vk::DeviceSize {m_next_region} * sizeof(uint32_t);
+	scheduler.EndRendering();
+	auto                    command = scheduler.Current().Handle();
+	vk::BufferMemoryBarrier flags_written {};
+	flags_written.srcAccessMask       = vk::AccessFlagBits::eShaderWrite;
+	flags_written.dstAccessMask       = vk::AccessFlagBits::eTransferRead;
+	flags_written.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
+	flags_written.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
+	flags_written.buffer              = m_feedback->Handle();
+	flags_written.offset              = 0;
+	flags_written.size                = size;
+	command.pipelineBarrier(vk::PipelineStageFlagBits::eAllCommands,
+	                        vk::PipelineStageFlagBits::eTransfer, {}, 0, nullptr, 1,
+	                        &flags_written, 0, nullptr);
+	const vk::BufferCopy copy {0, 0, size};
+	command.copyBuffer(m_feedback->Handle(), m_feedback_snapshot->Handle(), 1, &copy);
+	auto snapshot_written          = flags_written;
+	snapshot_written.srcAccessMask = vk::AccessFlagBits::eTransferWrite;
+	snapshot_written.dstAccessMask = vk::AccessFlagBits::eHostRead;
+	snapshot_written.buffer        = m_feedback_snapshot->Handle();
+	command.pipelineBarrier(vk::PipelineStageFlagBits::eTransfer,
+	                        vk::PipelineStageFlagBits::eHost, {}, 0, nullptr, 1,
+	                        &snapshot_written, 0, nullptr);
+	m_snapshot_tick = scheduler.CurrentTick();
+}
+
+bool BindlessTable::SnapshotReady(CommandScheduler& scheduler) {
+	return m_snapshot_tick != 0 && scheduler.IsFree(m_snapshot_tick);
+}
+
+void BindlessTable::TakeRequests(const Heap& heap, std::vector<uint32_t>& keys) {
+	const auto* snapshot = reinterpret_cast<const uint32_t*>(m_feedback_snapshot->Mapped().data());
+	auto*       feedback = reinterpret_cast<uint32_t*>(m_feedback->Mapped().data());
+	m_feedback_snapshot->Invalidate(heap.region * sizeof(uint32_t),
+	                                heap.entries * sizeof(uint32_t));
+	bool cleared = false;
+	for (uint32_t key = 0; key < heap.entries; key++) {
+		if (snapshot[heap.region + key] != 0) {
+			// A flag the GPU sets again after the snapshot may be lost here; a key that is
+			// still pending is flagged again by the next draw that samples it.
+			feedback[heap.region + key] = 0;
+			keys.push_back(key);
+			cleared = true;
+		}
+	}
+	if (cleared) {
+		m_feedback->Flush(heap.region * sizeof(uint32_t), heap.entries * sizeof(uint32_t));
+	}
+}
+
+void BindlessTable::DrainWatchdogReports(uint64_t frame) {
+	using ShaderRecompiler::IR::WatchdogReportBase;
+	using ShaderRecompiler::IR::WatchdogReportPhis;
+	using ShaderRecompiler::IR::WatchdogReportSlots;
+	using ShaderRecompiler::IR::WatchdogReportWords;
+	static_assert(WatchdogReportBase + WatchdogReportWords * (WatchdogReportSlots + 1) <=
+	              TranslationEntries);
+	auto* feedback = reinterpret_cast<uint32_t*>(m_feedback->Mapped().data());
+	if (!m_feedback->IsCoherent()) {
+		m_feedback->Invalidate(WatchdogReportBase * sizeof(uint32_t),
+		                       WatchdogReportWords * (WatchdogReportSlots + 1) * sizeof(uint32_t));
+	}
+	const auto count = feedback[WatchdogReportBase];
+	if (count == 0) {
+		return;
+	}
+	const auto stored = std::min(count, WatchdogReportSlots);
+	// Per (shader, loop): how many tripped, and the first report in full.
+	std::unordered_map<uint64_t, std::pair<uint32_t, const uint32_t*>> loops;
+	for (uint32_t n = 0; n < stored; n++) {
+		const auto* report = feedback + WatchdogReportBase + WatchdogReportWords * (n + 1);
+		if ((report[0] >> 16u) != 0x5744u) {
+			continue;
+		}
+		const auto key = (static_cast<uint64_t>(report[2]) << 32u | report[1]) ^
+		                 (static_cast<uint64_t>(report[0] & 0xffffu) << 48u);
+		auto& entry = loops[key];
+		if (entry.first++ == 0) {
+			entry.second = report;
+		}
+	}
+	static std::atomic<uint32_t> logged = 0;
+	LOGF("WatchdogTrips: frame=%" PRIu64 " reports=%u loops=%zu\n", frame, count, loops.size());
+	for (const auto& [key, entry]: loops) {
+		if (logged.fetch_add(1) >= 256) {
+			break;
+		}
+		const auto* r = entry.second;
+		std::string phis;
+		for (uint32_t half = 0; half < 2; half++) {
+			phis += half == 0 ? " lo:" : " hi:";
+			for (uint32_t i = 0; i < WatchdogReportPhis; i++) {
+				phis += fmt::format(" {:x}", r[16 + half * WatchdogReportPhis + i]);
+			}
+		}
+		LOGF("WatchdogTrip: hash=0x%08x%08x loop_block=%u trips=%u counter=%u group=%u lane=%u "
+		     "ud=[%08x %08x %08x %08x %08x %08x %08x %08x]%s\n",
+		     r[2], r[1], r[0] & 0xffffu, entry.first, r[3], r[4], r[5], r[6], r[7], r[8], r[9],
+		     r[10], r[11], r[12], r[13], phis.c_str());
+	}
+	feedback[WatchdogReportBase] = 0;
+	if (!m_feedback->IsCoherent()) {
+		m_feedback->Flush(WatchdogReportBase * sizeof(uint32_t), sizeof(uint32_t));
+	}
+}
+
+void BindlessTable::AddImageReference(ImageId id, Heap& heap, uint32_t key) {
+	m_image_refs[ImageKey(id)].emplace_back(&heap, key);
+}
+
+void BindlessTable::OnImageUnregistered(ImageId id) {
+	const auto found = m_image_refs.find(ImageKey(id));
+	if (found == m_image_refs.end()) {
+		return;
+	}
+	for (const auto& [heap, key]: found->second) {
+		if (heap->slots[key] != 0) {
+			WriteSlot(heap->binding, heap->slots[key], m_placeholder_views[heap->binding],
+			          vk::ImageLayout::eShaderReadOnlyOptimal);
+		}
+		heap->slots[key]   = 0;
+		heap->settled[key] = 0;
+		SetTranslation(*heap, key, ShaderRecompiler::IR::BindlessPending);
+		std::erase(heap->resolved, id);
+	}
+	m_image_refs.erase(found);
+}

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

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
rg -nP -C6 '\bOnImageUnregistered\s*\(' src/graphics
rg -nP -C4 'bindless_pinned' src/graphics

Repository: KytyPS5/KytyPS5

Length of output: 7367


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- bindless diff ---'
git diff --unified=30 05057c9441dbf3972d49f9143b90213a43a01a00 d6ec3a42ed19d0f16bb3e184ca57e20cce8d5176 -- src/graphics/host_gpu/renderer/pipeline/bindlessTable.cpp src/graphics/host_gpu/renderer/pipeline/bindlessTable.h
printf '%s\n' '--- unregister lifecycle ---'
sed -n '210,280p' src/graphics/host_gpu/renderer/cache/textureCache.cpp
rg -n -P -C8 'Unregister|unregister|on_bindless_unregister|bindless_pinned|m_slot_images\.erase|slot_images' src/graphics/host_gpu/renderer/cache/textureCache.cpp
printf '%s\n' '--- bindless declarations and flags ---'
sed -n '100,175p' src/graphics/host_gpu/renderer/pipeline/bindlessTable.h
rg -n -P -C10 'eUpdateAfterBind|eUpdateUnusedWhilePending|eUpdateAfterBind' src/graphics/host_gpu/renderer/pipeline/bindlessTable.cpp src/graphics/host_gpu/renderer/pipeline/bindlessTable.h
printf '%s\n' '--- scheduler APIs and related deferred cleanup ---'
rg -n -P -C8 'SchedulerTick|scheduler tick|CurrentTick|last.*tick|retir|pending.*release|defer|SafeTo|WaitFor|IsFree|IsReady' src/graphics/host_gpu/renderer | head -n 500
printf '%s\n' '--- image destruction references ---'
rg -n -P -C8 'vk::ImageView|image_view|view.*destroy|destroy.*view|m_slot_images|UnregisterImage|RegisterImage' src/graphics/host_gpu/renderer/cache src/graphics/host_gpu/renderer/image src/graphics/host_gpu/renderer | head -n 500

Repository: KytyPS5/KytyPS5

Length of output: 42932


🤖 get_repo_knowledge executed:

get_repo_knowledge KytyPS5/KytyPS5 /tmp/coderabbit-repo-knowledge/kytyps5-kytyps5-b6cddd0b/architecture

Length of output: 42532


Defer bindless slot retirement until pending work completes.

TextureCache::UnregisterImage calls OnImageUnregistered immediately. That function updates the descriptor and translation for each referenced slot. A submitted draw may still use the slot. eUpdateUnusedWhilePending does not permit updates to descriptors used by pending work.

Defer the complete slot retirement, including the placeholder descriptor write, translation update, and state cleanup, until the scheduler confirms that the last submission using the slot has retired. DeleteImage already defers image destruction while the scheduler is active, but that does not make the descriptor update safe.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-30 00:19 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/937#discussion_r4139620629) On `src/graphics/host_gpu/renderer/pipeline/bindlessTable.cpp` line 601 (outdated): ```diff @@ -0,0 +1,603 @@ +#include "graphics/host_gpu/renderer/pipeline/bindlessTable.h" + +#include "common/assert.h" +#include "common/logging/log.h" +#include "common/threads.h" +#include "graphics/host_gpu/graphicContext.h" +#include "graphics/host_gpu/renderer/cache/samplerCache.h" +#include "graphics/host_gpu/renderer/commandScheduler.h" +#include "graphics/host_gpu/vulkanCommon.h" +#include "graphics/shader/shaderBindings.h" + +#include <algorithm> +#include <atomic> +#include <cinttypes> +#include <array> +#include <atomic> +#include <fmt/format.h> +#include <string> +#include <cstdlib> + +namespace Libs::Graphics { + +BindlessTable::BindlessTable(GraphicContext& graphics, CommandScheduler& scheduler) + : m_graphics(graphics) { + if (!graphics.bindless_enabled) { + return; + } + m_images_per_array = + std::min(MaxImagesPerArray, graphics.bindless_max_sampled_images / ImageArrays); + if (m_images_per_array == 0) { + LOGF("Bindless table: the device allows no update-after-bind sampled images\n"); + return; + } + + constexpr auto image_flags = vk::DescriptorBindingFlagBits::ePartiallyBound | + vk::DescriptorBindingFlagBits::eUpdateAfterBind | + vk::DescriptorBindingFlagBits::eUpdateUnusedWhilePending; + // The buffers are written once, here, so they need no update-after-bind. + constexpr auto buffer_flags = vk::DescriptorBindingFlags {}; + // A device without update-after-bind samplers still gets a one-entry array, holding the + // default sampler, so every bindless pipeline sees the same layout. + m_samplers_per_array = std::min(MaxSamplers, graphics.bindless_max_samplers); + const std::array<vk::DescriptorSetLayoutBinding, 7> bindings {{ + {Images2D, vk::DescriptorType::eSampledImage, m_images_per_array, vk::ShaderStageFlagBits::eAll, + nullptr}, + {Images2DArray, vk::DescriptorType::eSampledImage, m_images_per_array, + vk::ShaderStageFlagBits::eAll, nullptr}, + {ImagesCube, vk::DescriptorType::eSampledImage, m_images_per_array, + vk::ShaderStageFlagBits::eAll, nullptr}, + {Images3D, vk::DescriptorType::eSampledImage, m_images_per_array, vk::ShaderStageFlagBits::eAll, + nullptr}, + {Translation, vk::DescriptorType::eStorageBuffer, 1, vk::ShaderStageFlagBits::eAll, nullptr}, + {Feedback, vk::DescriptorType::eStorageBuffer, 1, vk::ShaderStageFlagBits::eAll, nullptr}, + {Samplers, vk::DescriptorType::eSampler, std::max(m_samplers_per_array, 1u), + vk::ShaderStageFlagBits::eAll, nullptr}, + }}; + const std::array<vk::DescriptorBindingFlags, 7> binding_flags { + image_flags, image_flags, image_flags, image_flags, buffer_flags, buffer_flags, image_flags}; + vk::DescriptorSetLayoutBindingFlagsCreateInfo flags_info {}; + flags_info.bindingCount = static_cast<uint32_t>(binding_flags.size()); + flags_info.pBindingFlags = binding_flags.data(); + vk::DescriptorSetLayoutCreateInfo layout_info {}; + layout_info.pNext = &flags_info; + layout_info.flags = vk::DescriptorSetLayoutCreateFlagBits::eUpdateAfterBindPool; + layout_info.bindingCount = static_cast<uint32_t>(bindings.size()); + layout_info.pBindings = bindings.data(); + RequireVulkanSuccess(graphics.device.createDescriptorSetLayout(&layout_info, nullptr, &m_layout), + "create bindless descriptor layout"); + + const std::array<vk::DescriptorPoolSize, 3> sizes {{ + {vk::DescriptorType::eSampledImage, m_images_per_array * ImageArrays}, + {vk::DescriptorType::eStorageBuffer, 2}, + {vk::DescriptorType::eSampler, std::max(m_samplers_per_array, 1u)}, + }}; + vk::DescriptorPoolCreateInfo pool_info {}; + pool_info.flags = vk::DescriptorPoolCreateFlagBits::eUpdateAfterBind; + pool_info.maxSets = 1; + pool_info.poolSizeCount = static_cast<uint32_t>(sizes.size()); + pool_info.pPoolSizes = sizes.data(); + RequireVulkanSuccess(graphics.device.createDescriptorPool(&pool_info, nullptr, &m_pool), + "create bindless descriptor pool"); + + vk::DescriptorSetAllocateInfo allocate_info {}; + allocate_info.descriptorPool = m_pool; + allocate_info.descriptorSetCount = 1; + allocate_info.pSetLayouts = &m_layout; + RequireVulkanSuccess(graphics.device.allocateDescriptorSets(&allocate_info, &m_set), + "allocate bindless descriptor set"); + + // Both live in host-visible device memory: the host writes translations and clears feedback + // flags directly, while shaders access them at device speed. The host reads the flags from + // a host-cached snapshot (RecordFeedbackSnapshot). + m_translation = std::make_unique<Buffer>(graphics, scheduler, MemoryUsage::Stream, 0, + AllFlags, TranslationEntries * sizeof(uint32_t)); + m_feedback = std::make_unique<Buffer>(graphics, scheduler, MemoryUsage::Stream, 0, + AllFlags, TranslationEntries * sizeof(uint32_t)); + m_feedback_snapshot = std::make_unique<Buffer>(graphics, scheduler, MemoryUsage::Download, 0, + AllFlags, TranslationEntries * sizeof(uint32_t)); + EXIT_IF(m_translation->Mapped().empty() || m_feedback->Mapped().empty() || + m_feedback_snapshot->Mapped().empty()); + // A region allocated after a snapshot was recorded reads as "no requests" until the next. + std::fill(m_feedback_snapshot->Mapped().begin(), m_feedback_snapshot->Mapped().end(), + uint8_t {0}); + m_feedback_snapshot->Flush(0, m_feedback_snapshot->Size()); + SetVulkanObjectNameF(graphics.device, m_translation->Handle(), "Bindless Translation"); + SetVulkanObjectNameF(graphics.device, m_feedback->Handle(), "Bindless Feedback"); + + const std::array<vk::DescriptorBufferInfo, 2> buffer_infos {{ + {m_translation->Handle(), 0, VK_WHOLE_SIZE}, + {m_feedback->Handle(), 0, VK_WHOLE_SIZE}, + }}; + std::array<vk::WriteDescriptorSet, 2> writes {}; + for (uint32_t i = 0; i < writes.size(); i++) { + writes[i].dstSet = m_set; + writes[i].dstBinding = Translation + i; + writes[i].descriptorCount = 1; + writes[i].descriptorType = vk::DescriptorType::eStorageBuffer; + writes[i].pBufferInfo = &buffer_infos[i]; + } + graphics.device.updateDescriptorSets(static_cast<uint32_t>(writes.size()), writes.data(), 0, + nullptr); + CreatePlaceholders(scheduler); + graphics.bindless_layout = m_layout; + graphics.bindless_set = m_set; + LOGF("Bindless table: %u images per array, %u translation entries, %u samplers\n", + m_images_per_array, TranslationEntries, m_samplers_per_array); +} + +BindlessTable::SamplerHeap* BindlessTable::FindOrCreateSamplerHeap(uint64_t base, + uint32_t table_offset, + uint32_t flags) { + for (auto& heap: m_sampler_heaps) { + if (heap.base == base && heap.table_offset == table_offset && heap.flags == flags) { + return &heap; + } + } + auto& heap = m_sampler_heaps.emplace_back(); + heap.base = base; + heap.table_offset = table_offset; + heap.flags = flags; + return &heap; +} + +void BindlessTable::WriteDefaultSampler(vk::Sampler sampler) { + if (m_default_sampler_written || m_set == nullptr) { + return; + } + vk::DescriptorImageInfo info {sampler, nullptr, vk::ImageLayout::eUndefined}; + vk::WriteDescriptorSet write {}; + write.dstSet = m_set; + write.dstBinding = Samplers; + write.dstArrayElement = 0; + write.descriptorCount = 1; + write.descriptorType = vk::DescriptorType::eSampler; + write.pImageInfo = &info; + m_graphics.device.updateDescriptorSets(1, &write, 0, nullptr); + m_default_sampler_written = true; +} + +bool BindlessTable::MirrorSamplerHeap(SamplerHeap& heap, + std::span<const std::array<uint32_t, 4>> records, + SamplerCache& cache) { + const auto same_prefix = + records.size() >= heap.records.size() && + std::equal(heap.records.begin(), heap.records.end(), records.begin()); + if (same_prefix && records.size() == heap.records.size()) { + return true; + } + uint32_t first = static_cast<uint32_t>(heap.records.size()); + if (!same_prefix || records.size() > heap.capacity || heap.region == 0) { + const auto capacity = std::max<uint32_t>(64u, static_cast<uint32_t>(records.size()) * 2u); + if (m_samplers_per_array <= 1u || capacity > m_samplers_per_array - m_next_sampler_slot) { + static std::atomic<uint32_t> reported = 0; + if (reported.fetch_add(1) < 8) { + LOGF("Bindless samplers: array full (%u of %u slots), heap 0x%016" PRIx64 + " keeps %zu records\n", + m_next_sampler_slot, m_samplers_per_array, heap.base, heap.records.size()); + } + return false; + } + heap.region = m_next_sampler_slot; + heap.capacity = capacity; + m_next_sampler_slot += capacity; + first = 0; + } + std::vector<vk::DescriptorImageInfo> infos; + infos.reserve(records.size() - first); + for (size_t key = first; key < records.size(); key++) { + ShaderSamplerResource descriptor; + std::copy(records[key].begin(), records[key].end(), descriptor.fields); + if ((heap.flags & SamplerDepthCompare) == 0u) { + descriptor.fields[0] &= ~(0x7u << 12u); + } + if ((heap.flags & SamplerPointFiltering) != 0u) { + descriptor.SetPointFiltering(); + } + infos.push_back({cache.GetSampler(descriptor, (heap.flags & SamplerIntegerBorder) != 0u), + nullptr, vk::ImageLayout::eUndefined}); + } + if (!infos.empty()) { + vk::WriteDescriptorSet write {}; + write.dstSet = m_set; + write.dstBinding = Samplers; + write.dstArrayElement = heap.region + first; + write.descriptorCount = static_cast<uint32_t>(infos.size()); + write.descriptorType = vk::DescriptorType::eSampler; + write.pImageInfo = infos.data(); + m_graphics.device.updateDescriptorSets(1, &write, 0, nullptr); + } + static std::atomic<uint32_t> logged = 0; + if (logged.fetch_add(1) < 32) { + LOGF("Bindless samplers: heap 0x%016" PRIx64 "+0x%x flags=%u region=%u records=%zu" + " (%u new)\n", + heap.base, heap.table_offset, heap.flags, heap.region, records.size(), + static_cast<uint32_t>(infos.size())); + } + heap.records.assign(records.begin(), records.end()); + return true; +} + +void BindlessTable::CreatePlaceholders(CommandScheduler& /*scheduler*/) { + struct Kind { + vk::ImageType type; + vk::ImageViewType view; + uint32_t layers; + vk::ImageCreateFlags flags; + }; + const std::array<Kind, ImageArrays> kinds {{ + {vk::ImageType::e2D, vk::ImageViewType::e2D, 1, {}}, + {vk::ImageType::e2D, vk::ImageViewType::e2DArray, 1, {}}, + {vk::ImageType::e2D, vk::ImageViewType::eCube, 6, vk::ImageCreateFlagBits::eCubeCompatible}, + {vk::ImageType::e3D, vk::ImageViewType::e3D, 1, {}}, + }}; + for (uint32_t i = 0; i < Placeholders; i++) { + vk::ImageCreateInfo info {}; + info.flags = kinds[i % ImageArrays].flags; + info.imageType = kinds[i % ImageArrays].type; + info.format = vk::Format::eR8G8B8A8Unorm; + info.extent = vk::Extent3D {1, 1, 1}; + info.mipLevels = 1; + info.arrayLayers = kinds[i % ImageArrays].layers; + info.samples = vk::SampleCountFlagBits::e1; + info.tiling = vk::ImageTiling::eOptimal; + info.usage = vk::ImageUsageFlagBits::eSampled | vk::ImageUsageFlagBits::eTransferDst; + info.initialLayout = vk::ImageLayout::eUndefined; + EXIT_IF(!m_graphics.CreateImage(info, m_placeholders[i])); + vk::ImageViewCreateInfo view {}; + view.image = m_placeholders[i].image; + view.viewType = kinds[i % ImageArrays].view; + view.format = info.format; + view.subresourceRange = {vk::ImageAspectFlagBits::eColor, 0, 1, 0, kinds[i % ImageArrays].layers}; + RequireVulkanSuccess( + m_graphics.device.createImageView(&view, nullptr, &m_placeholder_views[i]), + "create bindless placeholder view"); + } + + // One fenced submission, before any rendering: clears and a buffer fill are not allowed + // inside the render passes draws record into. + vk::CommandPoolCreateInfo pool_info {}; + pool_info.flags = vk::CommandPoolCreateFlagBits::eTransient; + pool_info.queueFamilyIndex = m_graphics.queue_family; + vk::CommandPool pool = nullptr; + RequireVulkanSuccess(m_graphics.device.createCommandPool(&pool_info, nullptr, &pool), + "create bindless init pool"); + vk::CommandBufferAllocateInfo allocate {}; + allocate.commandPool = pool; + allocate.level = vk::CommandBufferLevel::ePrimary; + allocate.commandBufferCount = 1; + vk::CommandBuffer command = nullptr; + RequireVulkanSuccess(m_graphics.device.allocateCommandBuffers(&allocate, &command), + "allocate bindless init command buffer"); + vk::CommandBufferBeginInfo begin {}; + begin.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit; + RequireVulkanSuccess(command.begin(&begin), "begin bindless init command buffer"); + + std::array<vk::ImageMemoryBarrier, Placeholders> to_transfer {}; + std::array<vk::ImageMemoryBarrier, Placeholders> to_read {}; + for (uint32_t i = 0; i < Placeholders; i++) { + const vk::ImageSubresourceRange range {vk::ImageAspectFlagBits::eColor, 0, 1, 0, + kinds[i % ImageArrays].layers}; + to_transfer[i].srcAccessMask = {}; + to_transfer[i].dstAccessMask = vk::AccessFlagBits::eTransferWrite; + to_transfer[i].oldLayout = vk::ImageLayout::eUndefined; + to_transfer[i].newLayout = vk::ImageLayout::eTransferDstOptimal; + to_transfer[i].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + to_transfer[i].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + to_transfer[i].image = m_placeholders[i].image; + to_transfer[i].subresourceRange = range; + to_read[i] = to_transfer[i]; + to_read[i].srcAccessMask = vk::AccessFlagBits::eTransferWrite; + to_read[i].dstAccessMask = vk::AccessFlagBits::eShaderRead; + to_read[i].oldLayout = vk::ImageLayout::eTransferDstOptimal; + to_read[i].newLayout = vk::ImageLayout::eShaderReadOnlyOptimal; + } + command.pipelineBarrier(vk::PipelineStageFlagBits::eTopOfPipe, + vk::PipelineStageFlagBits::eTransfer, {}, 0, nullptr, 0, nullptr, + Placeholders, to_transfer.data()); + // Transparent black by default. KYTY_BINDLESS_DEBUG_COLORS=1: slot 0 grey (not resident), slot + // 1 red (key outside its heap), slot 2 blue (pending), to see which case a surface is in. + const bool debug_colors = std::getenv("KYTY_BINDLESS_DEBUG_COLORS") != nullptr; + const auto color = [debug_colors](float r, float g, float b) { + return debug_colors ? vk::ClearColorValue {std::array<float, 4> {r, g, b, 1.0f}} + : vk::ClearColorValue {std::array<float, 4> {0.0f, 0.0f, 0.0f, 0.0f}}; + }; + const std::array<vk::ClearColorValue, PlaceholderColors> colors { + color(0.5f, 0.5f, 0.5f), color(0.8f, 0.1f, 0.1f), color(0.1f, 0.2f, 0.8f)}; + for (uint32_t i = 0; i < Placeholders; i++) { + command.clearColorImage(m_placeholders[i].image, vk::ImageLayout::eTransferDstOptimal, + &colors[i / ImageArrays], 1, &to_transfer[i].subresourceRange); + } + // translation[0], the entry of keys outside their heap, is the red slot. + command.fillBuffer(m_translation->Handle(), 4, VK_WHOLE_SIZE, 0u); + command.fillBuffer(m_translation->Handle(), 0, 4, 1u); + command.fillBuffer(m_feedback->Handle(), 0, VK_WHOLE_SIZE, 0u); + vk::BufferMemoryBarrier translation_ready {}; + translation_ready.srcAccessMask = vk::AccessFlagBits::eTransferWrite; + translation_ready.dstAccessMask = vk::AccessFlagBits::eShaderRead; + translation_ready.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + translation_ready.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + translation_ready.buffer = m_translation->Handle(); + translation_ready.offset = 0; + translation_ready.size = VK_WHOLE_SIZE; + auto feedback_ready = translation_ready; + feedback_ready.dstAccessMask = vk::AccessFlagBits::eShaderRead | + vk::AccessFlagBits::eShaderWrite | + vk::AccessFlagBits::eHostRead; + feedback_ready.buffer = m_feedback->Handle(); + const std::array<vk::BufferMemoryBarrier, 2> buffers_ready {translation_ready, feedback_ready}; + command.pipelineBarrier(vk::PipelineStageFlagBits::eTransfer, + vk::PipelineStageFlagBits::eAllCommands | + vk::PipelineStageFlagBits::eHost, + {}, 0, nullptr, static_cast<uint32_t>(buffers_ready.size()), + buffers_ready.data(), Placeholders, to_read.data()); + RequireVulkanSuccess(command.end(), "end bindless init command buffer"); + + vk::FenceCreateInfo fence_info {}; + vk::Fence fence = nullptr; + RequireVulkanSuccess(m_graphics.device.createFence(&fence_info, nullptr, &fence), + "create bindless init fence"); + vk::SubmitInfo submit {}; + submit.commandBufferCount = 1; + submit.pCommandBuffers = &command; + { + Common::LockGuard lock(m_graphics.queue_mutex); + RequireVulkanSuccess(m_graphics.queue.submit(1, &submit, fence), "submit bindless init"); + } + RequireVulkanSuccess(m_graphics.device.waitForFences(1, &fence, VK_TRUE, UINT64_MAX), + "wait for bindless init"); + m_graphics.device.destroyFence(fence, nullptr); + m_graphics.device.destroyCommandPool(pool, nullptr); + + std::array<vk::DescriptorImageInfo, Placeholders> infos {}; + std::array<vk::WriteDescriptorSet, Placeholders> writes {}; + for (uint32_t i = 0; i < Placeholders; i++) { + infos[i] = {nullptr, m_placeholder_views[i], + vk::ImageLayout::eShaderReadOnlyOptimal}; + writes[i].dstSet = m_set; + writes[i].dstBinding = Images2D + i % ImageArrays; + writes[i].dstArrayElement = i / ImageArrays; + writes[i].descriptorCount = 1; + writes[i].descriptorType = vk::DescriptorType::eSampledImage; + writes[i].pImageInfo = &infos[i]; + } + m_graphics.device.updateDescriptorSets(Placeholders, writes.data(), 0, nullptr); +} + +BindlessTable::~BindlessTable() { + for (uint32_t i = 0; i < Placeholders; i++) { + if (m_placeholder_views[i] != nullptr) { + m_graphics.device.destroyImageView(m_placeholder_views[i], nullptr); + } + if (m_placeholders[i].image != nullptr) { + m_graphics.DeleteImage(m_placeholders[i]); + } + } + m_translation.reset(); + m_feedback.reset(); + m_feedback_snapshot.reset(); + if (m_pool != nullptr) { + m_graphics.device.destroyDescriptorPool(m_pool, nullptr); + } + if (m_layout != nullptr) { + m_graphics.device.destroyDescriptorSetLayout(m_layout, nullptr); + } +} + +bool BindlessTable::AllocateRegion(Heap& heap, uint32_t entries) { + // Headroom so a growing heap rarely moves; a move re-writes the keys resolved so far. + const auto capacity = std::max(entries, std::min<uint32_t>(entries * 2u, 1u << 16u)); + if (capacity > ShaderRecompiler::IR::WatchdogReportBase - m_next_region) { + return false; + } + const auto old_region = heap.region; + const auto old_entries = heap.entries; + heap.region = m_next_region; + heap.entries = capacity; + m_next_region += capacity; + heap.slots.resize(capacity, 0u); + heap.settled.resize(capacity, 0u); + auto* translation = reinterpret_cast<uint32_t*>(m_translation->Mapped().data()); + auto* feedback = reinterpret_cast<uint32_t*>(m_feedback->Mapped().data()); + for (uint32_t key = 0; key < capacity; key++) { + uint32_t value = ShaderRecompiler::IR::BindlessPending; + if (key < old_entries && heap.settled[key] != 0) { + value = heap.slots[key]; + } + translation[heap.region + key] = value; + feedback[heap.region + key] = 0; + } + if (!m_translation->IsCoherent()) { + m_translation->Flush(heap.region * sizeof(uint32_t), capacity * sizeof(uint32_t)); + } + LOGF("Bindless heap region: base=0x%016" PRIx64 " binding=%u region=%u entries=%u (was %u at " + "%u)\n", + heap.base, heap.binding, heap.region, capacity, old_entries, old_region); + return true; +} + +BindlessTable::Heap* BindlessTable::FindOrCreateHeap( + uint64_t base, uint32_t table_offset, uint32_t binding, uint32_t entries, + const ShaderRecompiler::IR::ImageResource& resource) { + if (entries == 0) { + return nullptr; + } + for (auto& heap: m_heaps) { + if (heap.base == base && heap.table_offset == table_offset && heap.binding == binding) { + if (entries > heap.entries && !AllocateRegion(heap, entries)) { + return nullptr; + } + return &heap; + } + } + auto& heap = m_heaps.emplace_back(); + heap.base = base; + heap.table_offset = table_offset; + heap.binding = binding; + heap.resource = resource; + if (!AllocateRegion(heap, std::max(entries, 1u << 14u))) { + m_heaps.pop_back(); + return nullptr; + } + return &heap; +} + +uint32_t BindlessTable::AllocateSlot(uint32_t binding) { + if (binding >= ImageArrays || m_next_slot[binding] >= m_images_per_array) { + return 0; + } + return m_next_slot[binding]++; +} + +void BindlessTable::WriteSlot(uint32_t binding, uint32_t slot, vk::ImageView view, + vk::ImageLayout layout) { + const vk::DescriptorImageInfo info {nullptr, view, layout}; + vk::WriteDescriptorSet write {}; + write.dstSet = m_set; + write.dstBinding = binding; + write.dstArrayElement = slot; + write.descriptorCount = 1; + write.descriptorType = vk::DescriptorType::eSampledImage; + write.pImageInfo = &info; + m_graphics.device.updateDescriptorSets(1, &write, 0, nullptr); +} + +void BindlessTable::SetTranslation(const Heap& heap, uint32_t key, uint32_t slot) { + auto* translation = reinterpret_cast<uint32_t*>(m_translation->Mapped().data()); + translation[heap.region + key] = slot; + if (!m_translation->IsCoherent()) { + m_translation->Flush((heap.region + key) * sizeof(uint32_t), sizeof(uint32_t)); + } +} + +void BindlessTable::RecordFeedbackSnapshot(CommandScheduler& scheduler) { + // Regions are allocated contiguously after word 0, so one copy covers every heap. + const vk::DeviceSize size = vk::DeviceSize {m_next_region} * sizeof(uint32_t); + scheduler.EndRendering(); + auto command = scheduler.Current().Handle(); + vk::BufferMemoryBarrier flags_written {}; + flags_written.srcAccessMask = vk::AccessFlagBits::eShaderWrite; + flags_written.dstAccessMask = vk::AccessFlagBits::eTransferRead; + flags_written.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + flags_written.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + flags_written.buffer = m_feedback->Handle(); + flags_written.offset = 0; + flags_written.size = size; + command.pipelineBarrier(vk::PipelineStageFlagBits::eAllCommands, + vk::PipelineStageFlagBits::eTransfer, {}, 0, nullptr, 1, + &flags_written, 0, nullptr); + const vk::BufferCopy copy {0, 0, size}; + command.copyBuffer(m_feedback->Handle(), m_feedback_snapshot->Handle(), 1, &copy); + auto snapshot_written = flags_written; + snapshot_written.srcAccessMask = vk::AccessFlagBits::eTransferWrite; + snapshot_written.dstAccessMask = vk::AccessFlagBits::eHostRead; + snapshot_written.buffer = m_feedback_snapshot->Handle(); + command.pipelineBarrier(vk::PipelineStageFlagBits::eTransfer, + vk::PipelineStageFlagBits::eHost, {}, 0, nullptr, 1, + &snapshot_written, 0, nullptr); + m_snapshot_tick = scheduler.CurrentTick(); +} + +bool BindlessTable::SnapshotReady(CommandScheduler& scheduler) { + return m_snapshot_tick != 0 && scheduler.IsFree(m_snapshot_tick); +} + +void BindlessTable::TakeRequests(const Heap& heap, std::vector<uint32_t>& keys) { + const auto* snapshot = reinterpret_cast<const uint32_t*>(m_feedback_snapshot->Mapped().data()); + auto* feedback = reinterpret_cast<uint32_t*>(m_feedback->Mapped().data()); + m_feedback_snapshot->Invalidate(heap.region * sizeof(uint32_t), + heap.entries * sizeof(uint32_t)); + bool cleared = false; + for (uint32_t key = 0; key < heap.entries; key++) { + if (snapshot[heap.region + key] != 0) { + // A flag the GPU sets again after the snapshot may be lost here; a key that is + // still pending is flagged again by the next draw that samples it. + feedback[heap.region + key] = 0; + keys.push_back(key); + cleared = true; + } + } + if (cleared) { + m_feedback->Flush(heap.region * sizeof(uint32_t), heap.entries * sizeof(uint32_t)); + } +} + +void BindlessTable::DrainWatchdogReports(uint64_t frame) { + using ShaderRecompiler::IR::WatchdogReportBase; + using ShaderRecompiler::IR::WatchdogReportPhis; + using ShaderRecompiler::IR::WatchdogReportSlots; + using ShaderRecompiler::IR::WatchdogReportWords; + static_assert(WatchdogReportBase + WatchdogReportWords * (WatchdogReportSlots + 1) <= + TranslationEntries); + auto* feedback = reinterpret_cast<uint32_t*>(m_feedback->Mapped().data()); + if (!m_feedback->IsCoherent()) { + m_feedback->Invalidate(WatchdogReportBase * sizeof(uint32_t), + WatchdogReportWords * (WatchdogReportSlots + 1) * sizeof(uint32_t)); + } + const auto count = feedback[WatchdogReportBase]; + if (count == 0) { + return; + } + const auto stored = std::min(count, WatchdogReportSlots); + // Per (shader, loop): how many tripped, and the first report in full. + std::unordered_map<uint64_t, std::pair<uint32_t, const uint32_t*>> loops; + for (uint32_t n = 0; n < stored; n++) { + const auto* report = feedback + WatchdogReportBase + WatchdogReportWords * (n + 1); + if ((report[0] >> 16u) != 0x5744u) { + continue; + } + const auto key = (static_cast<uint64_t>(report[2]) << 32u | report[1]) ^ + (static_cast<uint64_t>(report[0] & 0xffffu) << 48u); + auto& entry = loops[key]; + if (entry.first++ == 0) { + entry.second = report; + } + } + static std::atomic<uint32_t> logged = 0; + LOGF("WatchdogTrips: frame=%" PRIu64 " reports=%u loops=%zu\n", frame, count, loops.size()); + for (const auto& [key, entry]: loops) { + if (logged.fetch_add(1) >= 256) { + break; + } + const auto* r = entry.second; + std::string phis; + for (uint32_t half = 0; half < 2; half++) { + phis += half == 0 ? " lo:" : " hi:"; + for (uint32_t i = 0; i < WatchdogReportPhis; i++) { + phis += fmt::format(" {:x}", r[16 + half * WatchdogReportPhis + i]); + } + } + LOGF("WatchdogTrip: hash=0x%08x%08x loop_block=%u trips=%u counter=%u group=%u lane=%u " + "ud=[%08x %08x %08x %08x %08x %08x %08x %08x]%s\n", + r[2], r[1], r[0] & 0xffffu, entry.first, r[3], r[4], r[5], r[6], r[7], r[8], r[9], + r[10], r[11], r[12], r[13], phis.c_str()); + } + feedback[WatchdogReportBase] = 0; + if (!m_feedback->IsCoherent()) { + m_feedback->Flush(WatchdogReportBase * sizeof(uint32_t), sizeof(uint32_t)); + } +} + +void BindlessTable::AddImageReference(ImageId id, Heap& heap, uint32_t key) { + m_image_refs[ImageKey(id)].emplace_back(&heap, key); +} + +void BindlessTable::OnImageUnregistered(ImageId id) { + const auto found = m_image_refs.find(ImageKey(id)); + if (found == m_image_refs.end()) { + return; + } + for (const auto& [heap, key]: found->second) { + if (heap->slots[key] != 0) { + WriteSlot(heap->binding, heap->slots[key], m_placeholder_views[heap->binding], + vk::ImageLayout::eShaderReadOnlyOptimal); + } + heap->slots[key] = 0; + heap->settled[key] = 0; + SetTranslation(*heap, key, ShaderRecompiler::IR::BindlessPending); + std::erase(heap->resolved, id); + } + m_image_refs.erase(found); +} ``` _🩺 Stability & Availability_ | _🟠 Major_ | _🏗️ Heavy lift_ <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash #!/bin/bash rg -nP -C6 '\bOnImageUnregistered\s*\(' src/graphics rg -nP -C4 'bindless_pinned' src/graphics ``` Repository: KytyPS5/KytyPS5 Length of output: 7367 --- 🏁 Script executed: ```bash #!/bin/bash set -eu printf '%s\n' '--- bindless diff ---' git diff --unified=30 05057c9441dbf3972d49f9143b90213a43a01a00 d6ec3a42ed19d0f16bb3e184ca57e20cce8d5176 -- src/graphics/host_gpu/renderer/pipeline/bindlessTable.cpp src/graphics/host_gpu/renderer/pipeline/bindlessTable.h printf '%s\n' '--- unregister lifecycle ---' sed -n '210,280p' src/graphics/host_gpu/renderer/cache/textureCache.cpp rg -n -P -C8 'Unregister|unregister|on_bindless_unregister|bindless_pinned|m_slot_images\.erase|slot_images' src/graphics/host_gpu/renderer/cache/textureCache.cpp printf '%s\n' '--- bindless declarations and flags ---' sed -n '100,175p' src/graphics/host_gpu/renderer/pipeline/bindlessTable.h rg -n -P -C10 'eUpdateAfterBind|eUpdateUnusedWhilePending|eUpdateAfterBind' src/graphics/host_gpu/renderer/pipeline/bindlessTable.cpp src/graphics/host_gpu/renderer/pipeline/bindlessTable.h printf '%s\n' '--- scheduler APIs and related deferred cleanup ---' rg -n -P -C8 'SchedulerTick|scheduler tick|CurrentTick|last.*tick|retir|pending.*release|defer|SafeTo|WaitFor|IsFree|IsReady' src/graphics/host_gpu/renderer | head -n 500 printf '%s\n' '--- image destruction references ---' rg -n -P -C8 'vk::ImageView|image_view|view.*destroy|destroy.*view|m_slot_images|UnregisterImage|RegisterImage' src/graphics/host_gpu/renderer/cache src/graphics/host_gpu/renderer/image src/graphics/host_gpu/renderer | head -n 500 ``` Repository: KytyPS5/KytyPS5 Length of output: 42932 --- 🤖 get_repo_knowledge executed: `get_repo_knowledge KytyPS5/KytyPS5 /tmp/coderabbit-repo-knowledge/kytyps5-kytyps5-b6cddd0b/architecture` Length of output: 42532 --- </details> **Defer bindless slot retirement until pending work completes.** `TextureCache::UnregisterImage` calls `OnImageUnregistered` immediately. That function updates the descriptor and translation for each referenced slot. A submitted draw may still use the slot. `eUpdateUnusedWhilePending` does not permit updates to descriptors used by pending work. Defer the complete slot retirement, including the placeholder descriptor write, translation update, and state cleanup, until the scheduler confirms that the last submission using the slot has retired. `DeleteImage` already defers image destruction while the scheduler is active, but that does not make the descriptor update safe. <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:f318df467854cbed818a3d3a --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-30 00:19 UTC · original
On src/graphics/host_gpu/renderer/pipeline/descriptors.cpp line 838 (outdated):

@@ -763,6 +783,207 @@ void RenderExecutor::ResetBindings() {
 	m_bound_images.clear();
 }
 
+static uint32_t BindlessBindingFor(const ShaderRecompiler::IR::ImageResource& resource) {
+	using ShaderRecompiler::Decoder::ImageDimension;
+	if (resource.cube) {
+		return ShaderRecompiler::IR::BindlessImagesCube;
+	}
+	if (resource.dimension == ImageDimension::Dim3D) {
+		return ShaderRecompiler::IR::BindlessImages3D;
+	}
+	if (resource.dimension == ImageDimension::Dim2DArray ||
+	    resource.dimension == ImageDimension::Dim2DMsaaArray) {
+		return ShaderRecompiler::IR::BindlessImages2DArray;
+	}
+	return ShaderRecompiler::IR::BindlessImages2D;
+}
+
+// A heap entry the bindless array of this binding can hold: a float-sampled, single-sample
+// texture of a matching shape. Anything else stays the placeholder rather than reaching
+// ResolveTexture, which exits on descriptors a draw would never bind that way.
+static bool BindlessCompatible(const ShaderTextureResource& descriptor, uint32_t binding) {
+	if (descriptor.IsNull() ||
+	    Prospero::SampledTextureNumericClass(descriptor.Format()) !=
+	        Prospero::TextureNumericClass::Float) {
+		return false;
+	}
+	switch (descriptor.Type()) {
+		case Prospero::ImageType::kColor2D:
+			return binding == ShaderRecompiler::IR::BindlessImages2D ||
+			       binding == ShaderRecompiler::IR::BindlessImages2DArray;
+		case Prospero::ImageType::kColor2DArray:
+			return binding == ShaderRecompiler::IR::BindlessImages2D ||
+			       binding == ShaderRecompiler::IR::BindlessImages2DArray;
+		case Prospero::ImageType::kCube: return binding == ShaderRecompiler::IR::BindlessImagesCube;
+		case Prospero::ImageType::kColor3D: return binding == ShaderRecompiler::IR::BindlessImages3D;
+		default: return false;
+	}
+}
+
+bool RenderExecutor::ResolveBindlessKey(BindlessTable::Heap& heap, uint32_t key) {
+	auto&                                 table = m_context.GetBindlessTable();
+	ShaderRecompiler::IR::DescriptorValue value {};
+	value.dword_count  = 8u;
+	const auto address = heap.base + heap.table_offset + static_cast<uint64_t>(key) * 32u;
+	heap.settled[key]  = 1;
+	if (!Libs::LibKernel::Memory::TryReadBacking(address, value.dwords.data(), 32u)) {
+		table.SetTranslation(heap, key, 0u);
+		return false;
+	}
+	const auto descriptor = DecodeNativeDescriptor<ShaderTextureResource>(value);
+	if (!BindlessCompatible(descriptor, heap.binding)) {
+		table.SetTranslation(heap, key, 0u);
+		return false;
+	}
+	auto binding = ResolveTexture(heap.resource, value);

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

BindlessCompatible does not filter every descriptor that makes ResolveTexture exit.

The comment says that incompatible entries stay on the placeholder "rather than reaching ResolveTexture, which exits". The filter checks only null, the float numeric class, and the image type. ResolveTexture still calls EXIT or EXIT_NOT_IMPLEMENTED in these cases:

  • base_level > last_level
  • MinLod() > LastLevel()*256
  • an unaligned base address
  • a base layer out of bounds
  • ResolveTextureMipView failures
  • heap.resource.numeric_class differs from the format class

Heap keys come from shader feedback. A stale or garbage guest heap entry therefore terminates the emulator. This is the crash that the placeholder path is meant to prevent.

Fix: add these same checks to BindlessCompatible so that bad entries fall back to the placeholder. As an alternative, add a non-fatal validation mode to ResolveTexture that returns an invalid binding.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-30 00:19 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/937#discussion_r4139620639) On `src/graphics/host_gpu/renderer/pipeline/descriptors.cpp` line 838 (outdated): ```diff @@ -763,6 +783,207 @@ void RenderExecutor::ResetBindings() { m_bound_images.clear(); } +static uint32_t BindlessBindingFor(const ShaderRecompiler::IR::ImageResource& resource) { + using ShaderRecompiler::Decoder::ImageDimension; + if (resource.cube) { + return ShaderRecompiler::IR::BindlessImagesCube; + } + if (resource.dimension == ImageDimension::Dim3D) { + return ShaderRecompiler::IR::BindlessImages3D; + } + if (resource.dimension == ImageDimension::Dim2DArray || + resource.dimension == ImageDimension::Dim2DMsaaArray) { + return ShaderRecompiler::IR::BindlessImages2DArray; + } + return ShaderRecompiler::IR::BindlessImages2D; +} + +// A heap entry the bindless array of this binding can hold: a float-sampled, single-sample +// texture of a matching shape. Anything else stays the placeholder rather than reaching +// ResolveTexture, which exits on descriptors a draw would never bind that way. +static bool BindlessCompatible(const ShaderTextureResource& descriptor, uint32_t binding) { + if (descriptor.IsNull() || + Prospero::SampledTextureNumericClass(descriptor.Format()) != + Prospero::TextureNumericClass::Float) { + return false; + } + switch (descriptor.Type()) { + case Prospero::ImageType::kColor2D: + return binding == ShaderRecompiler::IR::BindlessImages2D || + binding == ShaderRecompiler::IR::BindlessImages2DArray; + case Prospero::ImageType::kColor2DArray: + return binding == ShaderRecompiler::IR::BindlessImages2D || + binding == ShaderRecompiler::IR::BindlessImages2DArray; + case Prospero::ImageType::kCube: return binding == ShaderRecompiler::IR::BindlessImagesCube; + case Prospero::ImageType::kColor3D: return binding == ShaderRecompiler::IR::BindlessImages3D; + default: return false; + } +} + +bool RenderExecutor::ResolveBindlessKey(BindlessTable::Heap& heap, uint32_t key) { + auto& table = m_context.GetBindlessTable(); + ShaderRecompiler::IR::DescriptorValue value {}; + value.dword_count = 8u; + const auto address = heap.base + heap.table_offset + static_cast<uint64_t>(key) * 32u; + heap.settled[key] = 1; + if (!Libs::LibKernel::Memory::TryReadBacking(address, value.dwords.data(), 32u)) { + table.SetTranslation(heap, key, 0u); + return false; + } + const auto descriptor = DecodeNativeDescriptor<ShaderTextureResource>(value); + if (!BindlessCompatible(descriptor, heap.binding)) { + table.SetTranslation(heap, key, 0u); + return false; + } + auto binding = ResolveTexture(heap.resource, value); ``` _🩺 Stability & Availability_ | _🟠 Major_ | _🏗️ Heavy lift_ **`BindlessCompatible` does not filter every descriptor that makes `ResolveTexture` exit.** The comment says that incompatible entries stay on the placeholder "rather than reaching ResolveTexture, which exits". The filter checks only null, the float numeric class, and the image type. `ResolveTexture` still calls `EXIT` or `EXIT_NOT_IMPLEMENTED` in these cases: - `base_level > last_level` - `MinLod() > LastLevel()*256` - an unaligned base address - a base layer out of bounds - `ResolveTextureMipView` failures - `heap.resource.numeric_class` differs from the format class Heap keys come from shader feedback. A stale or garbage guest heap entry therefore terminates the emulator. This is the crash that the placeholder path is meant to prevent. Fix: add these same checks to `BindlessCompatible` so that bad entries fall back to the placeholder. As an alternative, add a non-fatal validation mode to `ResolveTexture` that returns an invalid binding. <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:a4d8ee41364edd8fcbdcf3ae --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-30 00:19 UTC · original
On src/graphics/host_gpu/renderer/pipeline/descriptors.cpp line 855 (outdated):

@@ -763,6 +783,207 @@ void RenderExecutor::ResetBindings() {
 	m_bound_images.clear();
 }
 
+static uint32_t BindlessBindingFor(const ShaderRecompiler::IR::ImageResource& resource) {
+	using ShaderRecompiler::Decoder::ImageDimension;
+	if (resource.cube) {
+		return ShaderRecompiler::IR::BindlessImagesCube;
+	}
+	if (resource.dimension == ImageDimension::Dim3D) {
+		return ShaderRecompiler::IR::BindlessImages3D;
+	}
+	if (resource.dimension == ImageDimension::Dim2DArray ||
+	    resource.dimension == ImageDimension::Dim2DMsaaArray) {
+		return ShaderRecompiler::IR::BindlessImages2DArray;
+	}
+	return ShaderRecompiler::IR::BindlessImages2D;
+}
+
+// A heap entry the bindless array of this binding can hold: a float-sampled, single-sample
+// texture of a matching shape. Anything else stays the placeholder rather than reaching
+// ResolveTexture, which exits on descriptors a draw would never bind that way.
+static bool BindlessCompatible(const ShaderTextureResource& descriptor, uint32_t binding) {
+	if (descriptor.IsNull() ||
+	    Prospero::SampledTextureNumericClass(descriptor.Format()) !=
+	        Prospero::TextureNumericClass::Float) {
+		return false;
+	}
+	switch (descriptor.Type()) {
+		case Prospero::ImageType::kColor2D:
+			return binding == ShaderRecompiler::IR::BindlessImages2D ||
+			       binding == ShaderRecompiler::IR::BindlessImages2DArray;
+		case Prospero::ImageType::kColor2DArray:
+			return binding == ShaderRecompiler::IR::BindlessImages2D ||
+			       binding == ShaderRecompiler::IR::BindlessImages2DArray;
+		case Prospero::ImageType::kCube: return binding == ShaderRecompiler::IR::BindlessImagesCube;
+		case Prospero::ImageType::kColor3D: return binding == ShaderRecompiler::IR::BindlessImages3D;
+		default: return false;
+	}
+}
+
+bool RenderExecutor::ResolveBindlessKey(BindlessTable::Heap& heap, uint32_t key) {
+	auto&                                 table = m_context.GetBindlessTable();
+	ShaderRecompiler::IR::DescriptorValue value {};
+	value.dword_count  = 8u;
+	const auto address = heap.base + heap.table_offset + static_cast<uint64_t>(key) * 32u;
+	heap.settled[key]  = 1;
+	if (!Libs::LibKernel::Memory::TryReadBacking(address, value.dwords.data(), 32u)) {
+		table.SetTranslation(heap, key, 0u);
+		return false;
+	}
+	const auto descriptor = DecodeNativeDescriptor<ShaderTextureResource>(value);
+	if (!BindlessCompatible(descriptor, heap.binding)) {
+		table.SetTranslation(heap, key, 0u);
+		return false;
+	}
+	auto binding = ResolveTexture(heap.resource, value);
+	auto& texture_cache = m_context.GetTextureCache();
+	auto* image = texture_cache.m_slot_images.try_get(binding.image_id);
+	if (image == nullptr || image->info.data.Empty()) {
+		table.SetTranslation(heap, key, 0u);
+		return false;
+	}
+	BindImage(binding.image_id, false);
+	const auto view = texture_cache.FindTexture(binding.image_id, binding.desc);
+	image           = texture_cache.m_slot_images.try_get(binding.image_id);
+	const auto slot = table.AllocateSlot(heap.binding);
+	if (image == nullptr || view == nullptr || slot == 0) {
+		table.SetTranslation(heap, key, 0u);
+		return false;
+	}
+	const auto layout = image->info.IsDepth() ? vk::ImageLayout::eDepthStencilReadOnlyOptimal
+	                                          : vk::ImageLayout::eShaderReadOnlyOptimal;
+	table.WriteSlot(heap.binding, slot, view, layout);

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Bindless cube slots receive a 2D-array view, but the placeholders in the same binding are cube views.

BindlessBindingFor sends resource.cube to BindlessImagesCube. CreatePlaceholders fills that binding with vk::ImageViewType::eCube views. However, ResolveTexture builds desc.view_info through TextureViewInfo, which has no cube case. A cube resource has dimension Dim2DArray, so the resolved view is e2DArray.

WriteSlot then puts an e2DArray view into the cube array. The shader declaration can match only one of the two view types. The other one is a descriptor/view-type mismatch, which is invalid in Vulkan and gives wrong sampling.

Fix: for heap.binding == BindlessImagesCube, set binding.desc.view_info.type = vk::ImageViewType::eCube before FindTexture. The layer count must be a multiple of 6. Also confirm that the texture cache creates such images with eCubeCompatible.

Proposed fix
 	BindImage(binding.image_id, false);
+	if (heap.binding == ShaderRecompiler::IR::BindlessImagesCube) {
+		binding.desc.view_info.type        = vk::ImageViewType::eCube;
+		binding.desc.view_info.layer_count = 6u;
+	}
 	const auto view = texture_cache.FindTexture(binding.image_id, binding.desc);
📝 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.

	auto binding = ResolveTexture(heap.resource, value);
	auto& texture_cache = m_context.GetTextureCache();
	auto* image = texture_cache.m_slot_images.try_get(binding.image_id);
	if (image == nullptr || image->info.data.Empty()) {
		table.SetTranslation(heap, key, 0u);
		return false;
	}
	BindImage(binding.image_id, false);
	if (heap.binding == ShaderRecompiler::IR::BindlessImagesCube) {
		binding.desc.view_info.type        = vk::ImageViewType::eCube;
		binding.desc.view_info.layer_count = 6u;
	}
	const auto view = texture_cache.FindTexture(binding.image_id, binding.desc);
	image           = texture_cache.m_slot_images.try_get(binding.image_id);
	const auto slot = table.AllocateSlot(heap.binding);
	if (image == nullptr || view == nullptr || slot == 0) {
		table.SetTranslation(heap, key, 0u);
		return false;
	}
	const auto layout = image->info.IsDepth() ? vk::ImageLayout::eDepthStencilReadOnlyOptimal
	                                          : vk::ImageLayout::eShaderReadOnlyOptimal;
	table.WriteSlot(heap.binding, slot, view, layout);
**@⁠coderabbitai[bot]** on GitHub · 2026-09-30 00:19 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/937#discussion_r4139620645) On `src/graphics/host_gpu/renderer/pipeline/descriptors.cpp` line 855 (outdated): ```diff @@ -763,6 +783,207 @@ void RenderExecutor::ResetBindings() { m_bound_images.clear(); } +static uint32_t BindlessBindingFor(const ShaderRecompiler::IR::ImageResource& resource) { + using ShaderRecompiler::Decoder::ImageDimension; + if (resource.cube) { + return ShaderRecompiler::IR::BindlessImagesCube; + } + if (resource.dimension == ImageDimension::Dim3D) { + return ShaderRecompiler::IR::BindlessImages3D; + } + if (resource.dimension == ImageDimension::Dim2DArray || + resource.dimension == ImageDimension::Dim2DMsaaArray) { + return ShaderRecompiler::IR::BindlessImages2DArray; + } + return ShaderRecompiler::IR::BindlessImages2D; +} + +// A heap entry the bindless array of this binding can hold: a float-sampled, single-sample +// texture of a matching shape. Anything else stays the placeholder rather than reaching +// ResolveTexture, which exits on descriptors a draw would never bind that way. +static bool BindlessCompatible(const ShaderTextureResource& descriptor, uint32_t binding) { + if (descriptor.IsNull() || + Prospero::SampledTextureNumericClass(descriptor.Format()) != + Prospero::TextureNumericClass::Float) { + return false; + } + switch (descriptor.Type()) { + case Prospero::ImageType::kColor2D: + return binding == ShaderRecompiler::IR::BindlessImages2D || + binding == ShaderRecompiler::IR::BindlessImages2DArray; + case Prospero::ImageType::kColor2DArray: + return binding == ShaderRecompiler::IR::BindlessImages2D || + binding == ShaderRecompiler::IR::BindlessImages2DArray; + case Prospero::ImageType::kCube: return binding == ShaderRecompiler::IR::BindlessImagesCube; + case Prospero::ImageType::kColor3D: return binding == ShaderRecompiler::IR::BindlessImages3D; + default: return false; + } +} + +bool RenderExecutor::ResolveBindlessKey(BindlessTable::Heap& heap, uint32_t key) { + auto& table = m_context.GetBindlessTable(); + ShaderRecompiler::IR::DescriptorValue value {}; + value.dword_count = 8u; + const auto address = heap.base + heap.table_offset + static_cast<uint64_t>(key) * 32u; + heap.settled[key] = 1; + if (!Libs::LibKernel::Memory::TryReadBacking(address, value.dwords.data(), 32u)) { + table.SetTranslation(heap, key, 0u); + return false; + } + const auto descriptor = DecodeNativeDescriptor<ShaderTextureResource>(value); + if (!BindlessCompatible(descriptor, heap.binding)) { + table.SetTranslation(heap, key, 0u); + return false; + } + auto binding = ResolveTexture(heap.resource, value); + auto& texture_cache = m_context.GetTextureCache(); + auto* image = texture_cache.m_slot_images.try_get(binding.image_id); + if (image == nullptr || image->info.data.Empty()) { + table.SetTranslation(heap, key, 0u); + return false; + } + BindImage(binding.image_id, false); + const auto view = texture_cache.FindTexture(binding.image_id, binding.desc); + image = texture_cache.m_slot_images.try_get(binding.image_id); + const auto slot = table.AllocateSlot(heap.binding); + if (image == nullptr || view == nullptr || slot == 0) { + table.SetTranslation(heap, key, 0u); + return false; + } + const auto layout = image->info.IsDepth() ? vk::ImageLayout::eDepthStencilReadOnlyOptimal + : vk::ImageLayout::eShaderReadOnlyOptimal; + table.WriteSlot(heap.binding, slot, view, layout); ``` _🎯 Functional Correctness_ | _🟠 Major_ | _⚡ Quick win_ **Bindless cube slots receive a 2D-array view, but the placeholders in the same binding are cube views.** `BindlessBindingFor` sends `resource.cube` to `BindlessImagesCube`. `CreatePlaceholders` fills that binding with `vk::ImageViewType::eCube` views. However, `ResolveTexture` builds `desc.view_info` through `TextureViewInfo`, which has no cube case. A cube resource has dimension `Dim2DArray`, so the resolved view is `e2DArray`. `WriteSlot` then puts an `e2DArray` view into the cube array. The shader declaration can match only one of the two view types. The other one is a descriptor/view-type mismatch, which is invalid in Vulkan and gives wrong sampling. Fix: for `heap.binding == BindlessImagesCube`, set `binding.desc.view_info.type = vk::ImageViewType::eCube` before `FindTexture`. The layer count must be a multiple of 6. Also confirm that the texture cache creates such images with `eCubeCompatible`. <details> <summary>Proposed fix</summary> ```diff BindImage(binding.image_id, false); + if (heap.binding == ShaderRecompiler::IR::BindlessImagesCube) { + binding.desc.view_info.type = vk::ImageViewType::eCube; + binding.desc.view_info.layer_count = 6u; + } const auto view = texture_cache.FindTexture(binding.image_id, binding.desc); ``` </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 auto binding = ResolveTexture(heap.resource, value); auto& texture_cache = m_context.GetTextureCache(); auto* image = texture_cache.m_slot_images.try_get(binding.image_id); if (image == nullptr || image->info.data.Empty()) { table.SetTranslation(heap, key, 0u); return false; } BindImage(binding.image_id, false); if (heap.binding == ShaderRecompiler::IR::BindlessImagesCube) { binding.desc.view_info.type = vk::ImageViewType::eCube; binding.desc.view_info.layer_count = 6u; } const auto view = texture_cache.FindTexture(binding.image_id, binding.desc); image = texture_cache.m_slot_images.try_get(binding.image_id); const auto slot = table.AllocateSlot(heap.binding); if (image == nullptr || view == nullptr || slot == 0) { table.SetTranslation(heap, key, 0u); return false; } const auto layout = image->info.IsDepth() ? vk::ImageLayout::eDepthStencilReadOnlyOptimal : vk::ImageLayout::eShaderReadOnlyOptimal; table.WriteSlot(heap.binding, slot, view, layout); ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:a4fea0c04fdd20a6fd1925bf --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-30 00:19 UTC · original
On src/graphics/host_gpu/renderer/pipeline/descriptors.cpp line 979 (outdated):

@@ -763,6 +783,207 @@ void RenderExecutor::ResetBindings() {
 	m_bound_images.clear();
 }
 
+static uint32_t BindlessBindingFor(const ShaderRecompiler::IR::ImageResource& resource) {
+	using ShaderRecompiler::Decoder::ImageDimension;
+	if (resource.cube) {
+		return ShaderRecompiler::IR::BindlessImagesCube;
+	}
+	if (resource.dimension == ImageDimension::Dim3D) {
+		return ShaderRecompiler::IR::BindlessImages3D;
+	}
+	if (resource.dimension == ImageDimension::Dim2DArray ||
+	    resource.dimension == ImageDimension::Dim2DMsaaArray) {
+		return ShaderRecompiler::IR::BindlessImages2DArray;
+	}
+	return ShaderRecompiler::IR::BindlessImages2D;
+}
+
+// A heap entry the bindless array of this binding can hold: a float-sampled, single-sample
+// texture of a matching shape. Anything else stays the placeholder rather than reaching
+// ResolveTexture, which exits on descriptors a draw would never bind that way.
+static bool BindlessCompatible(const ShaderTextureResource& descriptor, uint32_t binding) {
+	if (descriptor.IsNull() ||
+	    Prospero::SampledTextureNumericClass(descriptor.Format()) !=
+	        Prospero::TextureNumericClass::Float) {
+		return false;
+	}
+	switch (descriptor.Type()) {
+		case Prospero::ImageType::kColor2D:
+			return binding == ShaderRecompiler::IR::BindlessImages2D ||
+			       binding == ShaderRecompiler::IR::BindlessImages2DArray;
+		case Prospero::ImageType::kColor2DArray:
+			return binding == ShaderRecompiler::IR::BindlessImages2D ||
+			       binding == ShaderRecompiler::IR::BindlessImages2DArray;
+		case Prospero::ImageType::kCube: return binding == ShaderRecompiler::IR::BindlessImagesCube;
+		case Prospero::ImageType::kColor3D: return binding == ShaderRecompiler::IR::BindlessImages3D;
+		default: return false;
+	}
+}
+
+bool RenderExecutor::ResolveBindlessKey(BindlessTable::Heap& heap, uint32_t key) {
+	auto&                                 table = m_context.GetBindlessTable();
+	ShaderRecompiler::IR::DescriptorValue value {};
+	value.dword_count  = 8u;
+	const auto address = heap.base + heap.table_offset + static_cast<uint64_t>(key) * 32u;
+	heap.settled[key]  = 1;
+	if (!Libs::LibKernel::Memory::TryReadBacking(address, value.dwords.data(), 32u)) {
+		table.SetTranslation(heap, key, 0u);
+		return false;
+	}
+	const auto descriptor = DecodeNativeDescriptor<ShaderTextureResource>(value);
+	if (!BindlessCompatible(descriptor, heap.binding)) {
+		table.SetTranslation(heap, key, 0u);
+		return false;
+	}
+	auto binding = ResolveTexture(heap.resource, value);
+	auto& texture_cache = m_context.GetTextureCache();
+	auto* image = texture_cache.m_slot_images.try_get(binding.image_id);
+	if (image == nullptr || image->info.data.Empty()) {
+		table.SetTranslation(heap, key, 0u);
+		return false;
+	}
+	BindImage(binding.image_id, false);
+	const auto view = texture_cache.FindTexture(binding.image_id, binding.desc);
+	image           = texture_cache.m_slot_images.try_get(binding.image_id);
+	const auto slot = table.AllocateSlot(heap.binding);
+	if (image == nullptr || view == nullptr || slot == 0) {
+		table.SetTranslation(heap, key, 0u);
+		return false;
+	}
+	const auto layout = image->info.IsDepth() ? vk::ImageLayout::eDepthStencilReadOnlyOptimal
+	                                          : vk::ImageLayout::eShaderReadOnlyOptimal;
+	table.WriteSlot(heap.binding, slot, view, layout);
+	heap.slots[key]         = slot;
+	image->bindless_pinned  = true;
+	image->usage.texture    = true;
+	heap.resolved.push_back(binding.image_id);
+	table.AddImageReference(binding.image_id, heap, key);
+	table.SetTranslation(heap, key, slot);
+	return true;
+}
+
+void RenderExecutor::ResolveBindlessRequests() {
+	const auto frame = m_context.GetGraphics().presented_frames.load(std::memory_order_relaxed);
+	if (frame == m_bindless_frame) {
+		return;
+	}
+	auto& table     = m_context.GetBindlessTable();
+	auto& scheduler = m_context.GetCommandScheduler();
+	// The flags come from a snapshot recorded in an earlier frame. Until the GPU has executed
+	// it, check again at the next bindless draw instead of waiting.
+	if (table.SnapshotRecorded() && !table.SnapshotReady(scheduler)) {
+		return;
+	}
+	m_bindless_frame = frame;
+	m_context.GetBindlessTable().DrainWatchdogReports(frame);
+	if (!table.SnapshotRecorded()) {
+		table.RecordFeedbackSnapshot(scheduler);
+		return;
+	}
+	table.ConsumeSnapshot();
+	// Each texture may upload and detile; spread first sight of a scene over a few frames.
+	constexpr uint32_t Budget   = 128;
+	uint32_t           resolved = 0;
+	for (auto& heap: m_context.GetBindlessTable().Heaps()) {
+		m_bindless_requests.clear();
+		m_context.GetBindlessTable().TakeRequests(heap, m_bindless_requests);
+		for (const auto key: m_bindless_requests) {
+			if (heap.settled[key] != 0) {
+				continue;
+			}
+			if (resolved >= Budget) {
+				break; // still pending: the next frame flags it again
+			}
+			resolved += ResolveBindlessKey(heap, key) ? 1u : 0u;
+		}
+	}
+	table.RecordFeedbackSnapshot(scheduler);
+}
+
+// Bindless samplers: the S# records of each sampler heap a draw indexes are mirrored into the
+// sampler array of set 1, once per frame per heap, and the shader gets the region base and record
+// count. Keys outside it, and heaps that cannot be read, use the default sampler in slot 0.
+void RenderExecutor::PrepareBindlessSamplers(const ShaderStageRuntime& runtime,
+                                             PreparedBindings&         prepared) {
+	const auto& program  = *runtime.program;
+	const auto& snapshot = *runtime.resources;
+	if (snapshot.bindless_sampler_heaps.empty()) {
+		return;
+	}
+	auto& table = m_context.GetBindlessTable();
+	auto& cache = m_context.GetSamplerCache();
+	{
+		ShaderSamplerResource default_sampler;
+		std::ranges::copy(ShaderRecompiler::IR::BindlessDefaultSampler, default_sampler.fields);
+		table.WriteDefaultSampler(cache.GetSampler(default_sampler, false));
+	}
+	const auto frame = m_context.GetGraphics().presented_frames.load(std::memory_order_relaxed);
+	constexpr uint64_t MaxRecords = 1024;
+	for (const auto& use: snapshot.bindless_sampler_heaps) {
+		uint32_t region  = 0;
+		uint32_t entries = 0;
+		if (table.SamplersEnabled() && use.sampler < program.info.samplers.size()) {
+			const auto&    sampler = program.info.samplers[use.sampler];
+			const uint32_t flags =
+			    (sampler.depth_compare ? BindlessTable::SamplerDepthCompare : 0u) |
+			    (sampler.force_point_filtering ? BindlessTable::SamplerPointFiltering : 0u) |
+			    (sampler.integer_border ? BindlessTable::SamplerIntegerBorder : 0u);
+			auto* heap = table.FindOrCreateSamplerHeap(use.base, use.table_offset, flags);
+			if (heap->checked_frame != frame) {
+				heap->checked_frame = frame;
+				const uint64_t available =
+				    use.size > use.table_offset ? (use.size - use.table_offset) / 16u : 0u;
+				std::vector<std::array<uint32_t, 4>> records(std::min(available, MaxRecords));
+				const uint64_t address = use.base + use.table_offset;
+				const uint64_t bytes   = records.size() * sizeof(records[0]);
+				if (!records.empty() &&
+				    !m_context.GetBufferCache().HasGpuDirtyBytes(address, bytes) &&
+				    Libs::LibKernel::Memory::TryReadBacking(address, records.data(), bytes)) {
+					(void)table.MirrorSamplerHeap(*heap, records, cache);
+				}
+			}
+			region  = heap->region;
+			entries = region != 0 ? static_cast<uint32_t>(heap->records.size()) : 0u;
+		}
+		prepared.bindless_patches.push_back({use.mapping_offset, region, entries});
+	}
+}
+
+void RenderExecutor::PrepareBindlessHeaps(const ShaderStageRuntime& runtime,
+                                          PreparedBindings& prepared) {
+	prepared.bindless_patches.clear();
+	prepared.bindless_images.clear();
+	const auto& program  = *runtime.program;
+	const auto& snapshot = *runtime.resources;
+	auto&       table    = m_context.GetBindlessTable();
+	if ((snapshot.bindless_heaps.empty() && snapshot.bindless_sampler_heaps.empty()) ||
+	    !table.Enabled()) {
+		return;
+	}
+	PrepareBindlessSamplers(runtime, prepared);
+	if (snapshot.bindless_heaps.empty()) {
+		return;
+	}
+	ResolveBindlessRequests();
+	for (const auto& use: snapshot.bindless_heaps) {
+		if (use.image >= program.info.images.size()) {
+			continue;
+		}
+		const auto& resource = program.info.images[use.image];
+		const uint64_t span  = use.size > use.table_offset ? use.size - use.table_offset : 0;
+		const auto entries   = static_cast<uint32_t>(std::min<uint64_t>(span / 32u, 1u << 18u));
+		auto* heap = table.FindOrCreateHeap(use.base, use.table_offset, BindlessBindingFor(resource),
+		                                    entries, resource);
+		if (heap == nullptr) {
+			continue; // region 0, count 0: every key samples the placeholder
+		}

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

The code skips the SRT patch when heap allocation fails, but the comment says the result is region 0 and count 0.

When use.image is out of range or FindOrCreateHeap returns null, the loop continues without pushing a patch. RebindBuffers then uploads the unpatched snapshot.flattened_srt. If no other patch exists, the whole upload is unpatched.

BindlessSlot reads base and count from mapping_offset. It then gets guest data instead of {0, 0}, and it indexes arbitrary translation and feedback entries. The sampler path already pushes {use.mapping_offset, 0, 0} in the same situation.

Proposed fix
 	for (const auto& use: snapshot.bindless_heaps) {
 		if (use.image >= program.info.images.size()) {
+			prepared.bindless_patches.push_back({use.mapping_offset, 0u, 0u});
 			continue;
 		}
 ...
 		if (heap == nullptr) {
+			prepared.bindless_patches.push_back({use.mapping_offset, 0u, 0u});
 			continue; // region 0, count 0: every key samples the placeholder
 		}
📝 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.

	for (const auto& use: snapshot.bindless_heaps) {
		if (use.image >= program.info.images.size()) {
			prepared.bindless_patches.push_back({use.mapping_offset, 0u, 0u});
			continue;
		}
		const auto& resource = program.info.images[use.image];
		const uint64_t span  = use.size > use.table_offset ? use.size - use.table_offset : 0;
		const auto entries   = static_cast<uint32_t>(std::min<uint64_t>(span / 32u, 1u << 18u));
		auto* heap = table.FindOrCreateHeap(use.base, use.table_offset, BindlessBindingFor(resource),
		                                    entries, resource);
		if (heap == nullptr) {
			prepared.bindless_patches.push_back({use.mapping_offset, 0u, 0u});
			continue; // region 0, count 0: every key samples the placeholder
		}
**@⁠coderabbitai[bot]** on GitHub · 2026-09-30 00:19 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/937#discussion_r4139620654) On `src/graphics/host_gpu/renderer/pipeline/descriptors.cpp` line 979 (outdated): ```diff @@ -763,6 +783,207 @@ void RenderExecutor::ResetBindings() { m_bound_images.clear(); } +static uint32_t BindlessBindingFor(const ShaderRecompiler::IR::ImageResource& resource) { + using ShaderRecompiler::Decoder::ImageDimension; + if (resource.cube) { + return ShaderRecompiler::IR::BindlessImagesCube; + } + if (resource.dimension == ImageDimension::Dim3D) { + return ShaderRecompiler::IR::BindlessImages3D; + } + if (resource.dimension == ImageDimension::Dim2DArray || + resource.dimension == ImageDimension::Dim2DMsaaArray) { + return ShaderRecompiler::IR::BindlessImages2DArray; + } + return ShaderRecompiler::IR::BindlessImages2D; +} + +// A heap entry the bindless array of this binding can hold: a float-sampled, single-sample +// texture of a matching shape. Anything else stays the placeholder rather than reaching +// ResolveTexture, which exits on descriptors a draw would never bind that way. +static bool BindlessCompatible(const ShaderTextureResource& descriptor, uint32_t binding) { + if (descriptor.IsNull() || + Prospero::SampledTextureNumericClass(descriptor.Format()) != + Prospero::TextureNumericClass::Float) { + return false; + } + switch (descriptor.Type()) { + case Prospero::ImageType::kColor2D: + return binding == ShaderRecompiler::IR::BindlessImages2D || + binding == ShaderRecompiler::IR::BindlessImages2DArray; + case Prospero::ImageType::kColor2DArray: + return binding == ShaderRecompiler::IR::BindlessImages2D || + binding == ShaderRecompiler::IR::BindlessImages2DArray; + case Prospero::ImageType::kCube: return binding == ShaderRecompiler::IR::BindlessImagesCube; + case Prospero::ImageType::kColor3D: return binding == ShaderRecompiler::IR::BindlessImages3D; + default: return false; + } +} + +bool RenderExecutor::ResolveBindlessKey(BindlessTable::Heap& heap, uint32_t key) { + auto& table = m_context.GetBindlessTable(); + ShaderRecompiler::IR::DescriptorValue value {}; + value.dword_count = 8u; + const auto address = heap.base + heap.table_offset + static_cast<uint64_t>(key) * 32u; + heap.settled[key] = 1; + if (!Libs::LibKernel::Memory::TryReadBacking(address, value.dwords.data(), 32u)) { + table.SetTranslation(heap, key, 0u); + return false; + } + const auto descriptor = DecodeNativeDescriptor<ShaderTextureResource>(value); + if (!BindlessCompatible(descriptor, heap.binding)) { + table.SetTranslation(heap, key, 0u); + return false; + } + auto binding = ResolveTexture(heap.resource, value); + auto& texture_cache = m_context.GetTextureCache(); + auto* image = texture_cache.m_slot_images.try_get(binding.image_id); + if (image == nullptr || image->info.data.Empty()) { + table.SetTranslation(heap, key, 0u); + return false; + } + BindImage(binding.image_id, false); + const auto view = texture_cache.FindTexture(binding.image_id, binding.desc); + image = texture_cache.m_slot_images.try_get(binding.image_id); + const auto slot = table.AllocateSlot(heap.binding); + if (image == nullptr || view == nullptr || slot == 0) { + table.SetTranslation(heap, key, 0u); + return false; + } + const auto layout = image->info.IsDepth() ? vk::ImageLayout::eDepthStencilReadOnlyOptimal + : vk::ImageLayout::eShaderReadOnlyOptimal; + table.WriteSlot(heap.binding, slot, view, layout); + heap.slots[key] = slot; + image->bindless_pinned = true; + image->usage.texture = true; + heap.resolved.push_back(binding.image_id); + table.AddImageReference(binding.image_id, heap, key); + table.SetTranslation(heap, key, slot); + return true; +} + +void RenderExecutor::ResolveBindlessRequests() { + const auto frame = m_context.GetGraphics().presented_frames.load(std::memory_order_relaxed); + if (frame == m_bindless_frame) { + return; + } + auto& table = m_context.GetBindlessTable(); + auto& scheduler = m_context.GetCommandScheduler(); + // The flags come from a snapshot recorded in an earlier frame. Until the GPU has executed + // it, check again at the next bindless draw instead of waiting. + if (table.SnapshotRecorded() && !table.SnapshotReady(scheduler)) { + return; + } + m_bindless_frame = frame; + m_context.GetBindlessTable().DrainWatchdogReports(frame); + if (!table.SnapshotRecorded()) { + table.RecordFeedbackSnapshot(scheduler); + return; + } + table.ConsumeSnapshot(); + // Each texture may upload and detile; spread first sight of a scene over a few frames. + constexpr uint32_t Budget = 128; + uint32_t resolved = 0; + for (auto& heap: m_context.GetBindlessTable().Heaps()) { + m_bindless_requests.clear(); + m_context.GetBindlessTable().TakeRequests(heap, m_bindless_requests); + for (const auto key: m_bindless_requests) { + if (heap.settled[key] != 0) { + continue; + } + if (resolved >= Budget) { + break; // still pending: the next frame flags it again + } + resolved += ResolveBindlessKey(heap, key) ? 1u : 0u; + } + } + table.RecordFeedbackSnapshot(scheduler); +} + +// Bindless samplers: the S# records of each sampler heap a draw indexes are mirrored into the +// sampler array of set 1, once per frame per heap, and the shader gets the region base and record +// count. Keys outside it, and heaps that cannot be read, use the default sampler in slot 0. +void RenderExecutor::PrepareBindlessSamplers(const ShaderStageRuntime& runtime, + PreparedBindings& prepared) { + const auto& program = *runtime.program; + const auto& snapshot = *runtime.resources; + if (snapshot.bindless_sampler_heaps.empty()) { + return; + } + auto& table = m_context.GetBindlessTable(); + auto& cache = m_context.GetSamplerCache(); + { + ShaderSamplerResource default_sampler; + std::ranges::copy(ShaderRecompiler::IR::BindlessDefaultSampler, default_sampler.fields); + table.WriteDefaultSampler(cache.GetSampler(default_sampler, false)); + } + const auto frame = m_context.GetGraphics().presented_frames.load(std::memory_order_relaxed); + constexpr uint64_t MaxRecords = 1024; + for (const auto& use: snapshot.bindless_sampler_heaps) { + uint32_t region = 0; + uint32_t entries = 0; + if (table.SamplersEnabled() && use.sampler < program.info.samplers.size()) { + const auto& sampler = program.info.samplers[use.sampler]; + const uint32_t flags = + (sampler.depth_compare ? BindlessTable::SamplerDepthCompare : 0u) | + (sampler.force_point_filtering ? BindlessTable::SamplerPointFiltering : 0u) | + (sampler.integer_border ? BindlessTable::SamplerIntegerBorder : 0u); + auto* heap = table.FindOrCreateSamplerHeap(use.base, use.table_offset, flags); + if (heap->checked_frame != frame) { + heap->checked_frame = frame; + const uint64_t available = + use.size > use.table_offset ? (use.size - use.table_offset) / 16u : 0u; + std::vector<std::array<uint32_t, 4>> records(std::min(available, MaxRecords)); + const uint64_t address = use.base + use.table_offset; + const uint64_t bytes = records.size() * sizeof(records[0]); + if (!records.empty() && + !m_context.GetBufferCache().HasGpuDirtyBytes(address, bytes) && + Libs::LibKernel::Memory::TryReadBacking(address, records.data(), bytes)) { + (void)table.MirrorSamplerHeap(*heap, records, cache); + } + } + region = heap->region; + entries = region != 0 ? static_cast<uint32_t>(heap->records.size()) : 0u; + } + prepared.bindless_patches.push_back({use.mapping_offset, region, entries}); + } +} + +void RenderExecutor::PrepareBindlessHeaps(const ShaderStageRuntime& runtime, + PreparedBindings& prepared) { + prepared.bindless_patches.clear(); + prepared.bindless_images.clear(); + const auto& program = *runtime.program; + const auto& snapshot = *runtime.resources; + auto& table = m_context.GetBindlessTable(); + if ((snapshot.bindless_heaps.empty() && snapshot.bindless_sampler_heaps.empty()) || + !table.Enabled()) { + return; + } + PrepareBindlessSamplers(runtime, prepared); + if (snapshot.bindless_heaps.empty()) { + return; + } + ResolveBindlessRequests(); + for (const auto& use: snapshot.bindless_heaps) { + if (use.image >= program.info.images.size()) { + continue; + } + const auto& resource = program.info.images[use.image]; + const uint64_t span = use.size > use.table_offset ? use.size - use.table_offset : 0; + const auto entries = static_cast<uint32_t>(std::min<uint64_t>(span / 32u, 1u << 18u)); + auto* heap = table.FindOrCreateHeap(use.base, use.table_offset, BindlessBindingFor(resource), + entries, resource); + if (heap == nullptr) { + continue; // region 0, count 0: every key samples the placeholder + } ``` _🎯 Functional Correctness_ | _🟠 Major_ | _⚡ Quick win_ **The code skips the SRT patch when heap allocation fails, but the comment says the result is region 0 and count 0.** When `use.image` is out of range or `FindOrCreateHeap` returns null, the loop continues without pushing a patch. `RebindBuffers` then uploads the unpatched `snapshot.flattened_srt`. If no other patch exists, the whole upload is unpatched. `BindlessSlot` reads base and count from `mapping_offset`. It then gets guest data instead of `{0, 0}`, and it indexes arbitrary translation and feedback entries. The sampler path already pushes `{use.mapping_offset, 0, 0}` in the same situation. <details> <summary>Proposed fix</summary> ```diff for (const auto& use: snapshot.bindless_heaps) { if (use.image >= program.info.images.size()) { + prepared.bindless_patches.push_back({use.mapping_offset, 0u, 0u}); continue; } ... if (heap == nullptr) { + prepared.bindless_patches.push_back({use.mapping_offset, 0u, 0u}); continue; // region 0, count 0: every key samples the placeholder } ``` </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 for (const auto& use: snapshot.bindless_heaps) { if (use.image >= program.info.images.size()) { prepared.bindless_patches.push_back({use.mapping_offset, 0u, 0u}); continue; } const auto& resource = program.info.images[use.image]; const uint64_t span = use.size > use.table_offset ? use.size - use.table_offset : 0; const auto entries = static_cast<uint32_t>(std::min<uint64_t>(span / 32u, 1u << 18u)); auto* heap = table.FindOrCreateHeap(use.base, use.table_offset, BindlessBindingFor(resource), entries, resource); if (heap == nullptr) { prepared.bindless_patches.push_back({use.mapping_offset, 0u, 0u}); continue; // region 0, count 0: every key samples the placeholder } ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:bdf9cddf4f3c71e93c056303 --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -646,0 +683,4 @@
diagnostics_config.pNext = &diagnostics_features;
create_info.pNext = &diagnostics_config;
}
}
Author
Owner

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

🚀 Performance & Scalability | 🟡 Minor | ⚡ Quick win

Put the NV diagnostics configuration behind a debug option.

This block enables eEnableShaderDebugInfo | eEnableResourceTracking | eEnableShaderErrorReporting on every NVIDIA device that exposes the extension. These are Aftermath-style debugging flags, and they add runtime overhead to all rendering. Every user on an NVIDIA GPU pays this cost, even without a device-loss investigation.

Fix: enable the flags only when a debug option is set, for example Config::GraphicsDebugDumpEnabled() or a dedicated switch.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-30 00:19 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/937#discussion_r4139620663) _🚀 Performance & Scalability_ | _🟡 Minor_ | _⚡ Quick win_ **Put the NV diagnostics configuration behind a debug option.** This block enables `eEnableShaderDebugInfo | eEnableResourceTracking | eEnableShaderErrorReporting` on every NVIDIA device that exposes the extension. These are Aftermath-style debugging flags, and they add runtime overhead to all rendering. Every user on an NVIDIA GPU pays this cost, even without a device-loss investigation. Fix: enable the flags only when a debug option is set, for example `Config::GraphicsDebugDumpEnabled()` or a dedicated switch. <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:84b7acb6e5c1c8c7d1bd6cfd --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -526,0 +533,4 @@
const auto vector_type = uint_output ? TypeU32Vector(state, 4)
: sint_output ? TypeI32Vector(state, 4)
: TypeF32Vector(state, 4);
auto value = ExportVector(ctx, data, exp, uint_output || sint_output);
Author
Owner

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

The pixel MRT store type and the declared output type use different predicates.

DefineOutputs picks the output variable type only from target_uint_mask and target_sint_mask. EmitSetAttribute also treats MrtOutputMode == 7 (UINT16_ABGR) as uint_output. For a format-7 export to a float or SINT attachment, the stored vector type differs from the variable type. This produces invalid SPIR-V.

  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterFlow.cpp#L533-L541: derive uint_output and sint_output from the same masks as DefineOutputs, so that they are mutually exclusive. Use format 7 only to choose the raw ExportVector unpacking, then convert the value to the attachment type before the store.
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterModule.cpp#L660-L668: keep the mask-based type as the only source of truth, and share one helper with EmitSetAttribute.
📍 Affects 2 files
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterFlow.cpp#L533-L541 (this comment)
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterModule.cpp#L660-L668
**@⁠coderabbitai[bot]** on GitHub · 2026-09-30 00:19 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/937#discussion_r4139620666) _🎯 Functional Correctness_ | _🟠 Major_ | _⚡ Quick win_ **The pixel MRT store type and the declared output type use different predicates.** `DefineOutputs` picks the output variable type only from `target_uint_mask` and `target_sint_mask`. `EmitSetAttribute` also treats `MrtOutputMode == 7` (UINT16_ABGR) as `uint_output`. For a format-7 export to a float or SINT attachment, the stored vector type differs from the variable type. This produces invalid SPIR-V. - `src/graphics/shader/recompiler/backend/spirv/spirvEmitterFlow.cpp#L533-L541`: derive `uint_output` and `sint_output` from the same masks as `DefineOutputs`, so that they are mutually exclusive. Use format 7 only to choose the raw `ExportVector` unpacking, then convert the value to the attachment type before the store. - `src/graphics/shader/recompiler/backend/spirv/spirvEmitterModule.cpp#L660-L668`: keep the mask-based type as the only source of truth, and share one helper with `EmitSetAttribute`. <details> <summary>📍 Affects 2 files</summary> - `src/graphics/shader/recompiler/backend/spirv/spirvEmitterFlow.cpp#L533-L541` (this comment) - `src/graphics/shader/recompiler/backend/spirv/spirvEmitterModule.cpp#L660-L668` </details> <!-- consolidated_sites_start --> <!-- <consolidated_sites> <site> <role>anchor</role> <file>src/graphics/shader/recompiler/backend/spirv/spirvEmitterFlow.cpp</file> <line_range>533-541</line_range> </site> <site> <role>sibling</role> <file>src/graphics/shader/recompiler/backend/spirv/spirvEmitterModule.cpp</file> <line_range>660-668</line_range> </site> </consolidated_sites> --> <!-- consolidated_sites_end --> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:b148e6c5c5f6b89ce1042001 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-30 00:19 UTC · original
On src/graphics/shader/recompiler/backend/spirv/spirvEmitterModule.cpp line 202 (outdated):

@@ -169,7 +180,94 @@ uint32_t F32ArrayType(EmitterState& state, uint32_t count) {
 	return state.builder.Type(spv::OpTypeArray, TypeF32(state), ConstantU32(state, count));
 }
 
+// Set 1 (BindlessBindings.h): one runtime array per image type, aliasing the binding of its
+// dimension, and the translation buffer. Declared before the entry point collects globals.
+void DefineBindlessImages(EmitterState& state) {
+	for (const auto& image: state.program.info.images) {
+		if (!image.bindless) {
+			continue;
+		}
+		const auto type = ImageType(state, image);
+		if (state.bindless_image_variables.contains(type)) {
+			continue;
+		}
+		uint32_t binding = IR::BindlessImages2D;
+		if (image.cube) {
+			binding = IR::BindlessImagesCube;
+		} else if (image.dimension == ImageDimension::Dim3D) {
+			binding = IR::BindlessImages3D;
+		} else if (image.dimension == ImageDimension::Dim2DArray ||
+		           image.dimension == ImageDimension::Dim2DMsaaArray) {
+			binding = IR::BindlessImages2DArray;
+		}

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Some bindless image types go to set-1 bindings of a different shape.

The binding selection gives these images the wrong binding:

  • Dim1D, Dim1DArray and Dim2DMsaa fall through to BindlessImages2D.
  • Dim2DMsaaArray goes to BindlessImages2DArray.

ImageType(state, image) still declares the real Dim, Arrayed and MS values for these images. The runtime array then aliases a binding whose views are 2D or 2D-array and not multisampled. Vulkan requires the view type to match the OpTypeImage dimensionality, arrayness and multisampling. A mismatch is undefined behavior and can cause device loss.

Reject these dimensions for bindless images before materialization, so they keep the enumerated path. The other option is separate bindings for them.

Proposed guard
 		uint32_t binding = IR::BindlessImages2D;
 		if (image.cube) {
 			binding = IR::BindlessImagesCube;
 		} else if (image.dimension == ImageDimension::Dim3D) {
 			binding = IR::BindlessImages3D;
-		} else if (image.dimension == ImageDimension::Dim2DArray ||
-		           image.dimension == ImageDimension::Dim2DMsaaArray) {
+		} else if (image.dimension == ImageDimension::Dim2DArray) {
 			binding = IR::BindlessImages2DArray;
+		} else if (image.dimension != ImageDimension::Dim2D) {
+			EXIT("bindless image dimension %u has no set-1 binding\n",
+			     static_cast<uint32_t>(image.dimension));
 		}
📝 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.

		uint32_t binding = IR::BindlessImages2D;
		if (image.cube) {
			binding = IR::BindlessImagesCube;
		} else if (image.dimension == ImageDimension::Dim3D) {
			binding = IR::BindlessImages3D;
		} else if (image.dimension == ImageDimension::Dim2DArray) {
			binding = IR::BindlessImages2DArray;
		} else if (image.dimension != ImageDimension::Dim2D) {
			EXIT("bindless image dimension %u has no set-1 binding\n",
			     static_cast<uint32_t>(image.dimension));
		}
**@⁠coderabbitai[bot]** on GitHub · 2026-09-30 00:19 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/937#discussion_r4139620670) On `src/graphics/shader/recompiler/backend/spirv/spirvEmitterModule.cpp` line 202 (outdated): ```diff @@ -169,7 +180,94 @@ uint32_t F32ArrayType(EmitterState& state, uint32_t count) { return state.builder.Type(spv::OpTypeArray, TypeF32(state), ConstantU32(state, count)); } +// Set 1 (BindlessBindings.h): one runtime array per image type, aliasing the binding of its +// dimension, and the translation buffer. Declared before the entry point collects globals. +void DefineBindlessImages(EmitterState& state) { + for (const auto& image: state.program.info.images) { + if (!image.bindless) { + continue; + } + const auto type = ImageType(state, image); + if (state.bindless_image_variables.contains(type)) { + continue; + } + uint32_t binding = IR::BindlessImages2D; + if (image.cube) { + binding = IR::BindlessImagesCube; + } else if (image.dimension == ImageDimension::Dim3D) { + binding = IR::BindlessImages3D; + } else if (image.dimension == ImageDimension::Dim2DArray || + image.dimension == ImageDimension::Dim2DMsaaArray) { + binding = IR::BindlessImages2DArray; + } ``` _🎯 Functional Correctness_ | _🟠 Major_ | _⚡ Quick win_ **Some bindless image types go to set-1 bindings of a different shape.** The binding selection gives these images the wrong binding: - `Dim1D`, `Dim1DArray` and `Dim2DMsaa` fall through to `BindlessImages2D`. - `Dim2DMsaaArray` goes to `BindlessImages2DArray`. `ImageType(state, image)` still declares the real `Dim`, `Arrayed` and `MS` values for these images. The runtime array then aliases a binding whose views are 2D or 2D-array and not multisampled. Vulkan requires the view type to match the `OpTypeImage` dimensionality, arrayness and multisampling. A mismatch is undefined behavior and can cause device loss. Reject these dimensions for bindless images before materialization, so they keep the enumerated path. The other option is separate bindings for them. <details> <summary>Proposed guard</summary> ```diff uint32_t binding = IR::BindlessImages2D; if (image.cube) { binding = IR::BindlessImagesCube; } else if (image.dimension == ImageDimension::Dim3D) { binding = IR::BindlessImages3D; - } else if (image.dimension == ImageDimension::Dim2DArray || - image.dimension == ImageDimension::Dim2DMsaaArray) { + } else if (image.dimension == ImageDimension::Dim2DArray) { binding = IR::BindlessImages2DArray; + } else if (image.dimension != ImageDimension::Dim2D) { + EXIT("bindless image dimension %u has no set-1 binding\n", + static_cast<uint32_t>(image.dimension)); } ``` </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 uint32_t binding = IR::BindlessImages2D; if (image.cube) { binding = IR::BindlessImagesCube; } else if (image.dimension == ImageDimension::Dim3D) { binding = IR::BindlessImages3D; } else if (image.dimension == ImageDimension::Dim2DArray) { binding = IR::BindlessImages2DArray; } else if (image.dimension != ImageDimension::Dim2D) { EXIT("bindless image dimension %u has no set-1 binding\n", static_cast<uint32_t>(image.dimension)); } ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:02259bc6e670ecd32e46f2f1 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-30 00:19 UTC · original
On src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp line 343 (outdated):

@@ -332,21 +335,585 @@ void PatchStructuredPhis(ValueEmitContext& ctx, StructuredFunctionState& structu
 	}
 }
 
+// Research: a loop watchdog for shaders that read memory through device addresses. A page such
+// a shader touches first reads as zero until the fault buffer maps it for the next dispatch;
+// a list walk fed zeros never ends and the device is lost before that dispatch. Each loop
+// whose continue block branches straight back to its header counts its iterations and leaves
+// through its merge block after LoopWatchdogLimit of them.
+constexpr uint32_t LoopWatchdogLimit = 4096;

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Gate the 4096-iteration cutoffs or raise the limit: legitimate long loops now end early with no error.

Both watchdogs are always on:

  • The loop watchdog applies to every structured program with uses_dma.
  • The dispatcher watchdog applies to every program that uses the dispatcher fallback.

LoopWatchdogLimit = 4096 caps a loop at 4096 iterations. MaxDispatcherTransitions = 4096 counts block transitions, not iterations. A loop body of three blocks is therefore cut after about 1365 iterations.

Correct shaders can exceed these limits. Examples are list walks over large buffers, per-element compute loops, and long blur or search loops. When a loop is cut, the invocation writes wrong results and nothing is reported. The emulator logs nothing and the draw or dispatch is not skipped.

The PR description says new behavior is opt-in except crash and hang fixes. This is a hang fix, but it applies to every qualifying shader.

Recommended changes:

  • Put the cutoff behind a config or option flag, as watchdog_reports already is.
  • Or raise the limits a lot. For the dispatcher, count loop back-edges instead of all block transitions.

Also applies to: 934-950

**@⁠coderabbitai[bot]** on GitHub · 2026-09-30 00:19 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/937#discussion_r4139620674) On `src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp` line 343 (outdated): ```diff @@ -332,21 +335,585 @@ void PatchStructuredPhis(ValueEmitContext& ctx, StructuredFunctionState& structu } } +// Research: a loop watchdog for shaders that read memory through device addresses. A page such +// a shader touches first reads as zero until the fault buffer maps it for the next dispatch; +// a list walk fed zeros never ends and the device is lost before that dispatch. Each loop +// whose continue block branches straight back to its header counts its iterations and leaves +// through its merge block after LoopWatchdogLimit of them. +constexpr uint32_t LoopWatchdogLimit = 4096; ``` _🎯 Functional Correctness_ | _🟠 Major_ | _⚡ Quick win_ **Gate the 4096-iteration cutoffs or raise the limit: legitimate long loops now end early with no error.** Both watchdogs are always on: - The loop watchdog applies to every structured program with `uses_dma`. - The dispatcher watchdog applies to every program that uses the dispatcher fallback. `LoopWatchdogLimit = 4096` caps a loop at 4096 iterations. `MaxDispatcherTransitions = 4096` counts block transitions, not iterations. A loop body of three blocks is therefore cut after about 1365 iterations. Correct shaders can exceed these limits. Examples are list walks over large buffers, per-element compute loops, and long blur or search loops. When a loop is cut, the invocation writes wrong results and nothing is reported. The emulator logs nothing and the draw or dispatch is not skipped. The PR description says new behavior is opt-in except crash and hang fixes. This is a hang fix, but it applies to every qualifying shader. Recommended changes: - Put the cutoff behind a config or option flag, as `watchdog_reports` already is. - Or raise the limits a lot. For the dispatcher, count loop back-edges instead of all block transitions. Also applies to: 934-950 <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:cade6047537136fef5f73bd9 --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -506,0 +521,4 @@
}
m_failed = true;
return;
}
Author
Owner

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

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Nonfatal Fail lets PlanScalarReads index memory_info out of bounds.

Fail used to exit, so code after a Fail call could assume the call never returned. In TranslationNonFatal() mode it now sets m_failed and returns. Several callers written for the old behavior keep executing after the failure.

In PlanScalarReads, lines 862-866 run:

  • if (flags.index >= m_program.memory_info.size()) Fail(...)
  • then const auto& memory = m_program.memory_info[flags.index];

With an out-of-range index, that reference is out of bounds and memory.kind reads past the vector. Line 865 has the same problem: after the NumArgs failure, the loop still reads inst.Arg(arg).

Run() checks m_failed only after PlanIndirectImages(). Every block of PlanScalarReads, then EliminateDeadCode, then PlanIndirectImages runs on the bad state first.

Fix: return or skip after each Fail call in PlanScalarReads, and check m_failed right after PlanScalarReads() in Run().

Proposed fix
-				if (flags.index >= m_program.memory_info.size())
-					Fail(flags.pc, "memory metadata index is out of range");
-				if (inst.NumArgs() < (image.needs_sampler ? 2u : 1u))
-					Fail(flags.pc, "memory operation has no resource handle");
+				if (flags.index >= m_program.memory_info.size()) {
+					Fail(flags.pc, "memory metadata index is out of range");
+					return;
+				}
+				if (inst.NumArgs() < (image.needs_sampler ? 2u : 1u)) {
+					Fail(flags.pc, "memory operation has no resource handle");
+					return;
+				}
 		PlanScalarReads();
+		if (m_failed) {
+			return;
+		}
 		EliminateDeadCode(m_program.blocks);
**@⁠coderabbitai[bot]** on GitHub · 2026-09-30 00:19 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/937#discussion_r4139620682) _🩺 Stability & Availability_ | _🟠 Major_ | _⚡ Quick win_ **Nonfatal `Fail` lets `PlanScalarReads` index `memory_info` out of bounds.** `Fail` used to exit, so code after a `Fail` call could assume the call never returned. In `TranslationNonFatal()` mode it now sets `m_failed` and returns. Several callers written for the old behavior keep executing after the failure. In `PlanScalarReads`, lines 862-866 run: - `if (flags.index >= m_program.memory_info.size()) Fail(...)` - then `const auto& memory = m_program.memory_info[flags.index];` With an out-of-range index, that reference is out of bounds and `memory.kind` reads past the vector. Line 865 has the same problem: after the `NumArgs` failure, the loop still reads `inst.Arg(arg)`. `Run()` checks `m_failed` only after `PlanIndirectImages()`. Every block of `PlanScalarReads`, then `EliminateDeadCode`, then `PlanIndirectImages` runs on the bad state first. Fix: return or skip after each `Fail` call in `PlanScalarReads`, and check `m_failed` right after `PlanScalarReads()` in `Run()`. <details> <summary>Proposed fix</summary> ```diff - if (flags.index >= m_program.memory_info.size()) - Fail(flags.pc, "memory metadata index is out of range"); - if (inst.NumArgs() < (image.needs_sampler ? 2u : 1u)) - Fail(flags.pc, "memory operation has no resource handle"); + if (flags.index >= m_program.memory_info.size()) { + Fail(flags.pc, "memory metadata index is out of range"); + return; + } + if (inst.NumArgs() < (image.needs_sampler ? 2u : 1u)) { + Fail(flags.pc, "memory operation has no resource handle"); + return; + } ``` ```diff PlanScalarReads(); + if (m_failed) { + return; + } EliminateDeadCode(m_program.blocks); ``` </details> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:b6e50b92f19a6f42ca0df0a9 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-30 00:19 UTC · original
On src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp line 2464 (outdated):

@@ -1439,29 +2279,243 @@ class Tracker {
 		std::copy_n(table_source.dwords.begin(), table_source.dword_count,
 		            image_source.dwords.begin() + 4u);
 		image_source.indirect_image = indirect;
-		plan.handle = &handle;
-		plan.source = InternSource(image_source);
-		plan.key = key;
-		plan.roots = image_source.dwords;
+		if (key_mask != UINT32_MAX) {
+			// The bindless lookup takes the key itself, so the mask the shader applies to the
+			// scaled key becomes an instruction on the key, just before the handle.
+			auto*      block = handle.Parent();
+			const auto where = std::ranges::find_if(
+			    block->Instructions(), [&](const Inst& inst) { return &inst == &handle; });
+			key = Value(&*block->PrependNewInst(where, ValueOpcode::BitwiseAnd32,
+			                                    {key, Value(key_mask)}));
+		}
+		plan.handle                 = &handle;
+		plan.source                 = InternSource(image_source);
+		plan.key                    = key;
+		plan.roots                  = image_source.dwords;
 		return true;
 	}
 
 	const IndirectImagePlan* FindIndirectImage(const Inst& handle) const {
 		const auto found =
 		    std::find_if(m_indirect_images.begin(), m_indirect_images.end(),
-		                 [&](const IndirectImagePlan& plan) {
-			    return plan.handle == &handle;
-		    });
+		                 [&](const IndirectImagePlan& plan) { return plan.handle == &handle; });
 		return found == m_indirect_images.end() ? nullptr : &*found;
 	}
 
+	bool IsLiveTableMemory(uint32_t index) const {
+		return std::ranges::find(m_live_table_memory, index) != m_live_table_memory.end();
+	}
+
 	bool IsIndirectPlanningMemory(uint32_t index) const {
+		if (IsLiveTableMemory(index)) {
+			return false;
+		}
 		return std::any_of(m_indirect_images.begin(), m_indirect_images.end(),
 		                   [&](const IndirectImagePlan& plan) {
-			return std::ranges::find(plan.memory, index) != plan.memory.end();
+			return std::ranges::find(plan.memory, index) != plan.memory.end() ||
+			       std::ranges::find(plan.extra_memory, index) != plan.extra_memory.end();
 		});
 	}
 
+	const BindlessSamplerPlan* FindBindlessSampler(const Inst& handle) const {
+		const auto found =
+		    std::ranges::find(m_bindless_samplers, &handle, &BindlessSamplerPlan::handle);
+		return found == m_bindless_samplers.end() ? nullptr : &*found;
+	}
+
+	// A bindless sampler: all four S# dwords are scalar reads of one sampler heap (a buffer of
+	// 16-byte records) at (key << 4) + record offset, with a GPU-computed key and a heap V# the
+	// host can evaluate. The shader keeps the key and indexes the bindless sampler array, which
+	// the host mirrors from the heap.
+	bool TryMakeBindlessSampler(Inst& handle, BindlessSamplerPlan& plan) {
+		Inst*    table_handle = nullptr;
+		Value    key;
+		uint32_t table_offset = 0;
+		for (uint32_t dword = 0; dword < 4u; ++dword) {
+			auto* read = ResolveInvariantPhi(m_program, handle.Arg(dword)).TryInstruction();
+			if (read == nullptr) {
+				return false;
+			}
+			uint32_t    memory_index = 0;
+			const auto* memory       = ScalarReadMemory(*read, memory_index);
+			if (memory == nullptr || memory->kind != ResourceKind::ScalarBuffer ||
+			    memory->offset > INT32_MAX || (memory->offset & 3u) != 0u ||
+			    !MemoryIndexBelongsTo(memory_index, *read)) {
+				return false;
+			}
+			auto*    current_handle = read->Arg(0).Resolve().TryInstruction();
+			Value    current_key;
+			uint32_t offset = 0;
+			if (current_handle == nullptr ||
+			    current_handle->GetOpcode() != ValueOpcode::GetBufferResource ||
+			    (table_handle != nullptr &&
+			     !EquivalentValue(m_program, Value(table_handle), Value(current_handle))) ||
+			    !MatchTableOffset(read->Arg(1), current_key, offset, 4u) ||
+			    memory->offset > UINT32_MAX - offset) {
+				return false;
+			}
+			offset += memory->offset;
+			if (dword == 0u) {
+				key          = current_key;
+				table_offset = offset;
+			} else if (!EquivalentValue(m_program, key, current_key) ||
+			           static_cast<uint64_t>(table_offset) + dword * sizeof(uint32_t) != offset) {
+				return false;
+			}
+			table_handle          = current_handle;
+			plan.reads[dword]     = read;
+			plan.memory[dword]    = memory_index;
+			plan.exclusive[dword] =
+			    !read->Uses().empty() && std::ranges::all_of(read->Uses(), [](const Use& use) {
+				    return use.user->GetOpcode() == ValueOpcode::GetSamplerResource ||
+				           FeedsOnlyDeadPhis(*use.user);
+			    });
+		}
+		DescriptorSource table_source;
+		if (!MakeRuntimeTableSource(*plan.reads[0], table_source) ||
+		    table_source.dword_count != 4u) {
+			return false;
+		}
+		DescriptorSource source;
+		source.dword_count = 4u;
+		source.dwords.fill(Value(0u));
+		for (uint32_t dword = 0; dword < 3u; dword++) {
+			source.dwords[dword]    = table_source.dwords[dword];
+			plan.table_roots[dword] = table_source.dwords[dword];
+		}
+		source.bindless_sampler = DescriptorSource::BindlessSampler {.table_offset = table_offset};
+		plan.handle             = &handle;
+		plan.key                = key;
+		plan.source             = InternSource(source);
+		return true;
+	}
+
+	void PlanBindlessSamplers() {
+		// Opt-in while a regression is investigated: with the game's own samplers the title's
+		// fog shows a bright arch (DEBUGGING.md, 2026-09-28). KYTY_BINDLESS_SAMPLERS=1 enables them.
+		static const bool enabled = std::getenv("KYTY_BINDLESS_SAMPLERS") != nullptr &&
+		                            std::getenv("KYTY_BINDLESS_SAMPLERS")[0] == '1';
+		if (!m_program.bindless_images || !enabled) {
+			return;
+		}
+		for (auto* block: m_program.blocks) {
+			for (auto& inst: *block) {
+				if (ImageOpcodeInfoOf(inst.GetOpcode()).access == ImageAccess::None ||
+				    inst.NumArgs() < 2u) {
+					continue;
+				}
+				auto* sampler = inst.Arg(1).Resolve().TryInstruction();
+				if (sampler == nullptr || sampler->GetOpcode() != ValueOpcode::GetSamplerResource ||
+				    sampler->NumArgs() != 4u || FindBindlessSampler(*sampler) != nullptr) {
+					continue;
+				}
+				const auto       flags  = inst.Flags<MemoryFlags>();
+				const auto&      memory = m_program.memory_info[flags.index];
+				DescriptorSource descriptor;
+				MakeSource(*sampler, 4u, true,
+				           (memory.image_sample_flags & Decoder::ImageSampleFlagAdjust) != 0,
+				           memory.sampler * 4u, descriptor, flags.pc);
+				uint32_t bad_dword = 0;
+				if (ValidateSource(descriptor, bad_dword)) {
+					continue;
+				}
+				BindlessSamplerPlan plan;
+				if (TryMakeBindlessSampler(*sampler, plan)) {
+					m_bindless_samplers.push_back(plan);
+				}
+			}
+		}
+	}
+
+	// Research stopgap: a bindless sampler (selected per material from a sampler heap, like
+	// the image beside it) has no indirect plan. Before the walk, give it one fixed sampler
+	// (trilinear, wrap, full LOD range) and make the heap reads it strands planning-only, as
+	// an indirect image's table reads are: registered as buffers, they would bind a
+	// descriptor that dead-code elimination then deletes. Only the filtering and edge
+	// addressing can differ from the material's own sampler.
+	void PlanDefaultSamplers() {
+		if (!Frontend::TranslationNonFatal()) {
+			return;
+		}
+		constexpr std::array<uint32_t, 4> DefaultSampler {
+		    0x00000000u,                             // wrap on every axis
+		    0xfffu << 12u,                           // max_lod 255.9
+		    (1u << 20u) | (1u << 22u) | (2u << 26u), // bilinear mag/min, linear mip
+		    0x00000000u};
+		for (auto* block: m_program.blocks) {
+			for (auto& inst: *block) {
+				if (ImageOpcodeInfoOf(inst.GetOpcode()).access == ImageAccess::None ||
+				    inst.NumArgs() < 2u) {
+					continue;
+				}
+				auto* sampler = inst.Arg(1).Resolve().TryInstruction();
+				if (sampler == nullptr || sampler->GetOpcode() != ValueOpcode::GetSamplerResource ||
+				    sampler->NumArgs() != 4u || FindBindlessSampler(*sampler) != nullptr) {
+					continue;
+				}
+				DescriptorSource descriptor;
+				descriptor.dword_count = 4u;
+				for (uint32_t dword = 0; dword < 4u; dword++) {
+					descriptor.dwords[dword] = LowerDescriptorPhi(sampler->Arg(dword));
+				}
+				uint32_t bad_dword = 0;
+				if (ValidateSource(descriptor, bad_dword)) {
+					continue;
+				}

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Use MakeSource in PlanDefaultSamplers, or valid samplers get replaced by the default sampler.

PlanDefaultSamplers decides whether a sampler is valid by calling LowerDescriptorPhi on each raw dword. Collect and PlanBindlessSamplers use MakeSource, which also does three things this check skips:

  • It resolves register sources through NativeDescriptorSource.
  • It applies CanonicalizeSampleAdjustDword3 when ImageSampleFlagAdjust is set.
  • It sets dword 3 to zero when no clamp axis selects border mode.

Without these steps, some samplers fail ValidateSource here even though GetHandle would accept them. For example, a SampleAdjust sampler whose dword 3 carries lane-dependent reserved scratch bits fails this check. TestSampleAdjustSamplerScratch covers that shape.

In nonfatal mode, PlanDefaultSamplers overwrites such a sampler with the fixed sampler and marks its reads planning-only. The game's filtering and addressing are lost, and nothing reports a failure.

Build the descriptor the same way PlanBindlessSamplers does.

Proposed fix
-				DescriptorSource descriptor;
-				descriptor.dword_count = 4u;
-				for (uint32_t dword = 0; dword < 4u; dword++) {
-					descriptor.dwords[dword] = LowerDescriptorPhi(sampler->Arg(dword));
-				}
+				const auto       flags  = inst.Flags<MemoryFlags>();
+				const auto&      memory = m_program.memory_info[flags.index];
+				DescriptorSource descriptor;
+				MakeSource(*sampler, 4u, true,
+				           (memory.image_sample_flags & Decoder::ImageSampleFlagAdjust) != 0,
+				           memory.sampler * 4u, descriptor, flags.pc);
+				if (m_failed) {
+					return;
+				}
**@⁠coderabbitai[bot]** on GitHub · 2026-09-30 00:19 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/937#discussion_r4139620691) On `src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp` line 2464 (outdated): ```diff @@ -1439,29 +2279,243 @@ class Tracker { std::copy_n(table_source.dwords.begin(), table_source.dword_count, image_source.dwords.begin() + 4u); image_source.indirect_image = indirect; - plan.handle = &handle; - plan.source = InternSource(image_source); - plan.key = key; - plan.roots = image_source.dwords; + if (key_mask != UINT32_MAX) { + // The bindless lookup takes the key itself, so the mask the shader applies to the + // scaled key becomes an instruction on the key, just before the handle. + auto* block = handle.Parent(); + const auto where = std::ranges::find_if( + block->Instructions(), [&](const Inst& inst) { return &inst == &handle; }); + key = Value(&*block->PrependNewInst(where, ValueOpcode::BitwiseAnd32, + {key, Value(key_mask)})); + } + plan.handle = &handle; + plan.source = InternSource(image_source); + plan.key = key; + plan.roots = image_source.dwords; return true; } const IndirectImagePlan* FindIndirectImage(const Inst& handle) const { const auto found = std::find_if(m_indirect_images.begin(), m_indirect_images.end(), - [&](const IndirectImagePlan& plan) { - return plan.handle == &handle; - }); + [&](const IndirectImagePlan& plan) { return plan.handle == &handle; }); return found == m_indirect_images.end() ? nullptr : &*found; } + bool IsLiveTableMemory(uint32_t index) const { + return std::ranges::find(m_live_table_memory, index) != m_live_table_memory.end(); + } + bool IsIndirectPlanningMemory(uint32_t index) const { + if (IsLiveTableMemory(index)) { + return false; + } return std::any_of(m_indirect_images.begin(), m_indirect_images.end(), [&](const IndirectImagePlan& plan) { - return std::ranges::find(plan.memory, index) != plan.memory.end(); + return std::ranges::find(plan.memory, index) != plan.memory.end() || + std::ranges::find(plan.extra_memory, index) != plan.extra_memory.end(); }); } + const BindlessSamplerPlan* FindBindlessSampler(const Inst& handle) const { + const auto found = + std::ranges::find(m_bindless_samplers, &handle, &BindlessSamplerPlan::handle); + return found == m_bindless_samplers.end() ? nullptr : &*found; + } + + // A bindless sampler: all four S# dwords are scalar reads of one sampler heap (a buffer of + // 16-byte records) at (key << 4) + record offset, with a GPU-computed key and a heap V# the + // host can evaluate. The shader keeps the key and indexes the bindless sampler array, which + // the host mirrors from the heap. + bool TryMakeBindlessSampler(Inst& handle, BindlessSamplerPlan& plan) { + Inst* table_handle = nullptr; + Value key; + uint32_t table_offset = 0; + for (uint32_t dword = 0; dword < 4u; ++dword) { + auto* read = ResolveInvariantPhi(m_program, handle.Arg(dword)).TryInstruction(); + if (read == nullptr) { + return false; + } + uint32_t memory_index = 0; + const auto* memory = ScalarReadMemory(*read, memory_index); + if (memory == nullptr || memory->kind != ResourceKind::ScalarBuffer || + memory->offset > INT32_MAX || (memory->offset & 3u) != 0u || + !MemoryIndexBelongsTo(memory_index, *read)) { + return false; + } + auto* current_handle = read->Arg(0).Resolve().TryInstruction(); + Value current_key; + uint32_t offset = 0; + if (current_handle == nullptr || + current_handle->GetOpcode() != ValueOpcode::GetBufferResource || + (table_handle != nullptr && + !EquivalentValue(m_program, Value(table_handle), Value(current_handle))) || + !MatchTableOffset(read->Arg(1), current_key, offset, 4u) || + memory->offset > UINT32_MAX - offset) { + return false; + } + offset += memory->offset; + if (dword == 0u) { + key = current_key; + table_offset = offset; + } else if (!EquivalentValue(m_program, key, current_key) || + static_cast<uint64_t>(table_offset) + dword * sizeof(uint32_t) != offset) { + return false; + } + table_handle = current_handle; + plan.reads[dword] = read; + plan.memory[dword] = memory_index; + plan.exclusive[dword] = + !read->Uses().empty() && std::ranges::all_of(read->Uses(), [](const Use& use) { + return use.user->GetOpcode() == ValueOpcode::GetSamplerResource || + FeedsOnlyDeadPhis(*use.user); + }); + } + DescriptorSource table_source; + if (!MakeRuntimeTableSource(*plan.reads[0], table_source) || + table_source.dword_count != 4u) { + return false; + } + DescriptorSource source; + source.dword_count = 4u; + source.dwords.fill(Value(0u)); + for (uint32_t dword = 0; dword < 3u; dword++) { + source.dwords[dword] = table_source.dwords[dword]; + plan.table_roots[dword] = table_source.dwords[dword]; + } + source.bindless_sampler = DescriptorSource::BindlessSampler {.table_offset = table_offset}; + plan.handle = &handle; + plan.key = key; + plan.source = InternSource(source); + return true; + } + + void PlanBindlessSamplers() { + // Opt-in while a regression is investigated: with the game's own samplers the title's + // fog shows a bright arch (DEBUGGING.md, 2026-09-28). KYTY_BINDLESS_SAMPLERS=1 enables them. + static const bool enabled = std::getenv("KYTY_BINDLESS_SAMPLERS") != nullptr && + std::getenv("KYTY_BINDLESS_SAMPLERS")[0] == '1'; + if (!m_program.bindless_images || !enabled) { + return; + } + for (auto* block: m_program.blocks) { + for (auto& inst: *block) { + if (ImageOpcodeInfoOf(inst.GetOpcode()).access == ImageAccess::None || + inst.NumArgs() < 2u) { + continue; + } + auto* sampler = inst.Arg(1).Resolve().TryInstruction(); + if (sampler == nullptr || sampler->GetOpcode() != ValueOpcode::GetSamplerResource || + sampler->NumArgs() != 4u || FindBindlessSampler(*sampler) != nullptr) { + continue; + } + const auto flags = inst.Flags<MemoryFlags>(); + const auto& memory = m_program.memory_info[flags.index]; + DescriptorSource descriptor; + MakeSource(*sampler, 4u, true, + (memory.image_sample_flags & Decoder::ImageSampleFlagAdjust) != 0, + memory.sampler * 4u, descriptor, flags.pc); + uint32_t bad_dword = 0; + if (ValidateSource(descriptor, bad_dword)) { + continue; + } + BindlessSamplerPlan plan; + if (TryMakeBindlessSampler(*sampler, plan)) { + m_bindless_samplers.push_back(plan); + } + } + } + } + + // Research stopgap: a bindless sampler (selected per material from a sampler heap, like + // the image beside it) has no indirect plan. Before the walk, give it one fixed sampler + // (trilinear, wrap, full LOD range) and make the heap reads it strands planning-only, as + // an indirect image's table reads are: registered as buffers, they would bind a + // descriptor that dead-code elimination then deletes. Only the filtering and edge + // addressing can differ from the material's own sampler. + void PlanDefaultSamplers() { + if (!Frontend::TranslationNonFatal()) { + return; + } + constexpr std::array<uint32_t, 4> DefaultSampler { + 0x00000000u, // wrap on every axis + 0xfffu << 12u, // max_lod 255.9 + (1u << 20u) | (1u << 22u) | (2u << 26u), // bilinear mag/min, linear mip + 0x00000000u}; + for (auto* block: m_program.blocks) { + for (auto& inst: *block) { + if (ImageOpcodeInfoOf(inst.GetOpcode()).access == ImageAccess::None || + inst.NumArgs() < 2u) { + continue; + } + auto* sampler = inst.Arg(1).Resolve().TryInstruction(); + if (sampler == nullptr || sampler->GetOpcode() != ValueOpcode::GetSamplerResource || + sampler->NumArgs() != 4u || FindBindlessSampler(*sampler) != nullptr) { + continue; + } + DescriptorSource descriptor; + descriptor.dword_count = 4u; + for (uint32_t dword = 0; dword < 4u; dword++) { + descriptor.dwords[dword] = LowerDescriptorPhi(sampler->Arg(dword)); + } + uint32_t bad_dword = 0; + if (ValidateSource(descriptor, bad_dword)) { + continue; + } ``` _🎯 Functional Correctness_ | _🟠 Major_ | _⚡ Quick win_ **Use `MakeSource` in `PlanDefaultSamplers`, or valid samplers get replaced by the default sampler.** `PlanDefaultSamplers` decides whether a sampler is valid by calling `LowerDescriptorPhi` on each raw dword. `Collect` and `PlanBindlessSamplers` use `MakeSource`, which also does three things this check skips: - It resolves register sources through `NativeDescriptorSource`. - It applies `CanonicalizeSampleAdjustDword3` when `ImageSampleFlagAdjust` is set. - It sets dword 3 to zero when no clamp axis selects border mode. Without these steps, some samplers fail `ValidateSource` here even though `GetHandle` would accept them. For example, a SampleAdjust sampler whose dword 3 carries lane-dependent reserved scratch bits fails this check. `TestSampleAdjustSamplerScratch` covers that shape. In nonfatal mode, `PlanDefaultSamplers` overwrites such a sampler with the fixed sampler and marks its reads planning-only. The game's filtering and addressing are lost, and nothing reports a failure. Build the descriptor the same way `PlanBindlessSamplers` does. <details> <summary>Proposed fix</summary> ```diff - DescriptorSource descriptor; - descriptor.dword_count = 4u; - for (uint32_t dword = 0; dword < 4u; dword++) { - descriptor.dwords[dword] = LowerDescriptorPhi(sampler->Arg(dword)); - } + const auto flags = inst.Flags<MemoryFlags>(); + const auto& memory = m_program.memory_info[flags.index]; + DescriptorSource descriptor; + MakeSource(*sampler, 4u, true, + (memory.image_sample_flags & Decoder::ImageSampleFlagAdjust) != 0, + memory.sampler * 4u, descriptor, flags.pc); + if (m_failed) { + return; + } ``` </details> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:2d5f4da6163e40e9f8ec0c36 --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -1241,0 +1284,4 @@
LOGF_COLOR(flushed ? Log::Color::Green : Log::Color::Red, "\tFsync: %s, %s\n",
Common::PathToString(file->real_name).c_str(), flushed ? "[ok]" : "[flush failed]");
return OK;
Author
Owner

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

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

Return an error when the flush fails.

When file->f.Flush() returns false, KernelFsync still returns OK. The new POSIX wrapper also receives success. This hides a failed synchronization from guest code that relies on fsync before treating a save as durable. FreeBSD specifies an error return when synchronization fails. (man.freebsd.org)

Return KERNEL_ERROR_EIO for a failed flush.

Proposed fix
-	return OK;
+	return flushed ? OK : KERNEL_ERROR_EIO;
📝 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 flushed ? OK : KERNEL_ERROR_EIO;
**@⁠coderabbitai[bot]** on GitHub · 2026-09-30 00:19 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/937#discussion_r4139620698) _🗄️ Data Integrity & Integration_ | _🟠 Major_ | _⚡ Quick win_ **Return an error when the flush fails.** When `file->f.Flush()` returns false, `KernelFsync` still returns `OK`. The new POSIX wrapper also receives success. This hides a failed synchronization from guest code that relies on `fsync` before treating a save as durable. FreeBSD specifies an error return when synchronization fails. ([man.freebsd.org](https://man.freebsd.org/cgi/man.cgi?manpath=FreeBSD+15.1-RELEASE+and+Ports&query=fsync&sektion=2&utm_source=openai)) Return `KERNEL_ERROR_EIO` for a failed flush. <details> <summary>Proposed fix</summary> ```diff - return OK; + return flushed ? OK : KERNEL_ERROR_EIO; ``` </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 flushed ? OK : KERNEL_ERROR_EIO; ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:poseidon:wombat61 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:f8da2183b2dfb15f51a76268 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-30 00:19 UTC · original
On src/libs/libPngEnc.cpp line 229 (outdated):

@@ -0,0 +1,318 @@
+#include "common/abi.h"
+#include "common/logging/log.h"
+#include "libs/libs.h"
+#include "loader/symbolDatabase.h"
+
+#include <algorithm>
+#include <cstddef>
+#include <cstring>
+#include <mutex>
+#include <vector>
+
+#define STB_IMAGE_WRITE_IMPLEMENTATION
+#define STB_IMAGE_WRITE_STATIC
+#define STBI_WRITE_NO_STDIO
+#include "stb_image_write.h"
+
+namespace Libs {
+
+LIB_VERSION("PngEnc", 1, "PngEnc", 1, 1);
+
+namespace PngEnc {
+
+constexpr int32_t PNG_ENC_ERROR_INVALID_ADDR    = -2140602111; // 0x80690101
+constexpr int32_t PNG_ENC_ERROR_INVALID_SIZE    = -2140602110; // 0x80690102
+constexpr int32_t PNG_ENC_ERROR_INVALID_PARAM   = -2140602109; // 0x80690103
+constexpr int32_t PNG_ENC_ERROR_INVALID_HANDLE  = -2140602108; // 0x80690104
+constexpr int32_t PNG_ENC_ERROR_DATA_OVERFLOW   = -2140602096; // 0x80690110
+constexpr int32_t PNG_ENC_ERROR_FATAL           = -2140602080; // 0x80690120
+
+constexpr uint32_t PNG_ENC_MAX_IMAGE_WIDTH        = 1000000;
+constexpr uint32_t PNG_ENC_MAX_FILTER_NUMBER      = 4;
+constexpr uint16_t PNG_ENC_COLOR_SPACE_RGB        = 3;
+constexpr uint16_t PNG_ENC_COLOR_SPACE_RGBA       = 19;
+constexpr uint16_t PNG_ENC_PIXEL_FORMAT_R8G8B8A8  = 0;
+constexpr uint16_t PNG_ENC_PIXEL_FORMAT_B8G8R8A8  = 1;
+constexpr uint16_t PNG_ENC_FILTER_TYPE_NONE       = 0;
+constexpr uint16_t PNG_ENC_FILTER_TYPE_SUB        = 1;
+constexpr uint16_t PNG_ENC_FILTER_TYPE_UP         = 2;
+constexpr uint16_t PNG_ENC_FILTER_TYPE_AVERAGE    = 4;
+constexpr uint16_t PNG_ENC_FILTER_TYPE_PAETH      = 8;
+
+struct PngEncCreateParam {
+	uint32_t this_size;
+	uint32_t attribute;
+	uint32_t max_image_width;
+	uint32_t max_filter_number;
+};
+
+struct PngEncEncodeParam {
+	const uint8_t* image_mem_addr;
+	uint8_t*       png_mem_addr;
+	uint32_t       image_mem_size;
+	uint32_t       png_mem_size;
+	uint32_t       image_width;
+	uint32_t       image_height;
+	uint32_t       image_pitch;
+	uint16_t       pixel_format;
+	uint16_t       color_space;
+	uint16_t       bit_depth;
+	uint16_t       clut_number;
+	uint16_t       filter_type;
+	uint16_t       compression_level;
+};
+
+struct PngEncOutputInfo {
+	uint32_t data_size;
+	uint32_t processed_height;
+};
+
+static_assert(sizeof(PngEncCreateParam) == 16);
+static_assert(sizeof(PngEncEncodeParam) == 48);
+
+struct PngEncContext {
+	uint64_t magic;
+	uint32_t max_image_width;
+};
+
+constexpr uint64_t PNG_ENC_CONTEXT_MAGIC = 0x4b595459504e4745ull; // KYTYPNGE
+
+struct PngEncWriter {
+	uint8_t* dst;
+	uint32_t capacity;
+	uint32_t size;
+	bool     overflow;
+};
+
+// stb_image_write keeps its compression level and filter choice in globals
+static std::mutex g_png_enc_mutex;
+
+static void PngEncWrite(void* context, void* data, int size) {
+	auto* writer = static_cast<PngEncWriter*>(context);
+
+	if (size < 0 || static_cast<uint64_t>(writer->size) + static_cast<uint32_t>(size) > writer->capacity) {
+		writer->overflow = true;
+		return;
+	}
+
+	std::memcpy(writer->dst + writer->size, data, static_cast<size_t>(size));
+	writer->size += static_cast<uint32_t>(size);
+}
+
+// Returns the stb filter to force (0 none, 1 sub, 2 up, 3 average, 4 paeth), or -1 to let stb
+// choose per row when the guest allows more than one filter.
+static int PngEncForcedFilter(uint16_t filter_type) {
+	switch (filter_type) {
+		case PNG_ENC_FILTER_TYPE_NONE: return 0;
+		case PNG_ENC_FILTER_TYPE_SUB: return 1;
+		case PNG_ENC_FILTER_TYPE_UP: return 2;
+		case PNG_ENC_FILTER_TYPE_AVERAGE: return 3;
+		case PNG_ENC_FILTER_TYPE_PAETH: return 4;
+		default: return -1;
+	}
+}
+
+static int32_t ValidateCreateParam(const PngEncCreateParam* param) {
+	if (param == nullptr) {
+		return PNG_ENC_ERROR_INVALID_ADDR;
+	}
+
+	LOGF("\t this_size         = %" PRIu32 "\n", param->this_size);
+	LOGF("\t attribute         = %" PRIu32 "\n", param->attribute);
+	LOGF("\t max_image_width   = %" PRIu32 "\n", param->max_image_width);
+	LOGF("\t max_filter_number = %" PRIu32 "\n", param->max_filter_number);
+
+	if (param->attribute != 0 || param->max_filter_number > PNG_ENC_MAX_FILTER_NUMBER) {
+		return PNG_ENC_ERROR_INVALID_PARAM;
+	}
+
+	if (param->max_image_width == 0 || param->max_image_width > PNG_ENC_MAX_IMAGE_WIDTH) {
+		return PNG_ENC_ERROR_INVALID_SIZE;
+	}
+
+	return 0;
+}
+
+static int32_t KYTY_SYSV_ABI PngEncQueryMemorySize(const PngEncCreateParam* param) {
+	PRINT_NAME();
+
+	if (int32_t result = ValidateCreateParam(param); result != 0) {
+		return result;
+	}
+
+	return sizeof(PngEncContext);
+}
+
+static int32_t KYTY_SYSV_ABI PngEncCreate(const PngEncCreateParam* param, void* memory_address,
+                                          uint32_t memory_size, void** handle) {
+	PRINT_NAME();
+
+	LOGF("\t memory_address    = %p\n", memory_address);
+	LOGF("\t memory_size       = %" PRIu32 "\n", memory_size);
+
+	if (int32_t result = ValidateCreateParam(param); result != 0) {
+		return result;
+	}
+
+	if (memory_address == nullptr || handle == nullptr) {
+		return PNG_ENC_ERROR_INVALID_ADDR;
+	}
+
+	if (memory_size < sizeof(PngEncContext)) {
+		return PNG_ENC_ERROR_INVALID_SIZE;
+	}
+
+	auto* ctx            = static_cast<PngEncContext*>(memory_address);
+	ctx->magic           = PNG_ENC_CONTEXT_MAGIC;
+	ctx->max_image_width = param->max_image_width;
+	*handle              = ctx;
+
+	return 0;
+}
+
+static int32_t KYTY_SYSV_ABI PngEncEncode(void* handle, const PngEncEncodeParam* param,
+                                          PngEncOutputInfo* output_info) {
+	PRINT_NAME();
+
+	if (handle == nullptr) {
+		return PNG_ENC_ERROR_INVALID_HANDLE;
+	}
+
+	const auto* ctx = static_cast<const PngEncContext*>(handle);
+	if (ctx->magic != PNG_ENC_CONTEXT_MAGIC) {
+		return PNG_ENC_ERROR_INVALID_HANDLE;
+	}
+
+	if (param == nullptr) {
+		return PNG_ENC_ERROR_INVALID_PARAM;
+	}
+
+	LOGF("\t image_mem_addr    = %p\n", static_cast<const void*>(param->image_mem_addr));
+	LOGF("\t png_mem_addr      = %p\n", static_cast<const void*>(param->png_mem_addr));
+	LOGF("\t image_mem_size    = %" PRIu32 "\n", param->image_mem_size);
+	LOGF("\t png_mem_size      = %" PRIu32 "\n", param->png_mem_size);
+	LOGF("\t image_width       = %" PRIu32 "\n", param->image_width);
+	LOGF("\t image_height      = %" PRIu32 "\n", param->image_height);
+	LOGF("\t image_pitch       = %" PRIu32 "\n", param->image_pitch);
+	LOGF("\t pixel_format      = %" PRIu16 "\n", param->pixel_format);
+	LOGF("\t color_space       = %" PRIu16 "\n", param->color_space);
+	LOGF("\t bit_depth         = %" PRIu16 "\n", param->bit_depth);
+	LOGF("\t filter_type       = %" PRIu16 "\n", param->filter_type);
+	LOGF("\t compression_level = %" PRIu16 "\n", param->compression_level);
+
+	if (param->image_mem_addr == nullptr || param->png_mem_addr == nullptr) {
+		return PNG_ENC_ERROR_INVALID_ADDR;
+	}
+
+	if (param->pixel_format != PNG_ENC_PIXEL_FORMAT_R8G8B8A8 &&
+	    param->pixel_format != PNG_ENC_PIXEL_FORMAT_B8G8R8A8) {
+		return PNG_ENC_ERROR_INVALID_PARAM;
+	}
+
+	if (param->color_space != PNG_ENC_COLOR_SPACE_RGB && param->color_space != PNG_ENC_COLOR_SPACE_RGBA) {
+		return PNG_ENC_ERROR_INVALID_PARAM;
+	}
+
+	// The source is always 8 bits per channel; 16-bit output is not implemented
+	if (param->bit_depth != 8) {
+		LOGF("\t unsupported bit depth\n");
+		return PNG_ENC_ERROR_INVALID_PARAM;
+	}
+
+	const uint32_t width     = param->image_width;
+	const uint32_t height    = param->image_height;
+	const uint32_t min_pitch = width * 4u;
+	const uint32_t pitch     = (param->image_pitch == 0 ? min_pitch : param->image_pitch);
+
+	if (width == 0 || height == 0 || width > ctx->max_image_width || height > 0x7fffffffu / min_pitch ||
+	    param->png_mem_size == 0 || pitch < min_pitch ||
+	    static_cast<uint64_t>(pitch) * (height - 1u) + min_pitch > param->image_mem_size) {

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Include the PNG filter byte in the height bound.

The guard at Line 227 checks height > 0x7fffffff / min_pitch, so min_pitch * height stays within INT_MAX. stbi_write_png_to_mem needs more space than that. It computes (x*n+1) * y in int arithmetic at Line 1144 of 3rdparty/stb/stb_image_write.h. It computes the same product again as y*(x*n+1) for stbi_zlib_compress at Line 1176. Each row has one extra filter byte.

Take RGBA input with width = 1 and height = 0x1fffffff. The guard accepts these values. The required image_mem_size is about 2 GiB, and a uint32_t can hold that. stb then computes 5 * 0x1fffffff, which is greater than INT_MAX. Signed overflow is undefined behavior. On common targets, the result wraps to a negative value, and malloc fails. The encode returns PNG_ENC_ERROR_FATAL, but the code still relies on undefined behavior. The guest controls image_width and image_height.

Bound height by the stb row size that includes the filter byte:

🐛 Proposed fix
-	if (width == 0 || height == 0 || width > ctx->max_image_width || height > 0x7fffffffu / min_pitch ||
+	// stb_image_write computes (row_bytes + 1) * height in int; keep it below INT_MAX
+	if (width == 0 || height == 0 || width > ctx->max_image_width || height > 0x7fffffffu / (min_pitch + 1u) ||
 	    param->png_mem_size == 0 || pitch < min_pitch ||
 	    static_cast<uint64_t>(pitch) * (height - 1u) + min_pitch > param->image_mem_size) {
📝 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.

	// stb_image_write computes (row_bytes + 1) * height in int; keep it below INT_MAX
	if (width == 0 || height == 0 || width > ctx->max_image_width || height > 0x7fffffffu / (min_pitch + 1u) ||
	    param->png_mem_size == 0 || pitch < min_pitch ||
	    static_cast<uint64_t>(pitch) * (height - 1u) + min_pitch > param->image_mem_size) {
**@⁠coderabbitai[bot]** on GitHub · 2026-09-30 00:19 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/937#discussion_r4139620707) On `src/libs/libPngEnc.cpp` line 229 (outdated): ```diff @@ -0,0 +1,318 @@ +#include "common/abi.h" +#include "common/logging/log.h" +#include "libs/libs.h" +#include "loader/symbolDatabase.h" + +#include <algorithm> +#include <cstddef> +#include <cstring> +#include <mutex> +#include <vector> + +#define STB_IMAGE_WRITE_IMPLEMENTATION +#define STB_IMAGE_WRITE_STATIC +#define STBI_WRITE_NO_STDIO +#include "stb_image_write.h" + +namespace Libs { + +LIB_VERSION("PngEnc", 1, "PngEnc", 1, 1); + +namespace PngEnc { + +constexpr int32_t PNG_ENC_ERROR_INVALID_ADDR = -2140602111; // 0x80690101 +constexpr int32_t PNG_ENC_ERROR_INVALID_SIZE = -2140602110; // 0x80690102 +constexpr int32_t PNG_ENC_ERROR_INVALID_PARAM = -2140602109; // 0x80690103 +constexpr int32_t PNG_ENC_ERROR_INVALID_HANDLE = -2140602108; // 0x80690104 +constexpr int32_t PNG_ENC_ERROR_DATA_OVERFLOW = -2140602096; // 0x80690110 +constexpr int32_t PNG_ENC_ERROR_FATAL = -2140602080; // 0x80690120 + +constexpr uint32_t PNG_ENC_MAX_IMAGE_WIDTH = 1000000; +constexpr uint32_t PNG_ENC_MAX_FILTER_NUMBER = 4; +constexpr uint16_t PNG_ENC_COLOR_SPACE_RGB = 3; +constexpr uint16_t PNG_ENC_COLOR_SPACE_RGBA = 19; +constexpr uint16_t PNG_ENC_PIXEL_FORMAT_R8G8B8A8 = 0; +constexpr uint16_t PNG_ENC_PIXEL_FORMAT_B8G8R8A8 = 1; +constexpr uint16_t PNG_ENC_FILTER_TYPE_NONE = 0; +constexpr uint16_t PNG_ENC_FILTER_TYPE_SUB = 1; +constexpr uint16_t PNG_ENC_FILTER_TYPE_UP = 2; +constexpr uint16_t PNG_ENC_FILTER_TYPE_AVERAGE = 4; +constexpr uint16_t PNG_ENC_FILTER_TYPE_PAETH = 8; + +struct PngEncCreateParam { + uint32_t this_size; + uint32_t attribute; + uint32_t max_image_width; + uint32_t max_filter_number; +}; + +struct PngEncEncodeParam { + const uint8_t* image_mem_addr; + uint8_t* png_mem_addr; + uint32_t image_mem_size; + uint32_t png_mem_size; + uint32_t image_width; + uint32_t image_height; + uint32_t image_pitch; + uint16_t pixel_format; + uint16_t color_space; + uint16_t bit_depth; + uint16_t clut_number; + uint16_t filter_type; + uint16_t compression_level; +}; + +struct PngEncOutputInfo { + uint32_t data_size; + uint32_t processed_height; +}; + +static_assert(sizeof(PngEncCreateParam) == 16); +static_assert(sizeof(PngEncEncodeParam) == 48); + +struct PngEncContext { + uint64_t magic; + uint32_t max_image_width; +}; + +constexpr uint64_t PNG_ENC_CONTEXT_MAGIC = 0x4b595459504e4745ull; // KYTYPNGE + +struct PngEncWriter { + uint8_t* dst; + uint32_t capacity; + uint32_t size; + bool overflow; +}; + +// stb_image_write keeps its compression level and filter choice in globals +static std::mutex g_png_enc_mutex; + +static void PngEncWrite(void* context, void* data, int size) { + auto* writer = static_cast<PngEncWriter*>(context); + + if (size < 0 || static_cast<uint64_t>(writer->size) + static_cast<uint32_t>(size) > writer->capacity) { + writer->overflow = true; + return; + } + + std::memcpy(writer->dst + writer->size, data, static_cast<size_t>(size)); + writer->size += static_cast<uint32_t>(size); +} + +// Returns the stb filter to force (0 none, 1 sub, 2 up, 3 average, 4 paeth), or -1 to let stb +// choose per row when the guest allows more than one filter. +static int PngEncForcedFilter(uint16_t filter_type) { + switch (filter_type) { + case PNG_ENC_FILTER_TYPE_NONE: return 0; + case PNG_ENC_FILTER_TYPE_SUB: return 1; + case PNG_ENC_FILTER_TYPE_UP: return 2; + case PNG_ENC_FILTER_TYPE_AVERAGE: return 3; + case PNG_ENC_FILTER_TYPE_PAETH: return 4; + default: return -1; + } +} + +static int32_t ValidateCreateParam(const PngEncCreateParam* param) { + if (param == nullptr) { + return PNG_ENC_ERROR_INVALID_ADDR; + } + + LOGF("\t this_size = %" PRIu32 "\n", param->this_size); + LOGF("\t attribute = %" PRIu32 "\n", param->attribute); + LOGF("\t max_image_width = %" PRIu32 "\n", param->max_image_width); + LOGF("\t max_filter_number = %" PRIu32 "\n", param->max_filter_number); + + if (param->attribute != 0 || param->max_filter_number > PNG_ENC_MAX_FILTER_NUMBER) { + return PNG_ENC_ERROR_INVALID_PARAM; + } + + if (param->max_image_width == 0 || param->max_image_width > PNG_ENC_MAX_IMAGE_WIDTH) { + return PNG_ENC_ERROR_INVALID_SIZE; + } + + return 0; +} + +static int32_t KYTY_SYSV_ABI PngEncQueryMemorySize(const PngEncCreateParam* param) { + PRINT_NAME(); + + if (int32_t result = ValidateCreateParam(param); result != 0) { + return result; + } + + return sizeof(PngEncContext); +} + +static int32_t KYTY_SYSV_ABI PngEncCreate(const PngEncCreateParam* param, void* memory_address, + uint32_t memory_size, void** handle) { + PRINT_NAME(); + + LOGF("\t memory_address = %p\n", memory_address); + LOGF("\t memory_size = %" PRIu32 "\n", memory_size); + + if (int32_t result = ValidateCreateParam(param); result != 0) { + return result; + } + + if (memory_address == nullptr || handle == nullptr) { + return PNG_ENC_ERROR_INVALID_ADDR; + } + + if (memory_size < sizeof(PngEncContext)) { + return PNG_ENC_ERROR_INVALID_SIZE; + } + + auto* ctx = static_cast<PngEncContext*>(memory_address); + ctx->magic = PNG_ENC_CONTEXT_MAGIC; + ctx->max_image_width = param->max_image_width; + *handle = ctx; + + return 0; +} + +static int32_t KYTY_SYSV_ABI PngEncEncode(void* handle, const PngEncEncodeParam* param, + PngEncOutputInfo* output_info) { + PRINT_NAME(); + + if (handle == nullptr) { + return PNG_ENC_ERROR_INVALID_HANDLE; + } + + const auto* ctx = static_cast<const PngEncContext*>(handle); + if (ctx->magic != PNG_ENC_CONTEXT_MAGIC) { + return PNG_ENC_ERROR_INVALID_HANDLE; + } + + if (param == nullptr) { + return PNG_ENC_ERROR_INVALID_PARAM; + } + + LOGF("\t image_mem_addr = %p\n", static_cast<const void*>(param->image_mem_addr)); + LOGF("\t png_mem_addr = %p\n", static_cast<const void*>(param->png_mem_addr)); + LOGF("\t image_mem_size = %" PRIu32 "\n", param->image_mem_size); + LOGF("\t png_mem_size = %" PRIu32 "\n", param->png_mem_size); + LOGF("\t image_width = %" PRIu32 "\n", param->image_width); + LOGF("\t image_height = %" PRIu32 "\n", param->image_height); + LOGF("\t image_pitch = %" PRIu32 "\n", param->image_pitch); + LOGF("\t pixel_format = %" PRIu16 "\n", param->pixel_format); + LOGF("\t color_space = %" PRIu16 "\n", param->color_space); + LOGF("\t bit_depth = %" PRIu16 "\n", param->bit_depth); + LOGF("\t filter_type = %" PRIu16 "\n", param->filter_type); + LOGF("\t compression_level = %" PRIu16 "\n", param->compression_level); + + if (param->image_mem_addr == nullptr || param->png_mem_addr == nullptr) { + return PNG_ENC_ERROR_INVALID_ADDR; + } + + if (param->pixel_format != PNG_ENC_PIXEL_FORMAT_R8G8B8A8 && + param->pixel_format != PNG_ENC_PIXEL_FORMAT_B8G8R8A8) { + return PNG_ENC_ERROR_INVALID_PARAM; + } + + if (param->color_space != PNG_ENC_COLOR_SPACE_RGB && param->color_space != PNG_ENC_COLOR_SPACE_RGBA) { + return PNG_ENC_ERROR_INVALID_PARAM; + } + + // The source is always 8 bits per channel; 16-bit output is not implemented + if (param->bit_depth != 8) { + LOGF("\t unsupported bit depth\n"); + return PNG_ENC_ERROR_INVALID_PARAM; + } + + const uint32_t width = param->image_width; + const uint32_t height = param->image_height; + const uint32_t min_pitch = width * 4u; + const uint32_t pitch = (param->image_pitch == 0 ? min_pitch : param->image_pitch); + + if (width == 0 || height == 0 || width > ctx->max_image_width || height > 0x7fffffffu / min_pitch || + param->png_mem_size == 0 || pitch < min_pitch || + static_cast<uint64_t>(pitch) * (height - 1u) + min_pitch > param->image_mem_size) { ``` _🎯 Functional Correctness_ | _🟡 Minor_ | _⚡ Quick win_ **Include the PNG filter byte in the height bound.** The guard at Line 227 checks `height > 0x7fffffff / min_pitch`, so `min_pitch * height` stays within `INT_MAX`. `stbi_write_png_to_mem` needs more space than that. It computes `(x*n+1) * y` in `int` arithmetic at Line 1144 of `3rdparty/stb/stb_image_write.h`. It computes the same product again as `y*(x*n+1)` for `stbi_zlib_compress` at Line 1176. Each row has one extra filter byte. Take RGBA input with `width = 1` and `height = 0x1fffffff`. The guard accepts these values. The required `image_mem_size` is about 2 GiB, and a `uint32_t` can hold that. stb then computes `5 * 0x1fffffff`, which is greater than `INT_MAX`. Signed overflow is undefined behavior. On common targets, the result wraps to a negative value, and `malloc` fails. The encode returns `PNG_ENC_ERROR_FATAL`, but the code still relies on undefined behavior. The guest controls `image_width` and `image_height`. Bound `height` by the stb row size that includes the filter byte: <details> <summary>🐛 Proposed fix</summary> ```diff - if (width == 0 || height == 0 || width > ctx->max_image_width || height > 0x7fffffffu / min_pitch || + // stb_image_write computes (row_bytes + 1) * height in int; keep it below INT_MAX + if (width == 0 || height == 0 || width > ctx->max_image_width || height > 0x7fffffffu / (min_pitch + 1u) || param->png_mem_size == 0 || pitch < min_pitch || static_cast<uint64_t>(pitch) * (height - 1u) + min_pitch > param->image_mem_size) { ``` </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 // stb_image_write computes (row_bytes + 1) * height in int; keep it below INT_MAX if (width == 0 || height == 0 || width > ctx->max_image_width || height > 0x7fffffffu / (min_pitch + 1u) || param->png_mem_size == 0 || pitch < min_pitch || static_cast<uint64_t>(pitch) * (height - 1u) + min_pitch > param->image_mem_size) { ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:fd662ce0f91a1fd925f639e8 --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -1196,0 +1214,4 @@
int KYTY_SYSV_ABI SaveDataConvert(const SaveDataConvertParam* convert) {
PRINT_NAME();
if (convert == nullptr || convert->src_dir_name == nullptr) {
Author
Owner

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

🔒 Security & Privacy | 🛡️ Detected with Advanced Tier | 🟠 Major | ⚡ Quick win

Path Traversal

Reachability: External
Exploitability: Moderate
CWE: CWE-22 — Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')

Validate both directory names before constructing host paths.

A guest can supply an existing source save and dst_dir_name = "../../victim". save_directory preserves the traversal components. The recursive copy can then overwrite matching files in a host directory outside _SaveData. Bounded strnlen does not enforce path containment. The filesystem copy options permit recursive copying and replacement of existing files. (eel.is)

Use valid_path_component for the source and any explicit destination, as the mount and delete APIs already do.

Proposed validation
-	if (convert == nullptr || convert->src_dir_name == nullptr) {
+	if (convert == nullptr || convert->src_dir_name == nullptr ||
+	    !valid_path_component(convert->src_dir_name->data) ||
+	    (convert->dst_dir_name != nullptr &&
+	     !valid_path_component(convert->dst_dir_name->data))) {
 		return SAVE_DATA_ERROR_PARAMETER;
 	}

View in Security blast radius

**@⁠coderabbitai[bot]** on GitHub · 2026-09-30 00:19 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/937#discussion_r4139620721) _🔒 Security & Privacy_ | _🛡️ Detected with Advanced Tier_ | _🟠 Major_ | _⚡ Quick win_ <!-- cr-reachability --> **Path Traversal** **Reachability:** External **Exploitability:** Moderate **CWE:** [CWE-22](https://cwe.mitre.org/data/definitions/22.html) — Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') **Validate both directory names before constructing host paths.** A guest can supply an existing source save and `dst_dir_name = "../../victim"`. `save_directory` preserves the traversal components. The recursive copy can then overwrite matching files in a host directory outside `_SaveData`. Bounded `strnlen` does not enforce path containment. The filesystem copy options permit recursive copying and replacement of existing files. ([eel.is](https://www.eel.is/c%2B%2Bdraft/fs.enum.copy.opts?utm_source=openai)) Use `valid_path_component` for the source and any explicit destination, as the mount and delete APIs already do. <details> <summary>Proposed validation</summary> ```diff - if (convert == nullptr || convert->src_dir_name == nullptr) { + if (convert == nullptr || convert->src_dir_name == nullptr || + !valid_path_component(convert->src_dir_name->data) || + (convert->dst_dir_name != nullptr && + !valid_path_component(convert->dst_dir_name->data))) { return SAVE_DATA_ERROR_PARAMETER; } ``` </details> [View in Security blast radius](https://app.coderabbit.ai/change-stack/KytyPS5/KytyPS5/pull/937/blast-radius?toCommitId=d6ec3a42ed19d0f16bb3e184ca57e20cce8d5176&reviewRunId=4888c092-8472-4d20-95a8-efdb21888a8e&securityFinding=6ba1a2e962ab80c499e61e64) <!-- fingerprinting:phantom:poseidon:wombat61 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:6ba1a2e962ab80c499e61e64 --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -1196,0 +1234,4 @@
std::filesystem::copy(from, save_directory(get_title_id(), dst_name, convert->user_id),
std::filesystem::copy_options::recursive |
std::filesystem::copy_options::overwrite_existing,
ec);
Author
Owner

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

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

Persist the destination allocation specified by dst_blocks.

If a source save has 48 blocks and conversion requests 96 blocks, this copy retains the source sce_sys/blocks.bin. Conversion reports success, but SaveDataGetMountInfo still reports 48 blocks. In-place conversion also leaves the allocation unchanged.

Validate the requested allocation and update the destination metadata with write_save_file. Report any metadata-write failure through the conversion event.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-30 00:19 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/937#discussion_r4139620725) _🗄️ Data Integrity & Integration_ | _🟠 Major_ | _⚡ Quick win_ **Persist the destination allocation specified by `dst_blocks`.** If a source save has 48 blocks and conversion requests 96 blocks, this copy retains the source `sce_sys/blocks.bin`. Conversion reports success, but `SaveDataGetMountInfo` still reports 48 blocks. In-place conversion also leaves the allocation unchanged. Validate the requested allocation and update the destination metadata with `write_save_file`. Report any metadata-write failure through the conversion event. <!-- fingerprinting:phantom:poseidon:wombat61 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:3650c1e1934847bf7e1bcf0d --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-30 00:19 UTC · original · reviewed

Actionable comments posted: 18

🧹 Nitpick comments (1)
tests/ResourceTrackingTests.cpp (1)

2489-2541: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a test that proves a valid sampler keeps its own words in nonfatal mode.

TestDefaultSamplerKeepsDataReads checks only that an invalid heap sampler gets the default sampler. No test runs a valid sampler under TranslationNonFatalScope. Such a test would catch the PlanDefaultSamplers validation mismatch described in ResourceTracking.cpp.

A good candidate is the SampleAdjust fixture from TestSampleAdjustSamplerScratch. Assert that its dword 3 is not replaced by the default sampler.


ℹ️ Review info
⚙️ Run configuration

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

Review profile: CHILL

Plan: Advanced

Run ID: 4888c092-8472-4d20-95a8-efdb21888a8e

📥 Commits

Reviewing files that changed from the base of the PR and between 05057c9441 and d6ec3a42ed19d0f16bb3e184ca57e20cce8d5176.

📒 Files selected for processing (144)
  • 3rdparty/stb/stb_image_write.h
  • CMakeLists.txt
  • src/common/CMakeLists.txt
  • src/common/assert.cpp
  • src/common/assert.h
  • src/common/emulatorConfig.cpp
  • src/common/emulatorConfig.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/guest_gpu/graphicsRun.h
  • 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/pageManager.cpp
  • src/graphics/host_gpu/pageManager.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/faultManager.h
  • src/graphics/host_gpu/renderer/cache/streamBuffer.h
  • 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/context.cpp
  • src/graphics/host_gpu/renderer/image/image.h
  • src/graphics/host_gpu/renderer/image/imageInfo.h
  • src/graphics/host_gpu/renderer/image/imageView.h
  • src/graphics/host_gpu/renderer/indirectDispatch.cpp
  • src/graphics/host_gpu/renderer/indirectDispatch.h
  • src/graphics/host_gpu/renderer/masterSemaphore.cpp
  • src/graphics/host_gpu/renderer/pipeline/bindlessTable.cpp
  • src/graphics/host_gpu/renderer/pipeline/bindlessTable.h
  • src/graphics/host_gpu/renderer/pipeline/descriptors.cpp
  • src/graphics/host_gpu/renderer/pipeline/descriptors.h
  • src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp
  • src/graphics/host_gpu/renderer/pipeline/pipelineCache.h
  • src/graphics/host_gpu/renderer/pipeline/shaders.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/shaders/dispatch_indirect_groups.comp
  • src/graphics/host_gpu/vma.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/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/SpirvEmitter.h
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterAnalysis.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterFlow.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterHelpers.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.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/spirvEmitterMesh.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterModule.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp
  • src/graphics/shader/recompiler/frontend/cfg/ShaderCFG.cpp
  • src/graphics/shader/recompiler/frontend/decode/ImageOps.cpp
  • src/graphics/shader/recompiler/frontend/decode/MemoryOps.cpp
  • src/graphics/shader/recompiler/frontend/decode/ScalarAluOps.cpp
  • src/graphics/shader/recompiler/frontend/decode/ShaderDecoder.cpp
  • src/graphics/shader/recompiler/frontend/decode/ShaderDecoder.h
  • src/graphics/shader/recompiler/frontend/decode/ShaderFunctions.cpp
  • src/graphics/shader/recompiler/frontend/decode/ShaderFunctions.h
  • src/graphics/shader/recompiler/frontend/decode/VectorAluOps.cpp
  • src/graphics/shader/recompiler/frontend/translate/Bvh.cpp
  • src/graphics/shader/recompiler/frontend/translate/Compare.cpp
  • src/graphics/shader/recompiler/frontend/translate/Control.cpp
  • src/graphics/shader/recompiler/frontend/translate/Dispatch.cpp
  • src/graphics/shader/recompiler/frontend/translate/Memory.cpp
  • src/graphics/shader/recompiler/frontend/translate/Scalar.cpp
  • src/graphics/shader/recompiler/frontend/translate/Translate.cpp
  • src/graphics/shader/recompiler/frontend/translate/Translator.h
  • src/graphics/shader/recompiler/frontend/translate/Vector.cpp
  • src/graphics/shader/recompiler/ir/BindlessBindings.h
  • src/graphics/shader/recompiler/ir/Program.cpp
  • src/graphics/shader/recompiler/ir/ResourceSnapshot.h
  • src/graphics/shader/recompiler/ir/ShaderIR.h
  • src/graphics/shader/recompiler/ir/opcodes/ValueOpcodes.cpp
  • src/graphics/shader/recompiler/ir/opcodes/ValueOpcodes.inc
  • src/graphics/shader/recompiler/ir/passes/BindingLayout.cpp
  • src/graphics/shader/recompiler/ir/passes/ConstantPropagation.cpp
  • src/graphics/shader/recompiler/ir/passes/ConstantPropagation.h
  • src/graphics/shader/recompiler/ir/passes/DeadCodeElimination.cpp
  • src/graphics/shader/recompiler/ir/passes/DeadCodeElimination.h
  • src/graphics/shader/recompiler/ir/passes/LocalAddressStores.cpp
  • src/graphics/shader/recompiler/ir/passes/ReadLaneElimination.cpp
  • src/graphics/shader/recompiler/ir/passes/ReadLaneElimination.h
  • src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp
  • src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.h
  • src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp
  • src/graphics/shader/recompiler/ir/passes/ResourceTracking.h
  • src/graphics/shader/recompiler/ir/passes/ShaderInfoCollection.cpp
  • src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp
  • src/graphics/shader/recompiler/ir/passes/SrtWalker.h
  • src/graphics/shader/shader.cpp
  • src/graphics/shader/shader.h
  • src/graphics/shader/shaderCompiler.h
  • src/kernel/eventQueue.cpp
  • src/kernel/fileSystem.cpp
  • src/kernel/fileSystem.h
  • src/kernel/memory.cpp
  • src/kernel/memory.h
  • src/launcher/forms/configuration_edit_dialog.ui
  • src/launcher/include/configuration.h
  • src/launcher/src/configurationEditDialog.cpp
  • src/launcher/src/mainDialog.cpp
  • src/libs/acm.cpp
  • src/libs/acm.h
  • src/libs/agc.cpp
  • src/libs/ajm.cpp
  • src/libs/ajm/atrac9_decoder.h
  • src/libs/ajm/opus_decoder.h
  • src/libs/dialog.cpp
  • src/libs/libAmpr.cpp
  • src/libs/libAudio.cpp
  • src/libs/libKernel.cpp
  • src/libs/libNet.cpp
  • src/libs/libPngEnc.cpp
  • src/libs/libSaveData.cpp
  • src/libs/libVideoOut.cpp
  • src/libs/libs.cpp
  • src/loader/runtimeLinker.cpp
  • src/loader/x64InstructionEmulator.cpp
  • src/loader/x64InstructionEmulator.h
  • src/main.cpp
  • tests/ResourceTrackingTests.cpp
  • tests/ScalarProvenanceTests.cpp
  • tests/ShaderRayTracingTests.inc
  • tests/ShaderRecompilerComputeTests.cpp
  • tests/X64LoadEmulationTests.cpp
  • tests/shaderCfgTests.cpp

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

**@⁠coderabbitai[bot]** on GitHub · 2026-09-30 00:19 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/937#pullrequestreview-5360039920) · **reviewed** **Actionable comments posted: 18** <details> <summary>🧹 Nitpick comments (1)</summary><blockquote> <details> <summary>tests/ResourceTrackingTests.cpp (1)</summary><blockquote> `2489-2541`: _📐 Maintainability & Code Quality_ | _🔵 Trivial_ | _⚡ Quick win_ **Add a test that proves a valid sampler keeps its own words in nonfatal mode.** `TestDefaultSamplerKeepsDataReads` checks only that an invalid heap sampler gets the default sampler. No test runs a valid sampler under `TranslationNonFatalScope`. Such a test would catch the `PlanDefaultSamplers` validation mismatch described in `ResourceTracking.cpp`. A good candidate is the SampleAdjust fixture from `TestSampleAdjustSamplerScratch`. Assert that its dword 3 is not replaced by the default sampler. <!-- cr-comment:v1:633d44ec72b1ceab9cdd5efe --> </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**: `4888c092-8472-4d20-95a8-efdb21888a8e` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 05057c9441dbf3972d49f9143b90213a43a01a00 and d6ec3a42ed19d0f16bb3e184ca57e20cce8d5176. </details> <details> <summary>📒 Files selected for processing (144)</summary> * `3rdparty/stb/stb_image_write.h` * `CMakeLists.txt` * `src/common/CMakeLists.txt` * `src/common/assert.cpp` * `src/common/assert.h` * `src/common/emulatorConfig.cpp` * `src/common/emulatorConfig.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/guest_gpu/graphicsRun.h` * `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/pageManager.cpp` * `src/graphics/host_gpu/pageManager.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/faultManager.h` * `src/graphics/host_gpu/renderer/cache/streamBuffer.h` * `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/context.cpp` * `src/graphics/host_gpu/renderer/image/image.h` * `src/graphics/host_gpu/renderer/image/imageInfo.h` * `src/graphics/host_gpu/renderer/image/imageView.h` * `src/graphics/host_gpu/renderer/indirectDispatch.cpp` * `src/graphics/host_gpu/renderer/indirectDispatch.h` * `src/graphics/host_gpu/renderer/masterSemaphore.cpp` * `src/graphics/host_gpu/renderer/pipeline/bindlessTable.cpp` * `src/graphics/host_gpu/renderer/pipeline/bindlessTable.h` * `src/graphics/host_gpu/renderer/pipeline/descriptors.cpp` * `src/graphics/host_gpu/renderer/pipeline/descriptors.h` * `src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp` * `src/graphics/host_gpu/renderer/pipeline/pipelineCache.h` * `src/graphics/host_gpu/renderer/pipeline/shaders.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/shaders/dispatch_indirect_groups.comp` * `src/graphics/host_gpu/vma.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/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/SpirvEmitter.h` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterAnalysis.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterFlow.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterHelpers.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.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/spirvEmitterMesh.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterModule.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp` * `src/graphics/shader/recompiler/frontend/cfg/ShaderCFG.cpp` * `src/graphics/shader/recompiler/frontend/decode/ImageOps.cpp` * `src/graphics/shader/recompiler/frontend/decode/MemoryOps.cpp` * `src/graphics/shader/recompiler/frontend/decode/ScalarAluOps.cpp` * `src/graphics/shader/recompiler/frontend/decode/ShaderDecoder.cpp` * `src/graphics/shader/recompiler/frontend/decode/ShaderDecoder.h` * `src/graphics/shader/recompiler/frontend/decode/ShaderFunctions.cpp` * `src/graphics/shader/recompiler/frontend/decode/ShaderFunctions.h` * `src/graphics/shader/recompiler/frontend/decode/VectorAluOps.cpp` * `src/graphics/shader/recompiler/frontend/translate/Bvh.cpp` * `src/graphics/shader/recompiler/frontend/translate/Compare.cpp` * `src/graphics/shader/recompiler/frontend/translate/Control.cpp` * `src/graphics/shader/recompiler/frontend/translate/Dispatch.cpp` * `src/graphics/shader/recompiler/frontend/translate/Memory.cpp` * `src/graphics/shader/recompiler/frontend/translate/Scalar.cpp` * `src/graphics/shader/recompiler/frontend/translate/Translate.cpp` * `src/graphics/shader/recompiler/frontend/translate/Translator.h` * `src/graphics/shader/recompiler/frontend/translate/Vector.cpp` * `src/graphics/shader/recompiler/ir/BindlessBindings.h` * `src/graphics/shader/recompiler/ir/Program.cpp` * `src/graphics/shader/recompiler/ir/ResourceSnapshot.h` * `src/graphics/shader/recompiler/ir/ShaderIR.h` * `src/graphics/shader/recompiler/ir/opcodes/ValueOpcodes.cpp` * `src/graphics/shader/recompiler/ir/opcodes/ValueOpcodes.inc` * `src/graphics/shader/recompiler/ir/passes/BindingLayout.cpp` * `src/graphics/shader/recompiler/ir/passes/ConstantPropagation.cpp` * `src/graphics/shader/recompiler/ir/passes/ConstantPropagation.h` * `src/graphics/shader/recompiler/ir/passes/DeadCodeElimination.cpp` * `src/graphics/shader/recompiler/ir/passes/DeadCodeElimination.h` * `src/graphics/shader/recompiler/ir/passes/LocalAddressStores.cpp` * `src/graphics/shader/recompiler/ir/passes/ReadLaneElimination.cpp` * `src/graphics/shader/recompiler/ir/passes/ReadLaneElimination.h` * `src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp` * `src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.h` * `src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp` * `src/graphics/shader/recompiler/ir/passes/ResourceTracking.h` * `src/graphics/shader/recompiler/ir/passes/ShaderInfoCollection.cpp` * `src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp` * `src/graphics/shader/recompiler/ir/passes/SrtWalker.h` * `src/graphics/shader/shader.cpp` * `src/graphics/shader/shader.h` * `src/graphics/shader/shaderCompiler.h` * `src/kernel/eventQueue.cpp` * `src/kernel/fileSystem.cpp` * `src/kernel/fileSystem.h` * `src/kernel/memory.cpp` * `src/kernel/memory.h` * `src/launcher/forms/configuration_edit_dialog.ui` * `src/launcher/include/configuration.h` * `src/launcher/src/configurationEditDialog.cpp` * `src/launcher/src/mainDialog.cpp` * `src/libs/acm.cpp` * `src/libs/acm.h` * `src/libs/agc.cpp` * `src/libs/ajm.cpp` * `src/libs/ajm/atrac9_decoder.h` * `src/libs/ajm/opus_decoder.h` * `src/libs/dialog.cpp` * `src/libs/libAmpr.cpp` * `src/libs/libAudio.cpp` * `src/libs/libKernel.cpp` * `src/libs/libNet.cpp` * `src/libs/libPngEnc.cpp` * `src/libs/libSaveData.cpp` * `src/libs/libVideoOut.cpp` * `src/libs/libs.cpp` * `src/loader/runtimeLinker.cpp` * `src/loader/x64InstructionEmulator.cpp` * `src/loader/x64InstructionEmulator.h` * `src/main.cpp` * `tests/ResourceTrackingTests.cpp` * `tests/ScalarProvenanceTests.cpp` * `tests/ShaderRayTracingTests.inc` * `tests/ShaderRecompilerComputeTests.cpp` * `tests/X64LoadEmulationTests.cpp` * `tests/shaderCfgTests.cpp` </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-01 07:53 UTC · original
On src/graphics/host_gpu/renderer/renderContext.cpp line 140 (outdated):

@@ -119,10 +129,24 @@ void RenderContext::UnmapMemory(uint64_t vaddr, uint64_t size) {
 }
 
 void RenderContext::PrepareBda() {
-	std::shared_lock lock(m_mapped_ranges_mutex);
-	m_mapped_ranges.ForEach([this](uint64_t start, uint64_t end) {
-		m_buffer_cache.SynchronizeBuffersInRange(start, end - start);
-	});
+	const auto epoch = g_cpu_dirty_epoch.load(std::memory_order_acquire);
+	if (epoch != m_bda_synced_epoch) {
+		const auto submission = g_guest_submission_seq.load(std::memory_order_relaxed);
+		if (submission == m_bda_synced_submission) {
+			m_fault_process_pending = true;
+			return;
+		}
+		m_bda_synced_submission = submission;
+	}

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

🔎 Supported by static analysis

🏁 Script executed:

set -eu
printf '%s\n' '--- diff stat ---'
git diff --stat b7a1fac898be93bfe0c282752a7a386fd5202486 3fa2b06dda4c7acfe64f33d8eef6c636405a76dd -- src/graphics/host_gpu/renderer/renderContext.cpp src/graphics/host_gpu/renderer
printf '%s\n' '--- changed hunks in renderContext.cpp ---'
git diff --unified=40 b7a1fac898be93bfe0c282752a7a386fd5202486 3fa2b06dda4c7acfe64f33d8eef6c636405a76dd -- src/graphics/host_gpu/renderer/renderContext.cpp
printf '%s\n' '--- relevant symbols ---'
rg -n -C 8 'PrepareBda|g_cpu_dirty_epoch|g_guest_submission_seq|m_bda_synced|Register\\(|JoinOverlap|FindBuffer|CreateBuffer|uses_dma' src/graphics/host_gpu/renderer src/graphics/host_gpu -g '*.[ch]pp' -g '*.[ch]'

Repository: KytyPS5/KytyPS5

Length of output: 9107


🏁 Script executed:

set -eu
printf '%s\n' '--- buffer cache symbols ---'
rg -n -C 12 -e 'PrepareBda|g_cpu_dirty_epoch|g_guest_submission_seq|m_bda_synced|Register\(|JoinOverlap|FindBuffer|CreateBuffer|uses_dma|SynchronizeCpuDirtyBuffersInRange|SynchronizeBuffersInRange' src/graphics/host_gpu/renderer/cache/bufferCache.cpp src/graphics/host_gpu/renderer/cache/bufferCache.h src/graphics/host_gpu/renderer/renderCompute.cpp src/graphics/host_gpu/renderer/renderDraw.cpp src/graphics/host_gpu/renderer/commandScheduler.cpp src/graphics/host_gpu/renderer/context.cpp src/graphics/host_gpu/renderer/renderContext.cpp
printf '%s\n' '--- global declarations and sequence updates ---'
rg -n -C 8 -e 'g_cpu_dirty_epoch|g_guest_submission_seq|submission_seq|guest_submission' src
printf '%s\n' '--- buffer cache outline ---'
ast-grep outline src/graphics/host_gpu/renderer/cache/bufferCache.cpp --view expanded
printf '%s\n' '--- render compute relevant regions ---'
rg -n -C 20 -e 'PrepareBda|uses_dma|FindBuffer|CreateBuffer|Dispatch|dispatch' src/graphics/host_gpu/renderer/renderCompute.cpp src/graphics/host_gpu/renderer/renderDraw.cpp

Repository: KytyPS5/KytyPS5

Length of output: 43507


🏁 Script executed:

set -eu
printf '%s\n' '--- CreateBuffer and overlap handling ---'
sed -n '379,490p' src/graphics/host_gpu/renderer/cache/bufferCache.cpp
printf '%s\n' '--- synchronization implementation ---'
rg -n -C 24 'SynchronizeCpuDirtyBuffersInRange|SynchronizeBuffersInRange|SynchronizeBuffer\(' src/graphics/host_gpu/renderer/cache/bufferCache.cpp
printf '%s\n' '--- submission sequence declaration and updates ---'
rg -n -C 12 'g_guest_submission_seq|guest_submission_seq|submission_seq' src/graphics/host_gpu/renderer
printf '%s\n' '--- dirty tracking declarations and updates ---'
rg -n -C 12 'g_cpu_dirty_epoch|MarkRegionAsCpuModified|IsRegionCpuModified|CpuDirty' src/graphics/host_gpu/renderer/cache src/graphics/host_gpu/renderer

Repository: KytyPS5/KytyPS5

Length of output: 42542


Synchronize buffers registered during the current submission.

FindBuffers runs before PrepareBda for DMA dispatches. BufferCache::Register increments g_cpu_dirty_epoch, but it does not advance g_guest_submission_seq. A later dispatch in the same submission can therefore register a new or enlarged buffer, then return from PrepareBda because the submission sequence is unchanged.

JoinOverlap copies only existing overlap contents. The uncovered pages still require guest-memory synchronization. Without it, a BDA read can observe uninitialized device memory instead of guest data.

Track registrations separately. Set the flag from Register, and clear it only after PrepareBda synchronizes the mapped ranges. Do not skip synchronization while the flag is set.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-01 07:53 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/937#discussion_r4153083560) On `src/graphics/host_gpu/renderer/renderContext.cpp` line 140 (outdated): ```diff @@ -119,10 +129,24 @@ void RenderContext::UnmapMemory(uint64_t vaddr, uint64_t size) { } void RenderContext::PrepareBda() { - std::shared_lock lock(m_mapped_ranges_mutex); - m_mapped_ranges.ForEach([this](uint64_t start, uint64_t end) { - m_buffer_cache.SynchronizeBuffersInRange(start, end - start); - }); + const auto epoch = g_cpu_dirty_epoch.load(std::memory_order_acquire); + if (epoch != m_bda_synced_epoch) { + const auto submission = g_guest_submission_seq.load(std::memory_order_relaxed); + if (submission == m_bda_synced_submission) { + m_fault_process_pending = true; + return; + } + m_bda_synced_submission = submission; + } ``` _🗄️ Data Integrity & Integration_ | _🟠 Major_ | _⚡ Quick win_ <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash set -eu printf '%s\n' '--- diff stat ---' git diff --stat b7a1fac898be93bfe0c282752a7a386fd5202486 3fa2b06dda4c7acfe64f33d8eef6c636405a76dd -- src/graphics/host_gpu/renderer/renderContext.cpp src/graphics/host_gpu/renderer printf '%s\n' '--- changed hunks in renderContext.cpp ---' git diff --unified=40 b7a1fac898be93bfe0c282752a7a386fd5202486 3fa2b06dda4c7acfe64f33d8eef6c636405a76dd -- src/graphics/host_gpu/renderer/renderContext.cpp printf '%s\n' '--- relevant symbols ---' rg -n -C 8 'PrepareBda|g_cpu_dirty_epoch|g_guest_submission_seq|m_bda_synced|Register\\(|JoinOverlap|FindBuffer|CreateBuffer|uses_dma' src/graphics/host_gpu/renderer src/graphics/host_gpu -g '*.[ch]pp' -g '*.[ch]' ``` Repository: KytyPS5/KytyPS5 Length of output: 9107 --- 🏁 Script executed: ```bash set -eu printf '%s\n' '--- buffer cache symbols ---' rg -n -C 12 -e 'PrepareBda|g_cpu_dirty_epoch|g_guest_submission_seq|m_bda_synced|Register\(|JoinOverlap|FindBuffer|CreateBuffer|uses_dma|SynchronizeCpuDirtyBuffersInRange|SynchronizeBuffersInRange' src/graphics/host_gpu/renderer/cache/bufferCache.cpp src/graphics/host_gpu/renderer/cache/bufferCache.h src/graphics/host_gpu/renderer/renderCompute.cpp src/graphics/host_gpu/renderer/renderDraw.cpp src/graphics/host_gpu/renderer/commandScheduler.cpp src/graphics/host_gpu/renderer/context.cpp src/graphics/host_gpu/renderer/renderContext.cpp printf '%s\n' '--- global declarations and sequence updates ---' rg -n -C 8 -e 'g_cpu_dirty_epoch|g_guest_submission_seq|submission_seq|guest_submission' src printf '%s\n' '--- buffer cache outline ---' ast-grep outline src/graphics/host_gpu/renderer/cache/bufferCache.cpp --view expanded printf '%s\n' '--- render compute relevant regions ---' rg -n -C 20 -e 'PrepareBda|uses_dma|FindBuffer|CreateBuffer|Dispatch|dispatch' src/graphics/host_gpu/renderer/renderCompute.cpp src/graphics/host_gpu/renderer/renderDraw.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 43507 --- 🏁 Script executed: ```bash set -eu printf '%s\n' '--- CreateBuffer and overlap handling ---' sed -n '379,490p' src/graphics/host_gpu/renderer/cache/bufferCache.cpp printf '%s\n' '--- synchronization implementation ---' rg -n -C 24 'SynchronizeCpuDirtyBuffersInRange|SynchronizeBuffersInRange|SynchronizeBuffer\(' src/graphics/host_gpu/renderer/cache/bufferCache.cpp printf '%s\n' '--- submission sequence declaration and updates ---' rg -n -C 12 'g_guest_submission_seq|guest_submission_seq|submission_seq' src/graphics/host_gpu/renderer printf '%s\n' '--- dirty tracking declarations and updates ---' rg -n -C 12 'g_cpu_dirty_epoch|MarkRegionAsCpuModified|IsRegionCpuModified|CpuDirty' src/graphics/host_gpu/renderer/cache src/graphics/host_gpu/renderer ``` Repository: KytyPS5/KytyPS5 Length of output: 42542 --- </details> **Synchronize buffers registered during the current submission.** `FindBuffers` runs before `PrepareBda` for DMA dispatches. `BufferCache::Register` increments `g_cpu_dirty_epoch`, but it does not advance `g_guest_submission_seq`. A later dispatch in the same submission can therefore register a new or enlarged buffer, then return from `PrepareBda` because the submission sequence is unchanged. `JoinOverlap` copies only existing overlap contents. The uncovered pages still require guest-memory synchronization. Without it, a BDA read can observe uninitialized device memory instead of guest data. Track registrations separately. Set the flag from `Register`, and clear it only after `PrepareBda` synchronizes the mapped ranges. Do not skip synchronization while the flag is set. <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:6159ee383e13b3fcccc8c0bb --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-01 07:53 UTC · original

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Include the high VGPR of V_CMP_EQ_F64 in vector_limit.

This PR adds V_CMP_EQ_F64, and EmitFloat64Equal reads 64-bit source pairs. Only V_CMP_LE_F64, V_CMPX_LE_F64, and V_CMPX_GE_F64 extend both sources by 2 here. If the high half of an EQ_F64 source is the highest VGPR in the shader, vector_limit does not cover it.

Proposed fix
+		case Decoder::Opcode::V_CMP_EQ_F64:
 		case Decoder::Opcode::V_CMP_LE_F64:
 		case Decoder::Opcode::V_CMPX_LE_F64:
 		case Decoder::Opcode::V_CMPX_GE_F64:
📝 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 Decoder::Opcode::V_CMP_EQ_F64:
		case Decoder::Opcode::V_CMP_LE_F64:
		case Decoder::Opcode::V_CMPX_LE_F64:
		case Decoder::Opcode::V_CMPX_GE_F64:
			include_vector(inst.src0, 2u);
			include_vector(inst.src1, 2u);
			break;
**@⁠coderabbitai[bot]** on GitHub · 2026-10-01 07:53 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/937#discussion_r4153083576) _🎯 Functional Correctness_ | _🟡 Minor_ | _⚡ Quick win_ **Include the high VGPR of `V_CMP_EQ_F64` in `vector_limit`.** This PR adds `V_CMP_EQ_F64`, and `EmitFloat64Equal` reads 64-bit source pairs. Only `V_CMP_LE_F64`, `V_CMPX_LE_F64`, and `V_CMPX_GE_F64` extend both sources by 2 here. If the high half of an `EQ_F64` source is the highest VGPR in the shader, `vector_limit` does not cover it. <details> <summary>Proposed fix</summary> ```diff + case Decoder::Opcode::V_CMP_EQ_F64: case Decoder::Opcode::V_CMP_LE_F64: case Decoder::Opcode::V_CMPX_LE_F64: case Decoder::Opcode::V_CMPX_GE_F64: ``` </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 Decoder::Opcode::V_CMP_EQ_F64: case Decoder::Opcode::V_CMP_LE_F64: case Decoder::Opcode::V_CMPX_LE_F64: case Decoder::Opcode::V_CMPX_GE_F64: include_vector(inst.src0, 2u); include_vector(inst.src1, 2u); break; ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:31ce454eaad8858f6c4736e9 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-01 07:53 UTC · original
On src/libs/libAudio2.cpp line 550 (outdated):

@@ -513,42 +529,89 @@ int KYTY_SYSV_ABI AudioOut2ContextAdvance(AudioOut2ContextHandle ctx) {
 	return OK;
 }
 
-int KYTY_SYSV_ABI AudioOut2ContextPush(AudioOut2ContextHandle ctx, uint32_t blocking) {
-	uint32_t sleep_micros = audioout2_grain_micros(512);
+// Queue time SDL may hold beyond the queue depth before it counts.
+constexpr uint64_t AUDIOOUT2_DEVICE_CUSHION_US = 20000;
+
+// Microseconds the context's device still has to play (its first port with PCM and a device), or
+// -1 when it has none: then the timer model applies.
+static int64_t audioout2_device_queued_us(AudioOut2ContextHandle ctx) {
+	int handle = 0;
+	{
+		Common::LockGuard lock(g_audioout2_port_mutex);
+		for (const auto& state: g_audioout2_ports) {
+			if (state.used && state.context == ctx && state.audio_handle > 0 &&
+			    !state.pcm_data.empty()) {
+				handle = state.audio_handle;
+				break;
+			}
+		}
+	}
+	return handle > 0 ? AudioInternal::AudioOutQueuedUs(handle) : -1;
+}

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Measure the device queue across all device ports, not only the first port with PCM.

audioout2_device_queued_us returns the queued time of the first port in the context that has a positive audio_handle and non-empty pcm_data. All push pacing now depends on that one value.

The selected port can be an AUDIO_OUT_PORT_TYPE_PADSPK port with an open SDL stream. When a DualSense is connected, Audio::AudioOutOutputs sends that port's PCM to DualSenseHaptics::Queue and never calls QueueSdlAudio. The port's SDL queue therefore stays empty, and AudioOutQueuedUs returns 0.

With device_us == 0, these effects follow:

  • audioout2_level_locked always reports level 0, so a non-blocking push is never refused.
  • audioout2_queue_context_audio is called with blocking == false. As a result, QueueSdlAudio does not pace the main port, and the PADSPK sleep is skipped.
  • The post-push wait loop exits at once, because 0 <= full_us.

The SDL queue of the main port in the same context then grows without a bound. Audio latency increases until the 200 ms clear in a later blocking push, which can only occur on the timer path.

Use the largest queued time over all device-backed ports in the context. A port that does not feed SDL then cannot hide the backlog of a port that does.

Proposed fix
 static int64_t audioout2_device_queued_us(AudioOut2ContextHandle ctx) {
-	int handle = 0;
+	std::array<int, AudioInternal::OUT_PORTS_MAX> handles {};
+	size_t                                         count = 0;
 	{
 		Common::LockGuard lock(g_audioout2_port_mutex);
 		for (const auto& state: g_audioout2_ports) {
 			if (state.used && state.context == ctx && state.audio_handle > 0 &&
-			    !state.pcm_data.empty()) {
-				handle = state.audio_handle;
-				break;
+			    !state.pcm_data.empty() && count < handles.size()) {
+				handles[count++] = state.audio_handle;
 			}
 		}
 	}
-	return handle > 0 ? AudioInternal::AudioOutQueuedUs(handle) : -1;
+	int64_t queued = -1;
+	for (size_t i = 0; i < count; i++) {
+		queued = std::max(queued, AudioInternal::AudioOutQueuedUs(handles[i]));
+	}
+	return queued;
 }
📝 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.

static int64_t audioout2_device_queued_us(AudioOut2ContextHandle ctx) {
	std::array<int, AudioInternal::OUT_PORTS_MAX> handles {};
	size_t                                         count = 0;
	{
		Common::LockGuard lock(g_audioout2_port_mutex);
		for (const auto& state: g_audioout2_ports) {
			if (state.used && state.context == ctx && state.audio_handle > 0 &&
			    !state.pcm_data.empty() && count < handles.size()) {
				handles[count++] = state.audio_handle;
			}
		}
	}
	int64_t queued = -1;
	for (size_t i = 0; i < count; i++) {
		queued = std::max(queued, AudioInternal::AudioOutQueuedUs(handles[i]));
	}
	return queued;
}
**@⁠coderabbitai[bot]** on GitHub · 2026-10-01 07:53 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/937#discussion_r4153083613) On `src/libs/libAudio2.cpp` line 550 (outdated): ```diff @@ -513,42 +529,89 @@ int KYTY_SYSV_ABI AudioOut2ContextAdvance(AudioOut2ContextHandle ctx) { return OK; } -int KYTY_SYSV_ABI AudioOut2ContextPush(AudioOut2ContextHandle ctx, uint32_t blocking) { - uint32_t sleep_micros = audioout2_grain_micros(512); +// Queue time SDL may hold beyond the queue depth before it counts. +constexpr uint64_t AUDIOOUT2_DEVICE_CUSHION_US = 20000; + +// Microseconds the context's device still has to play (its first port with PCM and a device), or +// -1 when it has none: then the timer model applies. +static int64_t audioout2_device_queued_us(AudioOut2ContextHandle ctx) { + int handle = 0; + { + Common::LockGuard lock(g_audioout2_port_mutex); + for (const auto& state: g_audioout2_ports) { + if (state.used && state.context == ctx && state.audio_handle > 0 && + !state.pcm_data.empty()) { + handle = state.audio_handle; + break; + } + } + } + return handle > 0 ? AudioInternal::AudioOutQueuedUs(handle) : -1; +} ``` _🎯 Functional Correctness_ | _🟠 Major_ | _⚡ Quick win_ **Measure the device queue across all device ports, not only the first port with PCM.** `audioout2_device_queued_us` returns the queued time of the first port in the context that has a positive `audio_handle` and non-empty `pcm_data`. All push pacing now depends on that one value. The selected port can be an `AUDIO_OUT_PORT_TYPE_PADSPK` port with an open SDL stream. When a DualSense is connected, `Audio::AudioOutOutputs` sends that port's PCM to `DualSenseHaptics::Queue` and never calls `QueueSdlAudio`. The port's SDL queue therefore stays empty, and `AudioOutQueuedUs` returns `0`. With `device_us == 0`, these effects follow: - `audioout2_level_locked` always reports level 0, so a non-blocking push is never refused. - `audioout2_queue_context_audio` is called with `blocking == false`. As a result, `QueueSdlAudio` does not pace the main port, and the `PADSPK` sleep is skipped. - The post-push wait loop exits at once, because `0 <= full_us`. The SDL queue of the main port in the same context then grows without a bound. Audio latency increases until the 200 ms clear in a later blocking push, which can only occur on the timer path. Use the largest queued time over all device-backed ports in the context. A port that does not feed SDL then cannot hide the backlog of a port that does. <details> <summary>Proposed fix</summary> ```diff static int64_t audioout2_device_queued_us(AudioOut2ContextHandle ctx) { - int handle = 0; + std::array<int, AudioInternal::OUT_PORTS_MAX> handles {}; + size_t count = 0; { Common::LockGuard lock(g_audioout2_port_mutex); for (const auto& state: g_audioout2_ports) { if (state.used && state.context == ctx && state.audio_handle > 0 && - !state.pcm_data.empty()) { - handle = state.audio_handle; - break; + !state.pcm_data.empty() && count < handles.size()) { + handles[count++] = state.audio_handle; } } } - return handle > 0 ? AudioInternal::AudioOutQueuedUs(handle) : -1; + int64_t queued = -1; + for (size_t i = 0; i < count; i++) { + queued = std::max(queued, AudioInternal::AudioOutQueuedUs(handles[i])); + } + return queued; } ``` </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 static int64_t audioout2_device_queued_us(AudioOut2ContextHandle ctx) { std::array<int, AudioInternal::OUT_PORTS_MAX> handles {}; size_t count = 0; { Common::LockGuard lock(g_audioout2_port_mutex); for (const auto& state: g_audioout2_ports) { if (state.used && state.context == ctx && state.audio_handle > 0 && !state.pcm_data.empty() && count < handles.size()) { handles[count++] = state.audio_handle; } } } int64_t queued = -1; for (size_t i = 0; i < count; i++) { queued = std::max(queued, AudioInternal::AudioOutQueuedUs(handles[i])); } return queued; } ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:ddacbddaee88804a139491d0 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-01 07:53 UTC · original · reviewed

Actionable comments posted: 3

Caution

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

⚠️ Outside diff range comments (1)

🟠 Major · Do not exit when an aged GPU-dirty buffer has no bytes to download. · bufferCache.cpp:785-788

src/graphics/host_gpu/renderer/cache/bufferCache.cpp:785-788
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Do not exit when an aged GPU-dirty buffer has no bytes to download.

dirty checks the tracker pages through IsRegionGpuModified. DownloadBufferMemory builds copies only from m_gpu_modified_ranges. These two states can now differ:

  • WriteClean (Line 306-310) subtracts the overwritten bytes from m_gpu_modified_ranges, but the tracker pages stay GPU-modified.
  • The ReadMemory comment (Line 327-331) describes the same state: the page is protected as GPU-written, but no bytes wait for a download.

If such a buffer ages out, DownloadBufferMemory returns false, and EXIT_IF ends the emulator. Treat a false result as "nothing to publish". The unmark/untrack loop after the wait already handles the buffer.

Proposed fix
 		if (dirty) {
-			EXIT_IF(!DownloadBufferMemory(buffer, buffer.CpuAddress(), buffer.Size()));
+			// Pages can stay GPU-protected with no dirty bytes left (WriteClean, partial
+			// downloads); there is then nothing to publish before releasing them.
+			(void)DownloadBufferMemory(buffer, buffer.CpuAddress(), buffer.Size());
 			dirty_buffers.push_back(id);

ℹ️ Review info
⚙️ Run configuration

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

Review profile: CHILL

Plan: Advanced

Run ID: 00ffb172-dcfc-4fff-8f44-567325be7547

📥 Commits

Reviewing files that changed from the base of the PR and between d6ec3a42ed19d0f16bb3e184ca57e20cce8d5176 and 3fa2b06dda4c7acfe64f33d8eef6c636405a76dd.

📒 Files selected for processing (45)
  • CMakeLists.txt
  • src/graphics/guest_gpu/command_processor/commandProcessor.h
  • src/graphics/guest_gpu/graphicsRun.cpp
  • src/graphics/guest_gpu/graphicsRun.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/textureCache.cpp
  • 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/pipeline/shaders.cpp
  • 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/presentation/window/vulkanWindow.cpp
  • src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.cpp
  • src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.h
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h
  • src/graphics/shader/recompiler/frontend/decode/ImageOps.cpp
  • src/graphics/shader/recompiler/frontend/decode/ShaderDecoder.h
  • src/graphics/shader/recompiler/frontend/decode/VectorAluOps.cpp
  • src/graphics/shader/recompiler/frontend/translate/Translate.cpp
  • src/graphics/shader/recompiler/frontend/translate/Vector.cpp
  • src/graphics/shader/recompiler/ir/ResourceSnapshot.h
  • src/graphics/shader/recompiler/ir/ShaderIR.h
  • src/graphics/shader/recompiler/ir/Value.cpp
  • src/graphics/shader/recompiler/ir/Value.h
  • src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp
  • src/graphics/shader/recompiler/ir/passes/SrtWalker.h
  • src/graphics/shader/shader.cpp
  • src/graphics/shader/shader.h
  • src/kernel/memory.cpp
  • src/kernel/memory.h
  • src/kernel/memoryAddressSpace.inc
  • src/kernel/pthread.cpp
  • src/libs/audio.cpp
  • src/libs/audio_internal.h
  • src/libs/libAmpr.cpp
  • src/libs/libAudio2.cpp
  • tests/AudioOut2PortTests.cpp
  • tests/ResourceTrackingTests.cpp
  • tests/ShaderRecompilerComputeTests.cpp
💤 Files with no reviewable changes (1)
  • src/graphics/shader/recompiler/ir/Value.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-10-01 07:53 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/937#pullrequestreview-5376488456) · **reviewed** **Actionable comments posted: 3** > [!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> · Do not exit when an aged GPU-dirty buffer has no bytes to download. · <code>bufferCache.cpp:785-788</code></summary><blockquote> > > `src/graphics/host_gpu/renderer/cache/bufferCache.cpp:785-788` > _🩺 Stability & Availability_ | _🟠 Major_ | _⚡ Quick win_ > > **Do not exit when an aged GPU-dirty buffer has no bytes to download.** > > `dirty` checks the tracker pages through `IsRegionGpuModified`. `DownloadBufferMemory` builds copies only from `m_gpu_modified_ranges`. These two states can now differ: > - `WriteClean` (Line 306-310) subtracts the overwritten bytes from `m_gpu_modified_ranges`, but the tracker pages stay GPU-modified. > - The `ReadMemory` comment (Line 327-331) describes the same state: the page is protected as GPU-written, but no bytes wait for a download. > > If such a buffer ages out, `DownloadBufferMemory` returns `false`, and `EXIT_IF` ends the emulator. Treat a `false` result as "nothing to publish". The unmark/untrack loop after the wait already handles the buffer. > > <details> > <summary>Proposed fix</summary> > > ```diff > if (dirty) { > - EXIT_IF(!DownloadBufferMemory(buffer, buffer.CpuAddress(), buffer.Size())); > + // Pages can stay GPU-protected with no dirty bytes left (WriteClean, partial > + // downloads); there is then nothing to publish before releasing them. > + (void)DownloadBufferMemory(buffer, buffer.CpuAddress(), buffer.Size()); > dirty_buffers.push_back(id); > ``` > </details> > > <!-- cr-comment:v1:62d16169553fc4230dc5f662 --> > > </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**: `00ffb172-dcfc-4fff-8f44-567325be7547` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between d6ec3a42ed19d0f16bb3e184ca57e20cce8d5176 and 3fa2b06dda4c7acfe64f33d8eef6c636405a76dd. </details> <details> <summary>📒 Files selected for processing (45)</summary> * `CMakeLists.txt` * `src/graphics/guest_gpu/command_processor/commandProcessor.h` * `src/graphics/guest_gpu/graphicsRun.cpp` * `src/graphics/guest_gpu/graphicsRun.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/textureCache.cpp` * `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/pipeline/shaders.cpp` * `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/presentation/window/vulkanWindow.cpp` * `src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.cpp` * `src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.h` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h` * `src/graphics/shader/recompiler/frontend/decode/ImageOps.cpp` * `src/graphics/shader/recompiler/frontend/decode/ShaderDecoder.h` * `src/graphics/shader/recompiler/frontend/decode/VectorAluOps.cpp` * `src/graphics/shader/recompiler/frontend/translate/Translate.cpp` * `src/graphics/shader/recompiler/frontend/translate/Vector.cpp` * `src/graphics/shader/recompiler/ir/ResourceSnapshot.h` * `src/graphics/shader/recompiler/ir/ShaderIR.h` * `src/graphics/shader/recompiler/ir/Value.cpp` * `src/graphics/shader/recompiler/ir/Value.h` * `src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp` * `src/graphics/shader/recompiler/ir/passes/SrtWalker.h` * `src/graphics/shader/shader.cpp` * `src/graphics/shader/shader.h` * `src/kernel/memory.cpp` * `src/kernel/memory.h` * `src/kernel/memoryAddressSpace.inc` * `src/kernel/pthread.cpp` * `src/libs/audio.cpp` * `src/libs/audio_internal.h` * `src/libs/libAmpr.cpp` * `src/libs/libAudio2.cpp` * `tests/AudioOut2PortTests.cpp` * `tests/ResourceTrackingTests.cpp` * `tests/ShaderRecompilerComputeTests.cpp` </details> <details> <summary>💤 Files with no reviewable changes (1)</summary> * src/graphics/shader/recompiler/ir/Value.cpp </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
Author
Owner

@⁠ronith256 on GitHub · 2026-10-11 09:44 UTC · original

Linux confirmation for PPSA03671 on PR head 41c7b27:

  • Host: Fedora 44, AMD x86-64 CPU, NVIDIA GeForce RTX 3080 (driver 610.57.04).
  • Built kyty_emulator locally with Clang 22.1.8 and glslangValidator 16.2.0.
  • Launch: KYTY_IGNORE_WRITTEN_OVERLAP=1 KYTY_LABELS_AFTER_GPU=1 ./kyty_emulator --game /path/to/eboot.bin --bindless --tessellation --readback-linear-images true --amd-cpu --screen-width 1600 --screen-height 900 --shader-validation false
  • The shader failure at pc 0x0000114c seen on current main did not recur. The game reached its visible opening screen and screen-reader accessibility prompt. The emulator remained running at that prompt.

--redzone is rejected as an unknown option on Linux; the flag is Windows-only in src/main.cpp, so the Linux command above omits it.

**@⁠ronith256** on GitHub · 2026-10-11 09:44 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/937#issuecomment-6107708712) Linux confirmation for PPSA03671 on PR head `41c7b27`: - Host: Fedora 44, AMD x86-64 CPU, NVIDIA GeForce RTX 3080 (driver 610.57.04). - Built `kyty_emulator` locally with Clang 22.1.8 and glslangValidator 16.2.0. - Launch: `KYTY_IGNORE_WRITTEN_OVERLAP=1 KYTY_LABELS_AFTER_GPU=1 ./kyty_emulator --game /path/to/eboot.bin --bindless --tessellation --readback-linear-images true --amd-cpu --screen-width 1600 --screen-height 900 --shader-validation false` - The shader failure at `pc 0x0000114c` seen on current `main` did not recur. The game reached its visible opening screen and screen-reader accessibility prompt. The emulator remained running at that prompt. `--redzone` is rejected as an unknown option on Linux; the flag is Windows-only in `src/main.cpp`, so the Linux command above omits it.
@ -1089,0 +1200,4 @@
PublishLabelAtCompletion(dst, data, sizeof(data), false);
} else if (at_completion) {
m_renderer.GetGpu().DeferLabelWrite(reinterpret_cast<uint64_t>(dst), data,
sizeof(data));
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-11 18:57 UTC · original

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Route the other label conditions through ReadLabel.

With KYTY_LABELS_AT_COMPLETION=1, DeferLabelWrite keeps the new value pending while backing memory retains the old value. CpOpCondExec still dereferences its comparison address directly at Line 1444 of src/graphics/guest_gpu/command_processor/pm4Handlers.cpp. Boolean CommandProcessor::SetPredication does the same at Line 929 of src/graphics/guest_gpu/graphicsRun.cpp. If either packet follows a deferred EOP write to that address, it can execute the wrong command path. Use the pending-label-aware read for these conditions too. The scheduler runs the write callback only after its recorded tick. (raw.githubusercontent.com)

**@⁠coderabbitai[bot]** on GitHub · 2026-10-11 18:57 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/937#discussion_r4242791710) **🎯 Functional Correctness** | **🟠 Major** | **⚡ Quick win** **Route the other label conditions through `ReadLabel`.** With `KYTY_LABELS_AT_COMPLETION=1`, `DeferLabelWrite` keeps the new value pending while backing memory retains the old value. `CpOpCondExec` still dereferences its comparison address directly at Line 1444 of `src/graphics/guest_gpu/command_processor/pm4Handlers.cpp`. Boolean `CommandProcessor::SetPredication` does the same at Line 929 of `src/graphics/guest_gpu/graphicsRun.cpp`. If either packet follows a deferred EOP write to that address, it can execute the wrong command path. Use the pending-label-aware read for these conditions too. The scheduler runs the write callback only after its recorded tick. ([raw.githubusercontent.com](https://raw.githubusercontent.com/KytyPS5/KytyPS5/41c7b27/src/graphics/host_gpu/renderer/commandScheduler.cpp)) <!-- fingerprinting:phantom:poseidon:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:a1b71dabb2f77d7c6ec768e3 --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -336,0 +359,4 @@
EXIT_NOT_IMPLEMENTED(m_worker_buffer.begin(&begin_info) != vk::Result::eSuccess);
});
return m_command;
}
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-11 18:57 UTC · original

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Invalidate the dynamic state in the threaded BeginCommand path.

The non-threaded path calls m_dynamic_state.Invalidate() after it begins a new command buffer. The threaded path returns at Line 361 without that call. RenderContext enables the recording thread unconditionally, so every guest command buffer takes this path.

A new Vulkan command buffer inherits no dynamic state. DynamicState::Commit emits only dirty fields. The first draw in each new command buffer is therefore recorded without viewport, scissor, depth, stencil, blend-constant, or color-write state when those values did not change since the previous command buffer. This is undefined behavior in Vulkan: validation errors, wrong rendering, or device loss.

Proposed fix
 	if (m_threaded) {
 		m_command.m_buffer = nullptr;
 		Record([this, tick](vk::CommandBuffer) {
 			...
 		});
+		m_dynamic_state.Invalidate();
 		return m_command;
 	}
📝 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.

	if (m_threaded) {
		m_command.m_buffer = nullptr;
		Record([this, tick](vk::CommandBuffer) {
			m_worker_buffer = m_command_pool.Commit(tick);
			vk::CommandBufferBeginInfo begin_info {};
			begin_info.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit;
			EXIT_NOT_IMPLEMENTED(m_worker_buffer.begin(&begin_info) != vk::Result::eSuccess);
		});
		m_dynamic_state.Invalidate();
		return m_command;
	}
**@⁠coderabbitai[bot]** on GitHub · 2026-10-11 18:57 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/937#discussion_r4242791712) **🎯 Functional Correctness** | **🟠 Major** | **⚡ Quick win** **Invalidate the dynamic state in the threaded `BeginCommand` path.** The non-threaded path calls `m_dynamic_state.Invalidate()` after it begins a new command buffer. The threaded path returns at Line 361 without that call. `RenderContext` enables the recording thread unconditionally, so every guest command buffer takes this path. A new Vulkan command buffer inherits no dynamic state. `DynamicState::Commit` emits only dirty fields. The first draw in each new command buffer is therefore recorded without viewport, scissor, depth, stencil, blend-constant, or color-write state when those values did not change since the previous command buffer. This is undefined behavior in Vulkan: validation errors, wrong rendering, or device loss. <details> <summary>Proposed fix</summary> ```diff if (m_threaded) { m_command.m_buffer = nullptr; Record([this, tick](vk::CommandBuffer) { ... }); + m_dynamic_state.Invalidate(); return m_command; } ``` </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 if (m_threaded) { m_command.m_buffer = nullptr; Record([this, tick](vk::CommandBuffer) { m_worker_buffer = m_command_pool.Commit(tick); vk::CommandBufferBeginInfo begin_info {}; begin_info.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit; EXIT_NOT_IMPLEMENTED(m_worker_buffer.begin(&begin_info) != vk::Result::eSuccess); }); m_dynamic_state.Invalidate(); return m_command; } ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:b70bf4e8b9559088eece0c0a --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -336,0 +357,4 @@
vk::CommandBufferBeginInfo begin_info {};
begin_info.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit;
EXIT_NOT_IMPLEMENTED(m_worker_buffer.begin(&begin_info) != vk::Result::eSuccess);
});
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-11 18:57 UTC · original

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
fd -e h -e cpp masterSemaphore --exec cat -n {}

Repository: KytyPS5/KytyPS5

Length of output: 4111


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- CommandPool references and declarations ---'
rg -n -F --glob '*.{h,cpp}' -- 'class CommandPool' src
rg -n -F --glob '*.{h,cpp}' -- 'CommandPool::' src
rg -n -F --glob '*.{h,cpp}' -- 'm_command_pool' src/graphics/host_gpu/renderer
printf '%s\n' '--- relevant source files ---'
files=$(rg -l -F --glob '*.{h,cpp}' -- 'class CommandPool' src; rg -l -F --glob '*.{h,cpp}' -- 'CommandPool::' src)
for f in $files; do
  printf '\n### %s\n' "$f"
  nl -ba "$f"
done
printf '%s\n' '--- changed scheduler block ---'
nl -ba src/graphics/host_gpu/renderer/commandScheduler.cpp | sed -n '280,430p'

Repository: KytyPS5/KytyPS5

Length of output: 41550


🏁 Script executed:

set -eu
rg -n -F --glob '*.h' --glob '*.cpp' -- 'CommandPool' src/graphics/host_gpu/renderer
printf '%s\n' '--- pool files ---'
for f in $(rg -l -F --glob '*.h' --glob '*.cpp' -- 'CommandPool' src/graphics/host_gpu/renderer); do
  printf '\n### %s\n' "$f"
  nl -ba "$f"
done
printf '%s\n' '--- scheduler Commit/Record/Submit paths ---'
rg -n -F --glob 'commandScheduler.cpp' -- 'm_command_pool.Commit' 'm_command_pool' 'Record(' 'Submit(' src/graphics/host_gpu/renderer
nl -ba src/graphics/host_gpu/renderer/commandScheduler.cpp | sed -n '320,410p'

Repository: KytyPS5/KytyPS5

Length of output: 36798


🌐 Web query:

Vulkan vkGetSemaphoreCounterValue host synchronization requirement vkWaitSemaphores vkGetSemaphoreCounterValue official specification

💡 Result:

For **timeline semaphores**, the current Khronos spec distinguishes the two host calls:

- **`vkGetSemaphoreCounterValue`**: host access to `semaphore` **must be externally synchronized**. So don’t make concurrent host accesses to that semaphore unless you synchronize them yourself. The semaphore must also be a timeline semaphore. ([docs.vulkan.org](https://docs.vulkan.org/spec/latest/chapters/synchronization.html?utm_source=openai))
- **`vkWaitSemaphores`**: the spec lists **no host-synchronization requirement** for the semaphore handles. Multiple host threads can wait on the same timeline semaphore without externally synchronizing those waits. It blocks until the requested value(s) are reached or the timeout expires. ([docs.vulkan.org](https://docs.vulkan.org/spec/latest/chapters/synchronization.html?utm_source=openai))

The queried counter is only a snapshot: if a queue submission is pending, the returned value may already be out of date. Use `vkWaitSemaphores` when you need to wait for a target value. ([docs.vulkan.org](https://docs.vulkan.org/spec/latest/chapters/synchronization.html?utm_source=openai))

Citations:

- 1: https://docs.vulkan.org/spec/latest/chapters/synchronization.html?utm_source=openai
- 2: https://docs.vulkan.org/spec/latest/chapters/synchronization.html?utm_source=openai
- 3: https://docs.vulkan.org/spec/latest/chapters/synchronization.html?utm_source=openai

Serialize vkGetSemaphoreCounterValue calls in MasterSemaphore.

m_gpu_tick is atomic, so it does not have the proposed C++ data race. However, CommandPool::Commit can call m_master.Refresh() on the recording thread while scheduler paths call Refresh() concurrently. Refresh() calls vkGetSemaphoreCounterValue without external synchronization. Vulkan requires host access for this operation to be externally synchronized.

Suggested fix
 #include <atomic>
+#include <mutex>
 
@@
 private:
+	std::mutex            m_refresh_mutex;
 	GraphicContext&       m_graphics;
 void MasterSemaphore::Refresh() {
+	std::lock_guard lock(m_refresh_mutex);
 	uint64_t   counter = 0;
**@⁠coderabbitai[bot]** on GitHub · 2026-10-11 18:57 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/937#discussion_r4242791724) **🩺 Stability & Availability** | **🟡 Minor** | **⚡ Quick win** <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash #!/bin/bash fd -e h -e cpp masterSemaphore --exec cat -n {} ``` Repository: KytyPS5/KytyPS5 Length of output: 4111 --- 🏁 Script executed: ```bash #!/bin/bash set -e printf '%s\n' '--- CommandPool references and declarations ---' rg -n -F --glob '*.{h,cpp}' -- 'class CommandPool' src rg -n -F --glob '*.{h,cpp}' -- 'CommandPool::' src rg -n -F --glob '*.{h,cpp}' -- 'm_command_pool' src/graphics/host_gpu/renderer printf '%s\n' '--- relevant source files ---' files=$(rg -l -F --glob '*.{h,cpp}' -- 'class CommandPool' src; rg -l -F --glob '*.{h,cpp}' -- 'CommandPool::' src) for f in $files; do printf '\n### %s\n' "$f" nl -ba "$f" done printf '%s\n' '--- changed scheduler block ---' nl -ba src/graphics/host_gpu/renderer/commandScheduler.cpp | sed -n '280,430p' ``` Repository: KytyPS5/KytyPS5 Length of output: 41550 --- 🏁 Script executed: ```bash set -eu rg -n -F --glob '*.h' --glob '*.cpp' -- 'CommandPool' src/graphics/host_gpu/renderer printf '%s\n' '--- pool files ---' for f in $(rg -l -F --glob '*.h' --glob '*.cpp' -- 'CommandPool' src/graphics/host_gpu/renderer); do printf '\n### %s\n' "$f" nl -ba "$f" done printf '%s\n' '--- scheduler Commit/Record/Submit paths ---' rg -n -F --glob 'commandScheduler.cpp' -- 'm_command_pool.Commit' 'm_command_pool' 'Record(' 'Submit(' src/graphics/host_gpu/renderer nl -ba src/graphics/host_gpu/renderer/commandScheduler.cpp | sed -n '320,410p' ``` Repository: KytyPS5/KytyPS5 Length of output: 36798 --- 🌐 Web query: `Vulkan vkGetSemaphoreCounterValue host synchronization requirement vkWaitSemaphores vkGetSemaphoreCounterValue official specification` 💡 Result: ``` For **timeline semaphores**, the current Khronos spec distinguishes the two host calls: - **`vkGetSemaphoreCounterValue`**: host access to `semaphore` **must be externally synchronized**. So don’t make concurrent host accesses to that semaphore unless you synchronize them yourself. The semaphore must also be a timeline semaphore. ([docs.vulkan.org](https://docs.vulkan.org/spec/latest/chapters/synchronization.html?utm_source=openai)) - **`vkWaitSemaphores`**: the spec lists **no host-synchronization requirement** for the semaphore handles. Multiple host threads can wait on the same timeline semaphore without externally synchronizing those waits. It blocks until the requested value(s) are reached or the timeout expires. ([docs.vulkan.org](https://docs.vulkan.org/spec/latest/chapters/synchronization.html?utm_source=openai)) The queried counter is only a snapshot: if a queue submission is pending, the returned value may already be out of date. Use `vkWaitSemaphores` when you need to wait for a target value. ([docs.vulkan.org](https://docs.vulkan.org/spec/latest/chapters/synchronization.html?utm_source=openai)) Citations: - 1: https://docs.vulkan.org/spec/latest/chapters/synchronization.html?utm_source=openai - 2: https://docs.vulkan.org/spec/latest/chapters/synchronization.html?utm_source=openai - 3: https://docs.vulkan.org/spec/latest/chapters/synchronization.html?utm_source=openai ``` --- </details> **Serialize `vkGetSemaphoreCounterValue` calls in `MasterSemaphore`.** `m_gpu_tick` is atomic, so it does not have the proposed C++ data race. However, `CommandPool::Commit` can call `m_master.Refresh()` on the recording thread while scheduler paths call `Refresh()` concurrently. `Refresh()` calls `vkGetSemaphoreCounterValue` without external synchronization. Vulkan requires host access for this operation to be externally synchronized. <details> <summary>Suggested fix</summary> ```diff #include <atomic> +#include <mutex> @@ private: + std::mutex m_refresh_mutex; GraphicContext& m_graphics; ``` ```diff void MasterSemaphore::Refresh() { + std::lock_guard lock(m_refresh_mutex); uint64_t counter = 0; ``` </details> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:0e87e3e57a0cbbfe2dab5420 --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -387,0 +528,4 @@
void CommandScheduler::DispatchChunk() {
if (m_chunk == nullptr || m_chunk->first == nullptr) {
return;
}
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-11 18:57 UTC · original

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Allocate can destroy a chunk that holds live stashed data.

DispatchChunk returns without queuing when m_chunk->first == nullptr. At Lines 519-522, Allocate then assigns m_chunk = take(). That assignment destroys the old chunk, but the old chunk can already hold arrays from Stash calls of the command that is being built.

Trigger: a fresh chunk receives stash data before its first Record, and the command's stash data exceeds the remaining space. One example is StashWrites for a large descriptor or bindless write array. The pointers that were already returned by Stash then dangle. The recording thread later reads freed memory.

Fix: dispatch the chunk whenever used != 0, not only when it holds commands. RecordingThread already handles a chunk with an empty command list, and the retention window keeps the chunk alive. Also note that the comment "up to two chunks before" holds only when one command's stash data spans at most two chunks.

Proposed fix
--- "a/src/graphics/host_gpu/renderer/commandScheduler.cpp"
+++ "b/src/graphics/host_gpu/renderer/commandScheduler.cpp"
@@ -525,10 +525,10 @@
 	return m_chunk->storage + offset;
 }
 
 void CommandScheduler::DispatchChunk() {
-	if (m_chunk == nullptr || m_chunk->first == nullptr) {
+	if (m_chunk == nullptr || (m_chunk->first == nullptr && m_chunk->used == 0)) {
 		return;
 	}
 	{
 		std::lock_guard lock(m_record_mutex);
 		m_record_queue.push_back(std::move(m_chunk));
📝 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.

void CommandScheduler::DispatchChunk() {
	if (m_chunk == nullptr || (m_chunk->first == nullptr && m_chunk->used == 0)) {
		return;
	}
**@⁠coderabbitai[bot]** on GitHub · 2026-10-11 18:57 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/937#discussion_r4242791727) **🩺 Stability & Availability** | **🟡 Minor** | **⚡ Quick win** **`Allocate` can destroy a chunk that holds live stashed data.** `DispatchChunk` returns without queuing when `m_chunk->first == nullptr`. At Lines 519-522, `Allocate` then assigns `m_chunk = take()`. That assignment destroys the old chunk, but the old chunk can already hold arrays from `Stash` calls of the command that is being built. Trigger: a fresh chunk receives stash data before its first `Record`, and the command's stash data exceeds the remaining space. One example is `StashWrites` for a large descriptor or bindless write array. The pointers that were already returned by `Stash` then dangle. The recording thread later reads freed memory. Fix: dispatch the chunk whenever `used != 0`, not only when it holds commands. `RecordingThread` already handles a chunk with an empty command list, and the retention window keeps the chunk alive. Also note that the comment "up to two chunks before" holds only when one command's stash data spans at most two chunks. <details> <summary>Proposed fix</summary> ```diff --- "a/src/graphics/host_gpu/renderer/commandScheduler.cpp" +++ "b/src/graphics/host_gpu/renderer/commandScheduler.cpp" @@ -525,10 +525,10 @@ return m_chunk->storage + offset; } void CommandScheduler::DispatchChunk() { - if (m_chunk == nullptr || m_chunk->first == nullptr) { + if (m_chunk == nullptr || (m_chunk->first == nullptr && m_chunk->used == 0)) { return; } { std::lock_guard lock(m_record_mutex); m_record_queue.push_back(std::move(m_chunk)); ``` </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 void CommandScheduler::DispatchChunk() { if (m_chunk == nullptr || (m_chunk->first == nullptr && m_chunk->used == 0)) { return; } ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:664f80904596272d68d7431c --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -343,0 +356,4 @@
if (!skip_device && !TryGetSurfaceCapabilities(device, surface, candidate_capabilities)) {
LOGF("Surface capabilities unavailable, skipping device\n");
skip_device = true;
}
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-11 18:57 UTC · original

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Record the surface-capability failure as a device rejection.

This branch sets skip_device directly and does not call reject. If this is the only candidate device, out_rejections stays empty. CreateVulkan then exits with "Could not find suitable device:" and gives no reason. Use reject so that the fatal message names the cause.

Proposed fix
--- "a/src/graphics/presentation/window/vulkanWindow.cpp"
+++ "b/src/graphics/presentation/window/vulkanWindow.cpp"
@@ -353,10 +353,9 @@
 		}
 
 		SurfaceCapabilities candidate_capabilities;
 		if (!skip_device && !TryGetSurfaceCapabilities(device, surface, candidate_capabilities)) {
-			LOGF("Surface capabilities unavailable, skipping device\n");
-			skip_device = true;
+			reject("Surface capabilities are unavailable");
 		}
 		if (!skip_device) {
 			if (!(candidate_capabilities.capabilities.supportedUsageFlags &
 			      vk::ImageUsageFlagBits::eTransferDst)) {
📝 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.

		if (!skip_device && !TryGetSurfaceCapabilities(device, surface, candidate_capabilities)) {
			reject("Surface capabilities are unavailable");
		}
**@⁠coderabbitai[bot]** on GitHub · 2026-10-11 18:57 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/937#discussion_r4242791730) **📐 Maintainability & Code Quality** | **🟡 Minor** | **⚡ Quick win** **Record the surface-capability failure as a device rejection.** This branch sets `skip_device` directly and does not call `reject`. If this is the only candidate device, `out_rejections` stays empty. `CreateVulkan` then exits with "Could not find suitable device:" and gives no reason. Use `reject` so that the fatal message names the cause. <details> <summary>Proposed fix</summary> ```diff --- "a/src/graphics/presentation/window/vulkanWindow.cpp" +++ "b/src/graphics/presentation/window/vulkanWindow.cpp" @@ -353,10 +353,9 @@ } SurfaceCapabilities candidate_capabilities; if (!skip_device && !TryGetSurfaceCapabilities(device, surface, candidate_capabilities)) { - LOGF("Surface capabilities unavailable, skipping device\n"); - skip_device = true; + reject("Surface capabilities are unavailable"); } if (!skip_device) { if (!(candidate_capabilities.capabilities.supportedUsageFlags & vk::ImageUsageFlagBits::eTransferDst)) { ``` </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 if (!skip_device && !TryGetSurfaceCapabilities(device, surface, candidate_capabilities)) { reject("Surface capabilities are unavailable"); } ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:51f54f03362762fdeb913811 --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -1077,0 +1278,4 @@
const auto& b = args[1];
switch (op) {
case ValueOpcode::IAdd32: out = {a.lo + b.lo, a.hi + b.hi}; break;
case ValueOpcode::IMul32: out = {a.lo * b.lo, a.hi * b.hi}; break;
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-11 18:57 UTC · original

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

set -e
printf '%s\n' '--- diff ---'
git diff --unified=40 984cfcebd141b211aa9e0a8cde63b0ebe652d07a cc6c83e34c404e2197c4d7b7c5ddc217b8ccda9c -- src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp
printf '%s\n' '--- target excerpts ---'
nl -ba src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp | sed -n '1180,1415p'
printf '%s\n' '--- overlap consumer references ---'
rg -n -F --glob '*.{cpp,h,hpp}' 'failed[|extent|WrittenOverlap|written overlap|Overlap' src/graphics | head -200

Repository: KytyPS5/KytyPS5

Length of output: 44544


🏁 Script executed:

set -e
printf '%s\n' '--- extent declarations and uses ---'
rg -n -F --glob '*.{h,hpp,cpp}' 'buffer_write_extents' src
rg -n -F --glob '*.{h,hpp,cpp}' 'buffer_writes_bounded' src
printf '%s\n' '--- overlap and descriptor access ---'
rg -n -i --glob '*.{h,hpp,cpp}' 'written.?overlap|overlap.*written|buffer.*extent|GetSize\(\)|AddTid\(\)|Soffset|soffset' src/graphics src/core src
printf '%s\n' '--- relevant declarations ---'
rg -n -F --glob '*.{h,hpp,cpp}' 'struct ResourceSnapshot' src
rg -n -F --glob '*.{h,hpp,cpp}' 'struct ShaderBufferResource' src

Repository: KytyPS5/KytyPS5

Length of output: 25280


🏁 Script executed:

set -e
printf '%s\n' '--- extent type ---'
nl -ba src/graphics/shader/recompiler/ir/ResourceSnapshot.h | sed -n '45,75p'
printf '%s\n' '--- overlap helper and setup ---'
nl -ba src/graphics/host_gpu/renderer/pipeline/descriptors.cpp | sed -n '90,135p'
nl -ba src/graphics/host_gpu/renderer/pipeline/descriptors.cpp | sed -n '780,885p'
printf '%s\n' '--- overlap consumer ---'
nl -ba src/graphics/host_gpu/renderer/pipeline/descriptors.cpp | sed -n '985,1045p'
printf '%s\n' '--- address calculation ---'
nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp | sed -n '30,90p'
nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp | sed -n '885,930p'
printf '%s\n' '--- descriptor fields ---'
nl -ba src/graphics/shader/shaderBindings.h | sed -n '35,70p'

Repository: KytyPS5/KytyPS5

Length of output: 21804


🏁 Script executed:

set -e
nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp | sed -n '85,155p'
nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp | sed -n '430,535p'
nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp | sed -n '880,985p'

Repository: KytyPS5/KytyPS5

Length of output: 16349


🏁 Script executed:

set -e
nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp | sed -n '980,1085p'
rg -n -F --glob 'spirvEmitterMemory.cpp' 'StoreIndirect|StoreBuffer|EmitMemoryElementInBounds|BufferByteAddress' src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp

Repository: KytyPS5/KytyPS5

Length of output: 6350


🏁 Script executed:

set -e
rg -n -F --glob 'spirvEmitterMemory.cpp' 'StoreWordPrepared' src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp
rg -n -F --glob 'spirvEmitterMemory.cpp' 'PrepareMemoryResourceAccess' src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp
rg -n -F --glob 'spirvEmitterMemory.cpp' 'EmitMemoryElementInBounds' src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp
nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp | sed -n '300,430p'

Repository: KytyPS5/KytyPS5

Length of output: 10063


🏁 Script executed:

set -e
nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp | sed -n '270,310p'
nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp | sed -n '530,575p'

Repository: KytyPS5/KytyPS5

Length of output: 4565


🏁 Script executed:

set -e
rg -n -F --glob '*.{cpp,h,hpp}' 'EmitMemoryElementInBounds' src/graphics/shader/recompiler

Repository: KytyPS5/KytyPS5

Length of output: 2286


🏁 Script executed:

set -e
nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemoryHelpers.cpp | sed -n '205,250p'

Repository: KytyPS5/KytyPS5

Length of output: 2659


Reject wrapped buffer-address extents.

CalculateBufferAddress performs the buffer additions as uint32_t. A valid store can wrap to a low address and pass EmitMemoryElementInBounds. ComputeBufferWriteExtents uses 64-bit arithmetic instead, so it can set begin and end to the descriptor limit and report an empty or incomplete range. The overlap check can then miss the store.

The IAdd32 and IMul32 interval checks already reject results whose upper bound exceeds UINT32_MAX. Add the guard before computing the extent:

Suggested fix
+		if (offset.hi + soffset.hi + write.immediate > UINT32_MAX) {
+			failed[write.buffer] = 1u;
+			extent               = {};
+			continue;
+		}
 		const uint64_t stride = descriptor.Stride();
**@⁠coderabbitai[bot]** on GitHub · 2026-10-11 18:57 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/937#discussion_r4242791732) **🗄️ Data Integrity & Integration** | **🟡 Minor** | **⚡ Quick win** <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash set -e printf '%s\n' '--- diff ---' git diff --unified=40 984cfcebd141b211aa9e0a8cde63b0ebe652d07a cc6c83e34c404e2197c4d7b7c5ddc217b8ccda9c -- src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp printf '%s\n' '--- target excerpts ---' nl -ba src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp | sed -n '1180,1415p' printf '%s\n' '--- overlap consumer references ---' rg -n -F --glob '*.{cpp,h,hpp}' 'failed[|extent|WrittenOverlap|written overlap|Overlap' src/graphics | head -200 ``` Repository: KytyPS5/KytyPS5 Length of output: 44544 --- 🏁 Script executed: ```bash set -e printf '%s\n' '--- extent declarations and uses ---' rg -n -F --glob '*.{h,hpp,cpp}' 'buffer_write_extents' src rg -n -F --glob '*.{h,hpp,cpp}' 'buffer_writes_bounded' src printf '%s\n' '--- overlap and descriptor access ---' rg -n -i --glob '*.{h,hpp,cpp}' 'written.?overlap|overlap.*written|buffer.*extent|GetSize\(\)|AddTid\(\)|Soffset|soffset' src/graphics src/core src printf '%s\n' '--- relevant declarations ---' rg -n -F --glob '*.{h,hpp,cpp}' 'struct ResourceSnapshot' src rg -n -F --glob '*.{h,hpp,cpp}' 'struct ShaderBufferResource' src ``` Repository: KytyPS5/KytyPS5 Length of output: 25280 --- 🏁 Script executed: ```bash set -e printf '%s\n' '--- extent type ---' nl -ba src/graphics/shader/recompiler/ir/ResourceSnapshot.h | sed -n '45,75p' printf '%s\n' '--- overlap helper and setup ---' nl -ba src/graphics/host_gpu/renderer/pipeline/descriptors.cpp | sed -n '90,135p' nl -ba src/graphics/host_gpu/renderer/pipeline/descriptors.cpp | sed -n '780,885p' printf '%s\n' '--- overlap consumer ---' nl -ba src/graphics/host_gpu/renderer/pipeline/descriptors.cpp | sed -n '985,1045p' printf '%s\n' '--- address calculation ---' nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp | sed -n '30,90p' nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp | sed -n '885,930p' printf '%s\n' '--- descriptor fields ---' nl -ba src/graphics/shader/shaderBindings.h | sed -n '35,70p' ``` Repository: KytyPS5/KytyPS5 Length of output: 21804 --- 🏁 Script executed: ```bash set -e nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp | sed -n '85,155p' nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp | sed -n '430,535p' nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp | sed -n '880,985p' ``` Repository: KytyPS5/KytyPS5 Length of output: 16349 --- 🏁 Script executed: ```bash set -e nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp | sed -n '980,1085p' rg -n -F --glob 'spirvEmitterMemory.cpp' 'StoreIndirect|StoreBuffer|EmitMemoryElementInBounds|BufferByteAddress' src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 6350 --- 🏁 Script executed: ```bash set -e rg -n -F --glob 'spirvEmitterMemory.cpp' 'StoreWordPrepared' src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp rg -n -F --glob 'spirvEmitterMemory.cpp' 'PrepareMemoryResourceAccess' src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp rg -n -F --glob 'spirvEmitterMemory.cpp' 'EmitMemoryElementInBounds' src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp | sed -n '300,430p' ``` Repository: KytyPS5/KytyPS5 Length of output: 10063 --- 🏁 Script executed: ```bash set -e nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp | sed -n '270,310p' nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp | sed -n '530,575p' ``` Repository: KytyPS5/KytyPS5 Length of output: 4565 --- 🏁 Script executed: ```bash set -e rg -n -F --glob '*.{cpp,h,hpp}' 'EmitMemoryElementInBounds' src/graphics/shader/recompiler ``` Repository: KytyPS5/KytyPS5 Length of output: 2286 --- 🏁 Script executed: ```bash set -e nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemoryHelpers.cpp | sed -n '205,250p' ``` Repository: KytyPS5/KytyPS5 Length of output: 2659 --- </details> **Reject wrapped buffer-address extents.** `CalculateBufferAddress` performs the buffer additions as `uint32_t`. A valid store can wrap to a low address and pass `EmitMemoryElementInBounds`. `ComputeBufferWriteExtents` uses 64-bit arithmetic instead, so it can set `begin` and `end` to the descriptor limit and report an empty or incomplete range. The overlap check can then miss the store. The `IAdd32` and `IMul32` interval checks already reject results whose upper bound exceeds `UINT32_MAX`. Add the guard before computing the extent: <details> <summary>Suggested fix</summary> ```diff + if (offset.hi + soffset.hi + write.immediate > UINT32_MAX) { + failed[write.buffer] = 1u; + extent = {}; + continue; + } const uint64_t stride = descriptor.Stride(); ``` </details> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:9c0b64217f3bb022c7dfc8b7 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-11 18:57 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 (2)

🟠 Major · DispatchDirect records the dispatch before its bindings when the… · renderCompute.cpp:360

src/graphics/host_gpu/renderer/renderCompute.cpp:360
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

DispatchDirect records the dispatch before its bindings when the recording thread is enabled.

Line 360 calls buffer.Handle(). In threaded mode this drains the recording thread and returns the raw command buffer. CommitBindings then queues the image transitions, push constants, and descriptor pushes through buffer.Recorder().

Lines 376 and 438-442 record ShaderWriteHazardBarrier, bindPipeline, dispatch, and ShaderAccessBarrier directly on the raw handle. The implicit CommandRecorder(vk::CommandBuffer) conversion makes these calls direct. The recording thread executes the queued CommitBindings commands later.

The consequences:

  • The dispatch runs with the previous dispatch's descriptors and push constants.
  • The dispatch runs without the image layout transitions it needs.
  • If a chunk fills during CommitBindings, the recording thread writes to the same VkCommandBuffer concurrently with the GPU thread. This violates Vulkan external synchronization.

RenderContext enables the recording thread unconditionally, so every direct compute dispatch takes this path. DispatchIndirect was already moved to Recorder(). Apply the same change here.

Proposed fix
-	auto              vk_buffer        = buffer.Handle();
+	const auto        vk_buffer        = buffer.Recorder();
 	CommitBindings(buffer, vk::PipelineBindPoint::eCompute, pipeline,
 	               std::span {&descriptor_stage, 1u});
🟡 Minor · Require an enabled value for KYTY_LABELS_AFTER_GPU. · graphicsRun.cpp:68-70

src/graphics/guest_gpu/graphicsRun.cpp:68-70
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Require an enabled value for KYTY_LABELS_AFTER_GPU.

When an operator sets KYTY_LABELS_AFTER_GPU=0, this presence check still enables completion-time label publication. That changes label timing despite an explicit disabled value. Parse the value as LabelsAtCompletion does.

🧹 Nitpick comments (5)
CMakeLists.txt (1)

605-607: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Correct the exception comment.

TrackResources does not catch exceptions. Non-fatal Fail records m_failed and returns. Fatal Fail calls EXIT; the focused tests replace DbgExitHandler with a throwing hook that propagates through TrackResources. Update the comment to describe this path instead of claiming that TrackResources catches the exception.

Suggested comment update
-	# Resource tracking gives a shader up by throwing (Fail, caught in TrackResources); utils.cmake
-	# turns exceptions off for clang and GCC, while clang-cl builds have them on (/EHsc). Every
-	# target that compiles the file, the emulator included, needs them on.
+	# Resource-tracking tests use a throwing DbgExitHandler for fatal Fail calls. The exception
+	# propagates through TrackResources; utils.cmake turns exceptions off for clang and GCC,
+	# while clang-cl builds have them on (/EHsc). Every target that compiles the file needs them on.
tests/shaderCfgTests.cpp (2)

8290-8291: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Validate SPIR-V for the captured loop.

This regression stops after Structurize, but the reported failure was invalid SPIR-V. Compile the captured control-flow shape and call CheckSpirvBinaryValidates. If unrelated shader instructions prevent compilation, reduce the fixture while preserving its loop exits.


10468-10468: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Register both new opcode regressions.

main does not call TestDsAddU64 or TestFloat64AddAndCompares. Add both calls so the normal test run checks the new LDS-atomic and FP64 paths.

src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp (2)

1024-1036: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low value

Deferred pipeline failure terminates the emulator.

A worker can finish with job.result != eSuccess. In that case FinishPending runs EXIT_NOT_IMPLEMENTED on the next draw. This check is equivalent to the synchronous path, so it is not a regression. However, the job stays cached, and the deferral path is documented as a nonfatal skip path. Under ShaderFailureNonFatal(), record the failure and return nullptr so the draw is skipped. Also, a worker that is still compiling holds job->build, and Save() joins that worker, so shutdown is safe.


139-151: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

ReadShaderCode appears unused.

No caller is visible in this file. The expander reads guest memory through the lambda in ExpandShaderFunctions. If nothing calls ReadShaderCode, remove it so an unused-function warning does not appear.


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: c9d83972-ae0d-467e-83d3-192314b9a485
📥 Commits

Reviewing files that changed from the base of the PR and between 41c7b27b738ce882c93108e8b882405e33a78d8d and cc6c83e34c404e2197c4d7b7c5ddc217b8ccda9c.

📒 Files selected for processing (94)
  • CMakeLists.txt
  • src/common/CMakeLists.txt
  • src/common/cpuAffinity.cpp
  • src/common/cpuAffinity.h
  • src/common/emulatorConfig.cpp
  • src/common/emulatorConfig.h
  • src/common/threads.cpp
  • 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/graphicContext.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/streamBuffer.h
  • src/graphics/host_gpu/renderer/cache/textureCache.cpp
  • src/graphics/host_gpu/renderer/cache/textureCache.h
  • src/graphics/host_gpu/renderer/commandRecorder.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/depthRenderTarget.cpp
  • src/graphics/host_gpu/renderer/dynamicState.cpp
  • src/graphics/host_gpu/renderer/dynamicState.h
  • src/graphics/host_gpu/renderer/image/blitHelper.cpp
  • src/graphics/host_gpu/renderer/image/image.cpp
  • src/graphics/host_gpu/renderer/image/image.h
  • src/graphics/host_gpu/renderer/image/imageInfo.h
  • src/graphics/host_gpu/renderer/image/tiler.cpp
  • 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/pipeline/shaderResourceBarrier.cpp
  • src/graphics/host_gpu/renderer/pipeline/shaderResourceBarrier.h
  • src/graphics/host_gpu/renderer/pipeline/shaders.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/renderDraw.cpp
  • src/graphics/host_gpu/renderer/sync.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/backend/spirv/SpirvEmitter.cpp
  • src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.h
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterAlu.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterAluHelpers.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterFlow.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.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/spirvEmitterModule.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp
  • src/graphics/shader/recompiler/frontend/cfg/ShaderCFG.cpp
  • src/graphics/shader/recompiler/frontend/decode/ImageOps.cpp
  • src/graphics/shader/recompiler/frontend/decode/ShaderDecoder.cpp
  • src/graphics/shader/recompiler/frontend/decode/ShaderDecoder.h
  • src/graphics/shader/recompiler/frontend/translate/Attribute.cpp
  • src/graphics/shader/recompiler/frontend/translate/Integer.cpp
  • src/graphics/shader/recompiler/frontend/translate/Memory.cpp
  • src/graphics/shader/recompiler/frontend/translate/Scalar.cpp
  • src/graphics/shader/recompiler/frontend/translate/Translate.cpp
  • src/graphics/shader/recompiler/frontend/translate/Translator.h
  • src/graphics/shader/recompiler/ir/ResourceSnapshot.h
  • 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/ResourceMaterialization.h
  • src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp
  • src/graphics/shader/recompiler/ir/passes/ShaderInfoCollection.cpp
  • src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp
  • src/graphics/shader/recompiler/ir/passes/SrtWalker.h
  • src/graphics/shader/shader.cpp
  • src/graphics/shader/shader.h
  • src/kernel/eventQueue.cpp
  • src/kernel/fileSystem.cpp
  • src/kernel/fileSystem.h
  • src/kernel/memory.cpp
  • src/kernel/memory.h
  • src/libs/agc.cpp
  • src/libs/avPlayer.cpp
  • src/libs/dialog.cpp
  • src/libs/libAmpr.cpp
  • src/libs/libKernel.cpp
  • src/libs/libNet.cpp
  • src/main.cpp
  • tests/AvPlayerFileTests.cpp
  • tests/ResourceTrackingTests.cpp
  • tests/ScalarProvenanceTests.cpp
  • tests/ShaderRecompilerComputeTests.cpp
  • tests/shaderCfgTests.cpp
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/graphics/shader/recompiler/frontend/translate/Scalar.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-10-11 18:57 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/937#pullrequestreview-5484510071) · **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 (2)** > > <details> > <summary><strong>🟠 Major</strong> · <code>DispatchDirect</code> records the dispatch before its bindings when the… · <code>renderCompute.cpp:360</code></summary><blockquote> > > `src/graphics/host_gpu/renderer/renderCompute.cpp:360` > **🎯 Functional Correctness** | **🟠 Major** | **⚡ Quick win** > > **`DispatchDirect` records the dispatch before its bindings when the recording thread is enabled.** > > Line 360 calls `buffer.Handle()`. In threaded mode this drains the recording thread and returns the raw command buffer. `CommitBindings` then queues the image transitions, push constants, and descriptor pushes through `buffer.Recorder()`. > > Lines 376 and 438-442 record `ShaderWriteHazardBarrier`, `bindPipeline`, `dispatch`, and `ShaderAccessBarrier` directly on the raw handle. The implicit `CommandRecorder(vk::CommandBuffer)` conversion makes these calls direct. The recording thread executes the queued `CommitBindings` commands later. > > The consequences: > - The dispatch runs with the previous dispatch's descriptors and push constants. > - The dispatch runs without the image layout transitions it needs. > - If a chunk fills during `CommitBindings`, the recording thread writes to the same `VkCommandBuffer` concurrently with the GPU thread. This violates Vulkan external synchronization. > > `RenderContext` enables the recording thread unconditionally, so every direct compute dispatch takes this path. `DispatchIndirect` was already moved to `Recorder()`. Apply the same change here. > > <details> > <summary>Proposed fix</summary> > > ```diff > - auto vk_buffer = buffer.Handle(); > + const auto vk_buffer = buffer.Recorder(); > CommitBindings(buffer, vk::PipelineBindPoint::eCompute, pipeline, > std::span {&descriptor_stage, 1u}); > ``` > </details> > > <!-- cr-comment:v1:6394b93c908d23fd5f2da34c --> > > </blockquote></details> > <details> > <summary><strong>🟡 Minor</strong> · Require an enabled value for <code>KYTY_LABELS_AFTER_GPU</code>. · <code>graphicsRun.cpp:68-70</code></summary><blockquote> > > `src/graphics/guest_gpu/graphicsRun.cpp:68-70` > **🎯 Functional Correctness** | **🟡 Minor** | **⚡ Quick win** > > **Require an enabled value for `KYTY_LABELS_AFTER_GPU`.** > > When an operator sets `KYTY_LABELS_AFTER_GPU=0`, this presence check still enables completion-time label publication. That changes label timing despite an explicit disabled value. Parse the value as `LabelsAtCompletion` does. > > <!-- cr-comment:v1:94f6acd27b73474cf1733719 --> > > </blockquote></details> <details> <summary>🧹 Nitpick comments (5)</summary><blockquote> <details> <summary>CMakeLists.txt (1)</summary><blockquote> `605-607`: **📐 Maintainability & Code Quality** | **🔵 Trivial** | **⚡ Quick win** **Correct the exception comment.** `TrackResources` does not catch exceptions. Non-fatal `Fail` records `m_failed` and returns. Fatal `Fail` calls `EXIT`; the focused tests replace `DbgExitHandler` with a throwing hook that propagates through `TrackResources`. Update the comment to describe this path instead of claiming that `TrackResources` catches the exception. <details> <summary>Suggested comment update</summary> ```diff - # Resource tracking gives a shader up by throwing (Fail, caught in TrackResources); utils.cmake - # turns exceptions off for clang and GCC, while clang-cl builds have them on (/EHsc). Every - # target that compiles the file, the emulator included, needs them on. + # Resource-tracking tests use a throwing DbgExitHandler for fatal Fail calls. The exception + # propagates through TrackResources; utils.cmake turns exceptions off for clang and GCC, + # while clang-cl builds have them on (/EHsc). Every target that compiles the file needs them on. ``` </details> <!-- cr-comment:v1:fb51223d880eee44c73e47cc --> </blockquote></details> <details> <summary>tests/shaderCfgTests.cpp (2)</summary><blockquote> `8290-8291`: **📐 Maintainability & Code Quality** | **🔵 Trivial** | **⚡ Quick win** **Validate SPIR-V for the captured loop.** This regression stops after `Structurize`, but the reported failure was invalid SPIR-V. Compile the captured control-flow shape and call `CheckSpirvBinaryValidates`. If unrelated shader instructions prevent compilation, reduce the fixture while preserving its loop exits. <!-- cr-comment:v1:5af153221afdc989c7c95da4 --> --- `10468-10468`: **📐 Maintainability & Code Quality** | **🔵 Trivial** | **⚡ Quick win** **Register both new opcode regressions.** `main` does not call `TestDsAddU64` or `TestFloat64AddAndCompares`. Add both calls so the normal test run checks the new LDS-atomic and FP64 paths. <!-- cr-comment:v1:5508ddd8d945f2c0bf9e22c3 --> </blockquote></details> <details> <summary>src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp (2)</summary><blockquote> `1024-1036`: **🩺 Stability & Availability** | **🔵 Trivial** | **💤 Low value** **Deferred pipeline failure terminates the emulator.** A worker can finish with `job.result != eSuccess`. In that case `FinishPending` runs `EXIT_NOT_IMPLEMENTED` on the next draw. This check is equivalent to the synchronous path, so it is not a regression. However, the job stays cached, and the deferral path is documented as a nonfatal skip path. Under `ShaderFailureNonFatal()`, record the failure and return `nullptr` so the draw is skipped. Also, a worker that is still compiling holds `job->build`, and `Save()` joins that worker, so shutdown is safe. <!-- cr-comment:v1:6c9ccbd533d671e11f397f20 --> --- `139-151`: **📐 Maintainability & Code Quality** | **🔵 Trivial** | **💤 Low value** **`ReadShaderCode` appears unused.** No caller is visible in this file. The expander reads guest memory through the lambda in `ExpandShaderFunctions`. If nothing calls `ReadShaderCode`, remove it so an unused-function warning does not appear. <!-- cr-comment:v1:550eb7cd2347f2f8088e90f1 --> </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**: `c9d83972-ae0d-467e-83d3-192314b9a485` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 41c7b27b738ce882c93108e8b882405e33a78d8d and cc6c83e34c404e2197c4d7b7c5ddc217b8ccda9c. </details> <details> <summary>📒 Files selected for processing (94)</summary> * `CMakeLists.txt` * `src/common/CMakeLists.txt` * `src/common/cpuAffinity.cpp` * `src/common/cpuAffinity.h` * `src/common/emulatorConfig.cpp` * `src/common/emulatorConfig.h` * `src/common/threads.cpp` * `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/graphicContext.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/streamBuffer.h` * `src/graphics/host_gpu/renderer/cache/textureCache.cpp` * `src/graphics/host_gpu/renderer/cache/textureCache.h` * `src/graphics/host_gpu/renderer/commandRecorder.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/depthRenderTarget.cpp` * `src/graphics/host_gpu/renderer/dynamicState.cpp` * `src/graphics/host_gpu/renderer/dynamicState.h` * `src/graphics/host_gpu/renderer/image/blitHelper.cpp` * `src/graphics/host_gpu/renderer/image/image.cpp` * `src/graphics/host_gpu/renderer/image/image.h` * `src/graphics/host_gpu/renderer/image/imageInfo.h` * `src/graphics/host_gpu/renderer/image/tiler.cpp` * `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/pipeline/shaderResourceBarrier.cpp` * `src/graphics/host_gpu/renderer/pipeline/shaderResourceBarrier.h` * `src/graphics/host_gpu/renderer/pipeline/shaders.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/renderDraw.cpp` * `src/graphics/host_gpu/renderer/sync.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/backend/spirv/SpirvEmitter.cpp` * `src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.h` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterAlu.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterAluHelpers.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterFlow.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.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/spirvEmitterModule.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp` * `src/graphics/shader/recompiler/frontend/cfg/ShaderCFG.cpp` * `src/graphics/shader/recompiler/frontend/decode/ImageOps.cpp` * `src/graphics/shader/recompiler/frontend/decode/ShaderDecoder.cpp` * `src/graphics/shader/recompiler/frontend/decode/ShaderDecoder.h` * `src/graphics/shader/recompiler/frontend/translate/Attribute.cpp` * `src/graphics/shader/recompiler/frontend/translate/Integer.cpp` * `src/graphics/shader/recompiler/frontend/translate/Memory.cpp` * `src/graphics/shader/recompiler/frontend/translate/Scalar.cpp` * `src/graphics/shader/recompiler/frontend/translate/Translate.cpp` * `src/graphics/shader/recompiler/frontend/translate/Translator.h` * `src/graphics/shader/recompiler/ir/ResourceSnapshot.h` * `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/ResourceMaterialization.h` * `src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp` * `src/graphics/shader/recompiler/ir/passes/ShaderInfoCollection.cpp` * `src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp` * `src/graphics/shader/recompiler/ir/passes/SrtWalker.h` * `src/graphics/shader/shader.cpp` * `src/graphics/shader/shader.h` * `src/kernel/eventQueue.cpp` * `src/kernel/fileSystem.cpp` * `src/kernel/fileSystem.h` * `src/kernel/memory.cpp` * `src/kernel/memory.h` * `src/libs/agc.cpp` * `src/libs/avPlayer.cpp` * `src/libs/dialog.cpp` * `src/libs/libAmpr.cpp` * `src/libs/libKernel.cpp` * `src/libs/libNet.cpp` * `src/main.cpp` * `tests/AvPlayerFileTests.cpp` * `tests/ResourceTrackingTests.cpp` * `tests/ScalarProvenanceTests.cpp` * `tests/ShaderRecompilerComputeTests.cpp` * `tests/shaderCfgTests.cpp` </details> <details> <summary>🚧 Files skipped from review as they are similar to previous changes (1)</summary> * src/graphics/shader/recompiler/frontend/translate/Scalar.cpp </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=57900f2a-b963-4e3a-b77b-b674ccb05ae1 attempt=d60ac7d7-5c77-4bd6-8f74-2262dbb7df00 batch=1/1 -->
@ -1143,0 +1270,4 @@
value, sizeof(value));
} else {
std::memcpy(dst, &value, sizeof(value));
}
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-11 19:31 UTC · original

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
rg -nP -C8 '\bWriteAtEndOfPipe(WithWriteBack|WithInterrupt|WithInterruptWriteBack)?64\s*\(' --type=cpp -g '!**/graphicsRun.cpp'

Repository: KytyPS5/KytyPS5

Length of output: 16202


Skip the Sync data write when labels are published at completion.

Sync::WriteAtEndOfPipe64 and its writeback variants write the supplied packet value to dst. When LabelsAfterGpu() and clock_value are both true, PublishLabelAtCompletion schedules the completion-time timestamp, but the Sync write can overwrite that timestamp with the raw packet payload. Ensure these paths signal or interrupt without performing a second data write.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-11 19:31 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/937#discussion_r4242913422) **🎯 Functional Correctness** | **🟡 Minor** | **⚡ Quick win** <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash #!/bin/bash rg -nP -C8 '\bWriteAtEndOfPipe(WithWriteBack|WithInterrupt|WithInterruptWriteBack)?64\s*\(' --type=cpp -g '!**/graphicsRun.cpp' ``` Repository: KytyPS5/KytyPS5 Length of output: 16202 --- </details> **Skip the Sync data write when labels are published at completion.** `Sync::WriteAtEndOfPipe64` and its writeback variants write the supplied packet value to `dst`. When `LabelsAfterGpu()` and `clock_value` are both true, `PublishLabelAtCompletion` schedules the completion-time timestamp, but the Sync write can overwrite that timestamp with the raw packet payload. Ensure these paths signal or interrupt without performing a second data write. <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:bf3a75c4b012c0ac5c0b64bd --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-11 19:31 UTC · original
On src/graphics/host_gpu/renderer/renderContext.cpp line 23 (outdated):

@@ -15,8 +15,12 @@ RenderContext::RenderContext(GraphicContext& graphics)
       m_descriptor_heap(graphics, m_command_scheduler.GetMasterSemaphore()),
       m_pipeline_cache(graphics), m_sampler_cache(graphics),
       m_buffer_cache(graphics, m_command_scheduler, m_page_manager, m_texture_cache),
-      m_texture_cache(graphics, m_command_scheduler, m_page_manager, m_buffer_cache) {
+      m_texture_cache(graphics, m_command_scheduler, m_page_manager, m_buffer_cache),
+      m_bindless_table(graphics, m_command_scheduler) {
 	EXIT_NOT_IMPLEMENTED(!Common::Thread::IsMainThread());
+	m_texture_cache.on_bindless_unregister = [this](ImageId id) {
+		m_bindless_table.OnImageUnregistered(id);
+	};

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Clear on_bindless_unregister before the members are destroyed. Otherwise shutdown can crash.

m_bindless_table is declared after m_texture_cache, so it is destroyed first. ~TextureCache then calls UnregisterImage for every registered image. For an image with bindless_pinned set, UnregisterImage invokes the callback. The callback calls m_bindless_table.OnImageUnregistered on the destroyed table. That call reads the freed m_image_refs. It then calls WriteSlot on the destroyed set and pool, and SetTranslation dereferences the reset m_translation.

This happens at every shutdown with --bindless after at least one key has resolved.

Proposed fix
 RenderContext::~RenderContext() {
 	ShutdownGpu();
 	m_command_scheduler.Shutdown();
+	// m_bindless_table is destroyed before m_texture_cache.
+	m_texture_cache.on_bindless_unregister = nullptr;
 }
**@⁠coderabbitai[bot]** on GitHub · 2026-10-11 19:31 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/937#discussion_r4242913424) On `src/graphics/host_gpu/renderer/renderContext.cpp` line 23 (outdated): ```diff @@ -15,8 +15,12 @@ RenderContext::RenderContext(GraphicContext& graphics) m_descriptor_heap(graphics, m_command_scheduler.GetMasterSemaphore()), m_pipeline_cache(graphics), m_sampler_cache(graphics), m_buffer_cache(graphics, m_command_scheduler, m_page_manager, m_texture_cache), - m_texture_cache(graphics, m_command_scheduler, m_page_manager, m_buffer_cache) { + m_texture_cache(graphics, m_command_scheduler, m_page_manager, m_buffer_cache), + m_bindless_table(graphics, m_command_scheduler) { EXIT_NOT_IMPLEMENTED(!Common::Thread::IsMainThread()); + m_texture_cache.on_bindless_unregister = [this](ImageId id) { + m_bindless_table.OnImageUnregistered(id); + }; ``` **🩺 Stability & Availability** | **🟠 Major** | **⚡ Quick win** **Clear `on_bindless_unregister` before the members are destroyed. Otherwise shutdown can crash.** `m_bindless_table` is declared after `m_texture_cache`, so it is destroyed first. `~TextureCache` then calls `UnregisterImage` for every registered image. For an image with `bindless_pinned` set, `UnregisterImage` invokes the callback. The callback calls `m_bindless_table.OnImageUnregistered` on the destroyed table. That call reads the freed `m_image_refs`. It then calls `WriteSlot` on the destroyed set and pool, and `SetTranslation` dereferences the reset `m_translation`. This happens at every shutdown with `--bindless` after at least one key has resolved. <details> <summary>Proposed fix</summary> ```diff RenderContext::~RenderContext() { ShutdownGpu(); m_command_scheduler.Shutdown(); + // m_bindless_table is destroyed before m_texture_cache. + m_texture_cache.on_bindless_unregister = nullptr; } ``` </details> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:992dc1f422dd58976105c681 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-11 19:31 UTC · original
On src/graphics/host_gpu/renderer/renderContext.cpp line 149 (outdated):

@@ -119,10 +129,24 @@ void RenderContext::UnmapMemory(uint64_t vaddr, uint64_t size) {
 }
 
 void RenderContext::PrepareBda() {
-	std::shared_lock lock(m_mapped_ranges_mutex);
-	m_mapped_ranges.ForEach([this](uint64_t start, uint64_t end) {
-		m_buffer_cache.SynchronizeBuffersInRange(start, end - start);
-	});
+	const auto epoch = g_cpu_dirty_epoch.load(std::memory_order_acquire);
+	if (epoch != m_bda_synced_epoch) {
+		const auto submission = g_guest_submission_seq.load(std::memory_order_relaxed);
+		if (submission == m_bda_synced_submission) {
+			m_fault_process_pending = true;
+			return;
+		}
+		m_bda_synced_submission = submission;
+	}
+	if (epoch != m_bda_synced_epoch) {
+		// The guest writes somewhere nearly all the time, so the epoch moves between most
+		// dispatches; walk only the regions holding CPU-dirty pages, not every buffer.
+		std::shared_lock lock(m_mapped_ranges_mutex);
+		m_mapped_ranges.ForEach([this](uint64_t start, uint64_t end) {
+			m_buffer_cache.SynchronizeCpuDirtyBuffersInRange(start, end - start);
+		});
+		m_bda_synced_epoch = epoch;
+	}

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

PrepareBda skips BDA synchronization after writes that the command processor makes in the current submission.

When only g_cpu_dirty_epoch has advanced within a submission, the function returns without synchronizing. Some writes in a submission are ordered before later dispatches by the command processor itself:

  • BufferCache::CopyBuffer (CPU memcpy path)
  • FillBuffer (std::fill path)
  • the WriteData fallback (memcpy)

These writes take write faults on tracked pages. The faults mark the pages CPU-dirty and advance the epoch. A later uses_dma dispatch in the same submission then reads the stale device copy through BDA. Normal bindings are not affected, because ObtainBuffer uploads CPU-dirty ranges.

This is a different trigger from the Register case in the earlier review comment. Do not skip synchronization when the epoch change came from the GPU thread. For example, keep a separate counter that ChangeState<Cpu, true> advances when GuestGpu::IsGpuThread() is true. Then require synchronization whenever that counter has changed.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-11 19:31 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/937#discussion_r4242913426) On `src/graphics/host_gpu/renderer/renderContext.cpp` line 149 (outdated): ```diff @@ -119,10 +129,24 @@ void RenderContext::UnmapMemory(uint64_t vaddr, uint64_t size) { } void RenderContext::PrepareBda() { - std::shared_lock lock(m_mapped_ranges_mutex); - m_mapped_ranges.ForEach([this](uint64_t start, uint64_t end) { - m_buffer_cache.SynchronizeBuffersInRange(start, end - start); - }); + const auto epoch = g_cpu_dirty_epoch.load(std::memory_order_acquire); + if (epoch != m_bda_synced_epoch) { + const auto submission = g_guest_submission_seq.load(std::memory_order_relaxed); + if (submission == m_bda_synced_submission) { + m_fault_process_pending = true; + return; + } + m_bda_synced_submission = submission; + } + if (epoch != m_bda_synced_epoch) { + // The guest writes somewhere nearly all the time, so the epoch moves between most + // dispatches; walk only the regions holding CPU-dirty pages, not every buffer. + std::shared_lock lock(m_mapped_ranges_mutex); + m_mapped_ranges.ForEach([this](uint64_t start, uint64_t end) { + m_buffer_cache.SynchronizeCpuDirtyBuffersInRange(start, end - start); + }); + m_bda_synced_epoch = epoch; + } ``` **🗄️ Data Integrity & Integration** | **🟠 Major** | **🏗️ Heavy lift** **`PrepareBda` skips BDA synchronization after writes that the command processor makes in the current submission.** When only `g_cpu_dirty_epoch` has advanced within a submission, the function returns without synchronizing. Some writes in a submission are ordered before later dispatches by the command processor itself: - `BufferCache::CopyBuffer` (CPU `memcpy` path) - `FillBuffer` (`std::fill` path) - the `WriteData` fallback (`memcpy`) These writes take write faults on tracked pages. The faults mark the pages CPU-dirty and advance the epoch. A later `uses_dma` dispatch in the same submission then reads the stale device copy through BDA. Normal bindings are not affected, because `ObtainBuffer` uploads CPU-dirty ranges. This is a different trigger from the `Register` case in the earlier review comment. Do not skip synchronization when the epoch change came from the GPU thread. For example, keep a separate counter that `ChangeState<Cpu, true>` advances when `GuestGpu::IsGpuThread()` is true. Then require synchronization whenever that counter has changed. <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:faf393f0fdd83d472700f277 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-11 19:31 UTC · original
On src/graphics/presentation/window/vulkanWindow.cpp line 533 (outdated):

@@ -494,6 +524,16 @@ static vk::Device VulkanCreateDevice(GraphicContext& graphics,
 	}
 	physical_device.getProperties2(&properties2);
 
+	graphics.bindless_max_sampled_images =
+	    graphics.bindless_enabled ? properties12.maxDescriptorSetUpdateAfterBindSampledImages : 0u;
+	graphics.bindless_max_samplers =
+	    graphics.bindless_enabled
+	        ? std::min(properties12.maxDescriptorSetUpdateAfterBindSamplers,
+	                   properties12.maxPerStageDescriptorUpdateAfterBindSamplers)
+	        : 0u;

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Also limit the bindless sampled-image count by the per-stage update-after-bind limit.

BindlessTable creates four arrays of m_images_per_array = min(16384, bindless_max_sampled_images / 4) sampled images. The arrays use eAll stages, and every bindless pipeline layout includes them. maxPerStageDescriptorUpdateAfterBindSampledImages limits the total sampled images in one stage, including the images in set 0. This code checks only maxDescriptorSetUpdateAfterBindSampledImages. On a device with a smaller per-stage limit, the pipeline layout exceeds the limit. The sampler limit on the next lines already takes the minimum of the two limits.

Proposed fix
--- "a/src/graphics/presentation/window/vulkanWindow.cpp"
+++ "b/src/graphics/presentation/window/vulkanWindow.cpp"
@@ -524,8 +524,11 @@
 	}
 	physical_device.getProperties2(&properties2);
 
 	graphics.bindless_max_sampled_images =
-	    graphics.bindless_enabled ? properties12.maxDescriptorSetUpdateAfterBindSampledImages : 0u;
+	    graphics.bindless_enabled
+	        ? std::min(properties12.maxDescriptorSetUpdateAfterBindSampledImages,
+	                   properties12.maxPerStageDescriptorUpdateAfterBindSampledImages)
+	        : 0u;
 	graphics.bindless_max_samplers =
 	    graphics.bindless_enabled
 	        ? std::min(properties12.maxDescriptorSetUpdateAfterBindSamplers,

Reserve headroom for the set 0 images too. For example, subtract a fixed per-stage budget before dividing by ImageArrays.

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

	graphics.bindless_max_sampled_images =
	    graphics.bindless_enabled
	        ? std::min(properties12.maxDescriptorSetUpdateAfterBindSampledImages,
	                   properties12.maxPerStageDescriptorUpdateAfterBindSampledImages)
	        : 0u;
	graphics.bindless_max_samplers =
	    graphics.bindless_enabled
	        ? std::min(properties12.maxDescriptorSetUpdateAfterBindSamplers,
	                   properties12.maxPerStageDescriptorUpdateAfterBindSamplers)
	        : 0u;
**@⁠coderabbitai[bot]** on GitHub · 2026-10-11 19:31 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/937#discussion_r4242913428) On `src/graphics/presentation/window/vulkanWindow.cpp` line 533 (outdated): ```diff @@ -494,6 +524,16 @@ static vk::Device VulkanCreateDevice(GraphicContext& graphics, } physical_device.getProperties2(&properties2); + graphics.bindless_max_sampled_images = + graphics.bindless_enabled ? properties12.maxDescriptorSetUpdateAfterBindSampledImages : 0u; + graphics.bindless_max_samplers = + graphics.bindless_enabled + ? std::min(properties12.maxDescriptorSetUpdateAfterBindSamplers, + properties12.maxPerStageDescriptorUpdateAfterBindSamplers) + : 0u; ``` **🩺 Stability & Availability** | **🟡 Minor** | **⚡ Quick win** **Also limit the bindless sampled-image count by the per-stage update-after-bind limit.** `BindlessTable` creates four arrays of `m_images_per_array = min(16384, bindless_max_sampled_images / 4)` sampled images. The arrays use `eAll` stages, and every bindless pipeline layout includes them. `maxPerStageDescriptorUpdateAfterBindSampledImages` limits the total sampled images in one stage, including the images in set 0. This code checks only `maxDescriptorSetUpdateAfterBindSampledImages`. On a device with a smaller per-stage limit, the pipeline layout exceeds the limit. The sampler limit on the next lines already takes the minimum of the two limits. <details> <summary>Proposed fix</summary> ```diff --- "a/src/graphics/presentation/window/vulkanWindow.cpp" +++ "b/src/graphics/presentation/window/vulkanWindow.cpp" @@ -524,8 +524,11 @@ } physical_device.getProperties2(&properties2); graphics.bindless_max_sampled_images = - graphics.bindless_enabled ? properties12.maxDescriptorSetUpdateAfterBindSampledImages : 0u; + graphics.bindless_enabled + ? std::min(properties12.maxDescriptorSetUpdateAfterBindSampledImages, + properties12.maxPerStageDescriptorUpdateAfterBindSampledImages) + : 0u; graphics.bindless_max_samplers = graphics.bindless_enabled ? std::min(properties12.maxDescriptorSetUpdateAfterBindSamplers, ``` </details> Reserve headroom for the set 0 images too. For example, subtract a fixed per-stage budget before dividing by `ImageArrays`. <!-- 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 graphics.bindless_max_sampled_images = graphics.bindless_enabled ? std::min(properties12.maxDescriptorSetUpdateAfterBindSampledImages, properties12.maxPerStageDescriptorUpdateAfterBindSampledImages) : 0u; graphics.bindless_max_samplers = graphics.bindless_enabled ? std::min(properties12.maxDescriptorSetUpdateAfterBindSamplers, properties12.maxPerStageDescriptorUpdateAfterBindSamplers) : 0u; ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:8a4e8d522f43c9dbdc4b3e2f --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-11 19:31 UTC · original
On src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp line 1249 (outdated):

@@ -800,75 +915,351 @@ uint32_t LoadIndirectBuffer(ValueEmitContext& ctx, const IR::Inst& inst, uint32_
 	const auto nonzero = [&](uint32_t value) {
 		return Binary(state, spv::OpINotEqual, TypeBool(state), value, ConstantU32(state, 0));
 	};
+	const auto format = memory.typed
+	                        ? ConstantU32(state, static_cast<uint32_t>(Format::DecodeTBufferFormat(
+	                                                 memory.data_format, memory.number_format)))
+	                        : field(word3, 12, 7);
+	const auto info   = DecodeDynamicBufferFormat(state, format);
+	// Zero is an unbound format. Other unknown encodings must not silently
+	// turn an unsupported descriptor into a successful zero-valued load.
+	EmitIfCondition(state,
+	                AndCondition(state, nonzero(format),
+	                             Unary(state, spv::OpLogicalNot, TypeBool(state), info.valid)),
+	                [&]() {
+		                EmitShaderTrap(state, ConstantU32(state, inst.Flags<IR::MemoryFlags>().pc),
+		                               ConstantU32(state, 0x100));
+	                });
+	const auto count        = field(info.layout, 0, 3);
+	const auto packed       = nonzero(field(info.layout, 8, 1));
+	const auto stride       = field(word1, 16, 14);
+	const auto swizzle      = AndCondition(state, nonzero(stride), nonzero(field(word1, 31, 1)));
+	const auto index_stride = field(word3, 21, 2);
+	const auto index        = Binary(state, spv::OpIAdd, TypeU32(state), ctx.Arg(inst, 1),
+	                                 Select(state, TypeU32(state), nonzero(field(word3, 23, 1)),
+	                                        BufferLane(state), ConstantU32(state, 0)));
+	const auto soffset      = ctx.Arg(inst, 3);
+	const auto base    = DeviceAddressFromWords(state, ctx.Arg(handle, 0), field(word1, 0, 16));
+	const auto address = CalculateBufferAddress(state, index, ctx.Arg(inst, 2), soffset,
+	                                            memory.offset, stride, swizzle, index_stride);
+	struct Component {
+		uint32_t selector, from_memory, bits, bit_shift, byte_offset, load_bits;
+	};
+	std::array<Component, 4> plans {};
+	auto                     payload = ConstantU32(state, 0);
+	for (uint32_t output = 0; output < components; ++output) {
+		auto& plan       = plans[output];
+		plan.selector    = memory.typed
+		                       ? Select(state, TypeU32(state),
+		                                Binary(state, spv::OpULessThan, TypeBool(state),
+		                                       ConstantU32(state, output), count),
+		                                ConstantU32(state, output + 4u), ConstantU32(state, 0))
+		                       : field(word3, output * 3u, 3);
+		plan.from_memory = Binary(state, spv::OpUGreaterThanEqual, TypeBool(state), plan.selector,
+		                          ConstantU32(state, 4));
+		const auto reserved =
+		    AndCondition(state, info.valid,
+		                 AndCondition(state,
+		                              Binary(state, spv::OpUGreaterThan, TypeBool(state),
+		                                     plan.selector, ConstantU32(state, 1)),
+		                              Binary(state, spv::OpULessThan, TypeBool(state),
+		                                     plan.selector, ConstantU32(state, 4))));
+		EmitIfCondition(state, reserved, [&]() {
+			EmitShaderTrap(state, ConstantU32(state, inst.Flags<IR::MemoryFlags>().pc),
+			               ConstantU32(state, 0x101));
+		});
+		const auto component =
+		    Binary(state, spv::OpUMod, TypeU32(state),
+		           Binary(state, spv::OpISub, TypeU32(state), plan.selector, ConstantU32(state, 4)),
+		           count);
+		plan.bits = EmitBitFieldUExtract(
+		    state, info.widths,
+		    Binary(state, spv::OpIMul, TypeU32(state), component, ConstantU32(state, 6)),
+		    ConstantU32(state, 6));
+		const auto bit_offset = EmitBitFieldUExtract(
+		    state, info.offsets,
+		    Binary(state, spv::OpIMul, TypeU32(state), component, ConstantU32(state, 7)),
+		    ConstantU32(state, 7));
+		plan.byte_offset = Select(state, TypeU32(state), packed, ConstantU32(state, 0),
+		                          Binary(state, spv::OpShiftRightLogical, TypeU32(state),
+		                                 bit_offset, ConstantU32(state, 3)));
+		plan.bit_shift   = Select(state, TypeU32(state), packed, bit_offset, ConstantU32(state, 0));
+		plan.load_bits   = Select(state, TypeU32(state), packed, ConstantU32(state, 32), plan.bits);
+		const auto end   = Binary(state, spv::OpIAdd, TypeU32(state), plan.byte_offset,
+		                          Binary(state, spv::OpShiftRightLogical, TypeU32(state),
+		                                 plan.load_bits, ConstantU32(state, 3)));
+		const auto needed =
+		    Select(state, TypeU32(state), plan.from_memory, end, ConstantU32(state, 0));
+		payload = Select(state, TypeU32(state),
+		                 Binary(state, spv::OpUGreaterThan, TypeBool(state), needed, payload),
+		                 needed, payload);
+	}
+	const auto has_payload = [&](uint32_t size) {
+		return AndCondition(state,
+		                    Binary(state, spv::OpUGreaterThanEqual, TypeBool(state), size, payload),
+		                    Binary(state, spv::OpULessThanEqual, TypeBool(state), address.offset,
+		                           Binary(state, spv::OpISub, TypeU32(state), size, payload)));
+	};
+	const auto index_bound = Binary(state, spv::OpULessThan, TypeBool(state), index, records);
+	const auto structured =
+	    AndCondition(state, index_bound,
+	                 Binary(state, spv::OpULessThan, TypeBool(state), address.offset, stride));
+	const auto remaining = Binary(state, spv::OpISub, TypeU32(state), records, soffset);
+	const auto raw       = AndCondition(
+	    state, Binary(state, spv::OpULessThanEqual, TypeBool(state), soffset, records),
+	    Select(state, TypeBool(state), swizzle,
+	           AndCondition(state,
+	                        Binary(state, spv::OpULessThan, TypeBool(state), index, remaining),
+	                        has_payload(stride)),
+	           has_payload(remaining)));
+	const auto mode = field(word3, 28, 2);
+	auto bound = Select(state, TypeBool(state),
+	                    Binary(state, spv::OpIEqual, TypeBool(state), mode, ConstantU32(state, 0)),
+	                    structured, index_bound);
+	bound =
+	    Select(state, TypeBool(state),
+	           Binary(state, spv::OpULessThan, TypeBool(state), mode, ConstantU32(state, 2)), bound,
+	           Select(state, TypeBool(state),
+	                  Binary(state, spv::OpIEqual, TypeBool(state), mode, ConstantU32(state, 2)),
+	                  nonzero(records), raw));
+	bound = AndCondition(state, info.valid, bound);
+	const auto integer =
+	    Binary(state, spv::OpLogicalOr, TypeBool(state),
+	           Binary(state, spv::OpIEqual, TypeBool(state), info.type,
+	                  ConstantU32(state, static_cast<uint32_t>(Format::ComponentType::Uint))),
+	           Binary(state, spv::OpIEqual, TypeBool(state), info.type,
+	                  ConstantU32(state, static_cast<uint32_t>(Format::ComponentType::Sint))));
+	const auto              one = Select(state, TypeU32(state), integer, ConstantU32(state, 1),
+	                                     ConstantU32(state, 0x3f800000));
+	std::array<uint32_t, 4> values {};
+	for (uint32_t output = 0; output < components; ++output) {
+		const auto& plan              = plans[output];
+		const auto  component_address = CalculateBufferAddress(
+		    state, index,
+		    Binary(state, spv::OpIAdd, TypeU32(state), ctx.Arg(inst, 2), plan.byte_offset), soffset,
+		    memory.offset, stride, swizzle, index_stride);
+		const auto guest =
+		    Binary(state, spv::OpIAdd, TypeScalarU64(state), base,
+		           Unary(state, spv::OpUConvert, TypeScalarU64(state), component_address.byte));
+		const auto loaded =
+		    EmitValueOrZeroIfCondition(state, AndCondition(state, bound, plan.from_memory), [&]() {
+			    return EmitValueOrDefaultIfCondition(
+			        state,
+			        Binary(state, spv::OpUGreaterThan, TypeBool(state), plan.load_bits,
+			               ConstantU32(state, 16)),
+			        TypeU32(state), ConstantU32(state, 0),
+			        [&]() { return LoadBda(ctx, guest, ConstantBool(state, true), 32u); });
+		    });
+		// Subword accesses must not fetch a second page merely because the
+		// following bytes belong to a different buffer or an unmapped allocation.
+		const auto subword = EmitValueOrZeroIfCondition(
+		    state,
+		    AndCondition(state, AndCondition(state, bound, plan.from_memory),
+		                 Binary(state, spv::OpULessThanEqual, TypeBool(state), plan.load_bits,
+		                        ConstantU32(state, 16))),
+		    [&]() {
+			    const auto wide = Binary(state, spv::OpIEqual, TypeBool(state), plan.load_bits,
+			                             ConstantU32(state, 16));
+			    const auto half = LoadBda(ctx, guest, wide, 16u);
+			    const auto byte =
+			        LoadBda(ctx, guest, Unary(state, spv::OpLogicalNot, TypeBool(state), wide), 8u);
+			    return Select(state, TypeU32(state), wide, half, byte);
+		    });
+		const auto data      = Binary(state, spv::OpBitwiseOr, TypeU32(state), loaded, subword);
+		const auto extracted = EmitBitFieldUExtract(state, data, plan.bit_shift, plan.bits);
+		const auto converted =
+		    NormalizeDynamicBufferComponent(state, extracted, plan.bits, info.type);
+		const auto constant_one = AndCondition(
+		    state, info.valid,
+		    Binary(state, spv::OpIEqual, TypeBool(state), plan.selector, ConstantU32(state, 1)));
+		values[output] = Select(
+		    state, TypeU32(state), constant_one, one,
+		    Select(state, TypeU32(state), plan.from_memory, converted, ConstantU32(state, 0)));
+	}
+	return components == 1u ? values[0] : ConstructU32Composite(state, components, values);
+}
+
+uint32_t LoadIndirectScalarBuffer(ValueEmitContext& ctx, const IR::Inst& inst) {
+	auto&       state  = ctx.state;
+	const auto& handle = *inst.Arg(0).ResolveInstruction();
+	const auto  word1  = ctx.Arg(handle, 1);
+	const auto  high =
+	    EmitBitFieldUExtract(state, word1, ConstantU32(state, 0), ConstantU32(state, 16));
+	const auto stride =
+	    EmitBitFieldUExtract(state, word1, ConstantU32(state, 16), ConstantU32(state, 14));
+	const auto records = Unary(state, spv::OpUConvert, TypeScalarU64(state), ctx.Arg(handle, 2));
+	const auto size    = Select(
+	    state, TypeScalarU64(state),
+	    Binary(state, spv::OpIEqual, TypeBool(state), stride, ConstantU32(state, 0)), records,
+	    Binary(state, spv::OpIMul, TypeScalarU64(state), records,
+	           Unary(state, spv::OpUConvert, TypeScalarU64(state), stride)));
+	// SMEM ignores the vector format, swizzle, and OOB_SELECT fields. Match
+	// scalar-buffer addressing: aligned base plus aligned byte offset, with
+	// stride used only to determine the descriptor's byte extent.
+	const auto low    = Binary(state, spv::OpBitwiseAnd, TypeU32(state), ctx.Arg(handle, 0),
+	                           ConstantU32(state, ~3u));
+	const auto offset = Binary(state, spv::OpIAdd, TypeU32(state), ctx.Arg(inst, 1),
+	                           ConstantU32(state, ctx.Memory(inst).offset));
+	const auto aligned =
+	    Binary(state, spv::OpBitwiseAnd, TypeU32(state), offset, ConstantU32(state, ~3u));
+	const auto relative = Unary(state, spv::OpUConvert, TypeScalarU64(state), aligned);
+	const auto end =
+	    Binary(state, spv::OpIAdd, TypeScalarU64(state), relative, ConstantDeviceAddress(state, 4));
+	const auto in_bounds = Binary(state, spv::OpULessThanEqual, TypeBool(state), end, size);
+	const auto address   = Binary(state, spv::OpIAdd, TypeScalarU64(state),
+	                              DeviceAddressFromWords(state, low, high), relative);
+	return LoadBda(ctx, address, in_bounds, 32u);
+}
+
+// The hardware's range check of a raw DWORD buffer access, from the V# words the shader holds.
+struct IndirectBufferAccess {
+	uint32_t base                = 0;
+	uint32_t stride              = 0;
+	uint32_t swizzle             = 0;
+	uint32_t index_stride        = 0;
+	uint32_t index               = 0;
+	uint32_t soffset             = 0;
+	uint32_t valid_format        = 0;
+	uint32_t mode                = 0;
+	uint32_t records             = 0;
+	uint32_t index_in_bounds     = 0;
+	uint32_t scalar_in_bounds    = 0;
+	uint32_t raw_records         = 0;
+	uint32_t raw_index_in_bounds = 0;
+};
+
+IndirectBufferAccess PrepareIndirectBufferAccess(ValueEmitContext& ctx, const IR::Inst& inst) {
+	auto&       state  = ctx.state;
+	const auto& handle = *inst.Arg(0).ResolveInstruction();
+	const auto  word1  = ctx.Arg(handle, 1);
+	const auto  word3  = ctx.Arg(handle, 3);
+	const auto  field  = [&](uint32_t word, uint32_t first, uint32_t count) {
+		return EmitBitFieldUExtract(state, word, ConstantU32(state, first),
+		                            ConstantU32(state, count));
+	};
+	const auto nonzero = [&](uint32_t value) {
+		return Binary(state, spv::OpINotEqual, TypeBool(state), value, ConstantU32(state, 0));
+	};
+	IndirectBufferAccess access;
+	access.records      = ctx.Arg(handle, 2);
+	access.stride       = field(word1, 16, 14);
+	access.swizzle      = AndCondition(state, nonzero(access.stride), nonzero(field(word1, 31, 1)));
+	access.index_stride = field(word3, 21, 2);
+	const auto add_tid  = nonzero(field(word3, 23, 1));
+	access.index =
+	    Binary(state, spv::OpIAdd, TypeU32(state), ctx.Arg(inst, 1),
+	           Select(state, TypeU32(state), add_tid, BufferLane(state), ConstantU32(state, 0)));
+	access.soffset      = ctx.Arg(inst, 3);
+	access.valid_format = nonzero(field(word3, 12, 7));
+	access.mode         = field(word3, 28, 2);
+	access.index_in_bounds =
+	    Binary(state, spv::OpULessThan, TypeBool(state), access.index, access.records);
+	access.scalar_in_bounds =
+	    Binary(state, spv::OpULessThanEqual, TypeBool(state), access.soffset, access.records);
+	access.raw_records =
+	    Binary(state, spv::OpISub, TypeU32(state), access.records, access.soffset);
+	access.raw_index_in_bounds =
+	    Binary(state, spv::OpULessThan, TypeBool(state), access.index, access.raw_records);
+	return access;
+}
+
+// The byte address (relative to the V# base) of one DWORD of the access, and whether the
+// hardware performs it.
+std::pair<uint32_t, uint32_t> IndirectBufferComponent(ValueEmitContext& ctx, const IR::Inst& inst,
+                                                      const IndirectBufferAccess& access,
+                                                      uint32_t component) {
+	auto&      state   = ctx.state;
+	const auto nonzero = [&](uint32_t value) {
+		return Binary(state, spv::OpINotEqual, TypeBool(state), value, ConstantU32(state, 0));
+	};
 	const auto has_dword = [&](uint32_t offset, uint32_t size) {
 		return AndCondition(
 		    state,
 		    Binary(state, spv::OpUGreaterThanEqual, TypeBool(state), size, ConstantU32(state, 4)),
 		    Binary(state, spv::OpULessThanEqual, TypeBool(state), offset,
 		           Binary(state, spv::OpISub, TypeU32(state), size, ConstantU32(state, 4))));
 	};
-	const auto stride       = field(word1, 16, 14);
-	const auto swizzle      = AndCondition(state, nonzero(stride), nonzero(field(word1, 31, 1)));
-	const auto index_stride = field(word3, 21, 2);
-	const auto add_tid      = nonzero(field(word3, 23, 1));
-	const auto index =
-	    Binary(state, spv::OpIAdd, TypeU32(state), ctx.Arg(inst, 1),
-	           Select(state, TypeU32(state), add_tid, BufferLane(state), ConstantU32(state, 0)));
-	const auto soffset = ctx.Arg(inst, 3);
-	const auto base    = DeviceAddressFromWords(state, ctx.Arg(handle, 0), field(word1, 0, 16));
-	const auto valid_format    = nonzero(field(word3, 12, 7));
-	const auto mode            = field(word3, 28, 2);
-	const auto index_in_bounds = Binary(state, spv::OpULessThan, TypeBool(state), index, records);
-	const auto scalar_in_bounds =
-	    Binary(state, spv::OpULessThanEqual, TypeBool(state), soffset, records);
-	const auto raw_records = Binary(state, spv::OpISub, TypeU32(state), records, soffset);
-	const auto raw_index_in_bounds =
-	    Binary(state, spv::OpULessThan, TypeBool(state), index, raw_records);
+	const auto address = CalculateBufferAddress(state, access.index, ctx.Arg(inst, 2),
+	                                            access.soffset,
+	                                            ctx.Memory(inst).offset + component * 4u,
+	                                            access.stride, access.swizzle, access.index_stride);
+	// RDNA2 raw DWORD vectors check each component, unlike formatted accesses.
+	const auto structured_bounds = AndCondition(
+	    state, access.index_in_bounds,
+	    Binary(state, spv::OpULessThan, TypeBool(state), address.offset, access.stride));
+	// OOB_SELECT=3 reduces NUM_RECORDS by SOFFSET before the offset/index check.
+	const auto raw_bounds = AndCondition(
+	    state, access.scalar_in_bounds,
+	    Select(state, TypeBool(state), access.swizzle,
+	           AndCondition(state, access.raw_index_in_bounds,
+	                        has_dword(address.offset, access.stride)),
+	           has_dword(address.offset, access.raw_records)));
+	auto in_bounds =
+	    Select(state, TypeBool(state),
+	           Binary(state, spv::OpIEqual, TypeBool(state), access.mode, ConstantU32(state, 0)),
+	           structured_bounds, access.index_in_bounds);
+	in_bounds = Select(
+	    state, TypeBool(state),
+	    Binary(state, spv::OpULessThan, TypeBool(state), access.mode, ConstantU32(state, 2)),
+	    in_bounds,
+	    Select(state, TypeBool(state),
+	           Binary(state, spv::OpIEqual, TypeBool(state), access.mode, ConstantU32(state, 2)),
+	           nonzero(access.records), raw_bounds));
+	return {address.byte, AndCondition(state, access.valid_format, in_bounds)};
+}
+
+uint32_t LoadIndirectBuffer(ValueEmitContext& ctx, const IR::Inst& inst, uint32_t components) {
+	if (ctx.Memory(inst).formatted) return LoadIndirectFormattedBuffer(ctx, inst, components);
+	auto&                   state  = ctx.state;
+	auto                    access = PrepareIndirectBufferAccess(ctx, inst);
+	const auto&             handle = *inst.Arg(0).ResolveInstruction();
+	// The device address is needed only to read; the range check alone stays 32-bit.
+	access.base = DeviceAddressFromWords(
+	    state, ctx.Arg(handle, 0),
+	    EmitBitFieldUExtract(state, ctx.Arg(handle, 1), ConstantU32(state, 0),
+	                         ConstantU32(state, 16)));
 	std::array<uint32_t, 4> values {};
 	for (uint32_t component = 0; component < components; component++) {
-		const auto address = CalculateBufferAddress(state, index, ctx.Arg(inst, 2), soffset,
-		                                            ctx.Memory(inst).offset + component * 4u,
-		                                            stride, swizzle, index_stride);
-		// RDNA2 raw DWORD vectors check each component, unlike formatted accesses.
-		const auto structured_bounds =
-		    AndCondition(state, index_in_bounds,
-		                 Binary(state, spv::OpULessThan, TypeBool(state), address.offset, stride));
-		// OOB_SELECT=3 reduces NUM_RECORDS by SOFFSET before the offset/index check.
-		const auto raw_bounds = AndCondition(
-		    state, scalar_in_bounds,
-		    Select(state, TypeBool(state), swizzle,
-		           AndCondition(state, raw_index_in_bounds, has_dword(address.offset, stride)),
-		           has_dword(address.offset, raw_records)));
-		auto in_bounds =
-		    Select(state, TypeBool(state),
-		           Binary(state, spv::OpIEqual, TypeBool(state), mode, ConstantU32(state, 0)),
-		           structured_bounds, index_in_bounds);
-		in_bounds = Select(
-		    state, TypeBool(state),
-		    Binary(state, spv::OpULessThan, TypeBool(state), mode, ConstantU32(state, 2)),
-		    in_bounds,
-		    Select(state, TypeBool(state),
-		           Binary(state, spv::OpIEqual, TypeBool(state), mode, ConstantU32(state, 2)),
-		           nonzero(records), raw_bounds));
+		const auto [byte, in_bounds] = IndirectBufferComponent(ctx, inst, access, component);
 		const auto guest =
-		    Binary(state, spv::OpIAdd, TypeScalarU64(state), base,
-		           Unary(state, spv::OpUConvert, TypeScalarU64(state), address.byte));
-		values[component] = LoadBda(ctx, guest, AndCondition(state, valid_format, in_bounds), 32u);
+		    Binary(state, spv::OpIAdd, TypeScalarU64(state), access.base,
+		           Unary(state, spv::OpUConvert, TypeScalarU64(state), byte));
+		values[component] = LoadBda(ctx, guest, in_bounds, 32u);
 	}
-	return ConstructU32Composite(state, components, values);
+	return components == 1u ? values[0] : ConstructU32Composite(state, components, values);
+}
+
+// Research: the enable predicate of a memory access. A buffer bound to the end of its mapping
+// because only the shader knows its record count (MemoryInfo::gpu_records) also applies the
+// hardware's range check with the V# words the shader computed.
+uint32_t EnabledAccess(ValueEmitContext& ctx, const IR::Inst& inst) {
+	const auto enabled = ctx.Arg(inst, inst.NumArgs() - 1);
+	if (IR::BufferAccessOf(inst.GetOpcode()) == IR::BufferAccess::None) {
+		return enabled;
+	}
+	const auto& mem = ctx.Memory(inst);
+	if (mem.kind != IR::ResourceKind::Buffer || !mem.gpu_records) {
+		return enabled;
+	}
+	const auto access = PrepareIndirectBufferAccess(ctx, inst);
+	auto       result = enabled;
+	for (uint32_t component = 0; component < std::max<uint32_t>(1u, mem.data_dwords); component++) {
+		result = AndCondition(ctx.state, result,
+		                      IndirectBufferComponent(ctx, inst, access, component).second);
+	}
+	return result;

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
rg -n -C3 'gpu_records' src/graphics/shader

Repository: KytyPS5/KytyPS5

Length of output: 8126


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- CompileProgram references and rewrite ---'
rg -n -C12 -F -- 'GetBufferResource' src/graphics/shader/recompiler/ShaderRecompiler.cpp
printf '%s\n' '--- PrepareIndirectBufferAccess and EnabledAccess ---'
rg -n -C20 -F -- 'PrepareIndirectBufferAccess' src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp
printf '%s\n' '--- Resource-tracking handle patch context ---'
sed -n '2538,2575p;2798,2825p' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp
printf '%s\n' '--- IR memory metadata and access declarations ---'
sed -n '65,135p' src/graphics/shader/recompiler/ir/ShaderIR.h

Repository: KytyPS5/KytyPS5

Length of output: 13780


🏁 Script executed:

#!/bin/bash
set -eu
sed -n '960,1025p' src/graphics/shader/recompiler/ShaderRecompiler.cpp
rg -n -C20 -F -- 'PrepareIndirectBufferAccess' src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp

Repository: KytyPS5/KytyPS5

Length of output: 8408


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- Complete indirect-buffer bounds calculation ---'
sed -n '1139,1208p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp
printf '%s\n' '--- EnabledAccess call sites ---'
rg -n -C3 -F -- 'EnabledAccess(ctx, inst)' src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp

Repository: KytyPS5/KytyPS5

Length of output: 10130


🏁 Script executed:

#!/bin/bash
set -eu
sed -n '1139,1208p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp
rg -n -C3 -F -- 'EnabledAccess(ctx, inst)' src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp

Repository: KytyPS5/KytyPS5

Length of output: 10045


Preserve descriptor words for gpu_records buffers.

CompileProgram zeroes all GetBufferResource arguments unless the resource is an IndirectBuffer. A gpu_records resource remains a Buffer, so PrepareIndirectBufferAccess receives zero descriptor words. Its valid_format predicate is then false, which disables loads and stores through EnabledAccess; load and atomic results become zero, and stores are skipped.

🐛 Suggested fix
 			if (op == IR::ValueOpcode::GetBufferResource) {
 				if (std::ranges::any_of(inst.Uses(), [&](const IR::Use& use) {
-					return ir.memory_info[use.user->Flags<IR::MemoryFlags>().index].kind ==
-					       IR::ResourceKind::IndirectBuffer;
+					const auto& memory = ir.memory_info[use.user->Flags<IR::MemoryFlags>().index];
+					return memory.kind == IR::ResourceKind::IndirectBuffer ||
+					       (memory.kind == IR::ResourceKind::Buffer && memory.gpu_records);
 				})) {
 					continue;
 				}
**@⁠coderabbitai[bot]** on GitHub · 2026-10-11 19:31 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/937#discussion_r4242913436) On `src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp` line 1249 (outdated): ```diff @@ -800,75 +915,351 @@ uint32_t LoadIndirectBuffer(ValueEmitContext& ctx, const IR::Inst& inst, uint32_ const auto nonzero = [&](uint32_t value) { return Binary(state, spv::OpINotEqual, TypeBool(state), value, ConstantU32(state, 0)); }; + const auto format = memory.typed + ? ConstantU32(state, static_cast<uint32_t>(Format::DecodeTBufferFormat( + memory.data_format, memory.number_format))) + : field(word3, 12, 7); + const auto info = DecodeDynamicBufferFormat(state, format); + // Zero is an unbound format. Other unknown encodings must not silently + // turn an unsupported descriptor into a successful zero-valued load. + EmitIfCondition(state, + AndCondition(state, nonzero(format), + Unary(state, spv::OpLogicalNot, TypeBool(state), info.valid)), + [&]() { + EmitShaderTrap(state, ConstantU32(state, inst.Flags<IR::MemoryFlags>().pc), + ConstantU32(state, 0x100)); + }); + const auto count = field(info.layout, 0, 3); + const auto packed = nonzero(field(info.layout, 8, 1)); + const auto stride = field(word1, 16, 14); + const auto swizzle = AndCondition(state, nonzero(stride), nonzero(field(word1, 31, 1))); + const auto index_stride = field(word3, 21, 2); + const auto index = Binary(state, spv::OpIAdd, TypeU32(state), ctx.Arg(inst, 1), + Select(state, TypeU32(state), nonzero(field(word3, 23, 1)), + BufferLane(state), ConstantU32(state, 0))); + const auto soffset = ctx.Arg(inst, 3); + const auto base = DeviceAddressFromWords(state, ctx.Arg(handle, 0), field(word1, 0, 16)); + const auto address = CalculateBufferAddress(state, index, ctx.Arg(inst, 2), soffset, + memory.offset, stride, swizzle, index_stride); + struct Component { + uint32_t selector, from_memory, bits, bit_shift, byte_offset, load_bits; + }; + std::array<Component, 4> plans {}; + auto payload = ConstantU32(state, 0); + for (uint32_t output = 0; output < components; ++output) { + auto& plan = plans[output]; + plan.selector = memory.typed + ? Select(state, TypeU32(state), + Binary(state, spv::OpULessThan, TypeBool(state), + ConstantU32(state, output), count), + ConstantU32(state, output + 4u), ConstantU32(state, 0)) + : field(word3, output * 3u, 3); + plan.from_memory = Binary(state, spv::OpUGreaterThanEqual, TypeBool(state), plan.selector, + ConstantU32(state, 4)); + const auto reserved = + AndCondition(state, info.valid, + AndCondition(state, + Binary(state, spv::OpUGreaterThan, TypeBool(state), + plan.selector, ConstantU32(state, 1)), + Binary(state, spv::OpULessThan, TypeBool(state), + plan.selector, ConstantU32(state, 4)))); + EmitIfCondition(state, reserved, [&]() { + EmitShaderTrap(state, ConstantU32(state, inst.Flags<IR::MemoryFlags>().pc), + ConstantU32(state, 0x101)); + }); + const auto component = + Binary(state, spv::OpUMod, TypeU32(state), + Binary(state, spv::OpISub, TypeU32(state), plan.selector, ConstantU32(state, 4)), + count); + plan.bits = EmitBitFieldUExtract( + state, info.widths, + Binary(state, spv::OpIMul, TypeU32(state), component, ConstantU32(state, 6)), + ConstantU32(state, 6)); + const auto bit_offset = EmitBitFieldUExtract( + state, info.offsets, + Binary(state, spv::OpIMul, TypeU32(state), component, ConstantU32(state, 7)), + ConstantU32(state, 7)); + plan.byte_offset = Select(state, TypeU32(state), packed, ConstantU32(state, 0), + Binary(state, spv::OpShiftRightLogical, TypeU32(state), + bit_offset, ConstantU32(state, 3))); + plan.bit_shift = Select(state, TypeU32(state), packed, bit_offset, ConstantU32(state, 0)); + plan.load_bits = Select(state, TypeU32(state), packed, ConstantU32(state, 32), plan.bits); + const auto end = Binary(state, spv::OpIAdd, TypeU32(state), plan.byte_offset, + Binary(state, spv::OpShiftRightLogical, TypeU32(state), + plan.load_bits, ConstantU32(state, 3))); + const auto needed = + Select(state, TypeU32(state), plan.from_memory, end, ConstantU32(state, 0)); + payload = Select(state, TypeU32(state), + Binary(state, spv::OpUGreaterThan, TypeBool(state), needed, payload), + needed, payload); + } + const auto has_payload = [&](uint32_t size) { + return AndCondition(state, + Binary(state, spv::OpUGreaterThanEqual, TypeBool(state), size, payload), + Binary(state, spv::OpULessThanEqual, TypeBool(state), address.offset, + Binary(state, spv::OpISub, TypeU32(state), size, payload))); + }; + const auto index_bound = Binary(state, spv::OpULessThan, TypeBool(state), index, records); + const auto structured = + AndCondition(state, index_bound, + Binary(state, spv::OpULessThan, TypeBool(state), address.offset, stride)); + const auto remaining = Binary(state, spv::OpISub, TypeU32(state), records, soffset); + const auto raw = AndCondition( + state, Binary(state, spv::OpULessThanEqual, TypeBool(state), soffset, records), + Select(state, TypeBool(state), swizzle, + AndCondition(state, + Binary(state, spv::OpULessThan, TypeBool(state), index, remaining), + has_payload(stride)), + has_payload(remaining))); + const auto mode = field(word3, 28, 2); + auto bound = Select(state, TypeBool(state), + Binary(state, spv::OpIEqual, TypeBool(state), mode, ConstantU32(state, 0)), + structured, index_bound); + bound = + Select(state, TypeBool(state), + Binary(state, spv::OpULessThan, TypeBool(state), mode, ConstantU32(state, 2)), bound, + Select(state, TypeBool(state), + Binary(state, spv::OpIEqual, TypeBool(state), mode, ConstantU32(state, 2)), + nonzero(records), raw)); + bound = AndCondition(state, info.valid, bound); + const auto integer = + Binary(state, spv::OpLogicalOr, TypeBool(state), + Binary(state, spv::OpIEqual, TypeBool(state), info.type, + ConstantU32(state, static_cast<uint32_t>(Format::ComponentType::Uint))), + Binary(state, spv::OpIEqual, TypeBool(state), info.type, + ConstantU32(state, static_cast<uint32_t>(Format::ComponentType::Sint)))); + const auto one = Select(state, TypeU32(state), integer, ConstantU32(state, 1), + ConstantU32(state, 0x3f800000)); + std::array<uint32_t, 4> values {}; + for (uint32_t output = 0; output < components; ++output) { + const auto& plan = plans[output]; + const auto component_address = CalculateBufferAddress( + state, index, + Binary(state, spv::OpIAdd, TypeU32(state), ctx.Arg(inst, 2), plan.byte_offset), soffset, + memory.offset, stride, swizzle, index_stride); + const auto guest = + Binary(state, spv::OpIAdd, TypeScalarU64(state), base, + Unary(state, spv::OpUConvert, TypeScalarU64(state), component_address.byte)); + const auto loaded = + EmitValueOrZeroIfCondition(state, AndCondition(state, bound, plan.from_memory), [&]() { + return EmitValueOrDefaultIfCondition( + state, + Binary(state, spv::OpUGreaterThan, TypeBool(state), plan.load_bits, + ConstantU32(state, 16)), + TypeU32(state), ConstantU32(state, 0), + [&]() { return LoadBda(ctx, guest, ConstantBool(state, true), 32u); }); + }); + // Subword accesses must not fetch a second page merely because the + // following bytes belong to a different buffer or an unmapped allocation. + const auto subword = EmitValueOrZeroIfCondition( + state, + AndCondition(state, AndCondition(state, bound, plan.from_memory), + Binary(state, spv::OpULessThanEqual, TypeBool(state), plan.load_bits, + ConstantU32(state, 16))), + [&]() { + const auto wide = Binary(state, spv::OpIEqual, TypeBool(state), plan.load_bits, + ConstantU32(state, 16)); + const auto half = LoadBda(ctx, guest, wide, 16u); + const auto byte = + LoadBda(ctx, guest, Unary(state, spv::OpLogicalNot, TypeBool(state), wide), 8u); + return Select(state, TypeU32(state), wide, half, byte); + }); + const auto data = Binary(state, spv::OpBitwiseOr, TypeU32(state), loaded, subword); + const auto extracted = EmitBitFieldUExtract(state, data, plan.bit_shift, plan.bits); + const auto converted = + NormalizeDynamicBufferComponent(state, extracted, plan.bits, info.type); + const auto constant_one = AndCondition( + state, info.valid, + Binary(state, spv::OpIEqual, TypeBool(state), plan.selector, ConstantU32(state, 1))); + values[output] = Select( + state, TypeU32(state), constant_one, one, + Select(state, TypeU32(state), plan.from_memory, converted, ConstantU32(state, 0))); + } + return components == 1u ? values[0] : ConstructU32Composite(state, components, values); +} + +uint32_t LoadIndirectScalarBuffer(ValueEmitContext& ctx, const IR::Inst& inst) { + auto& state = ctx.state; + const auto& handle = *inst.Arg(0).ResolveInstruction(); + const auto word1 = ctx.Arg(handle, 1); + const auto high = + EmitBitFieldUExtract(state, word1, ConstantU32(state, 0), ConstantU32(state, 16)); + const auto stride = + EmitBitFieldUExtract(state, word1, ConstantU32(state, 16), ConstantU32(state, 14)); + const auto records = Unary(state, spv::OpUConvert, TypeScalarU64(state), ctx.Arg(handle, 2)); + const auto size = Select( + state, TypeScalarU64(state), + Binary(state, spv::OpIEqual, TypeBool(state), stride, ConstantU32(state, 0)), records, + Binary(state, spv::OpIMul, TypeScalarU64(state), records, + Unary(state, spv::OpUConvert, TypeScalarU64(state), stride))); + // SMEM ignores the vector format, swizzle, and OOB_SELECT fields. Match + // scalar-buffer addressing: aligned base plus aligned byte offset, with + // stride used only to determine the descriptor's byte extent. + const auto low = Binary(state, spv::OpBitwiseAnd, TypeU32(state), ctx.Arg(handle, 0), + ConstantU32(state, ~3u)); + const auto offset = Binary(state, spv::OpIAdd, TypeU32(state), ctx.Arg(inst, 1), + ConstantU32(state, ctx.Memory(inst).offset)); + const auto aligned = + Binary(state, spv::OpBitwiseAnd, TypeU32(state), offset, ConstantU32(state, ~3u)); + const auto relative = Unary(state, spv::OpUConvert, TypeScalarU64(state), aligned); + const auto end = + Binary(state, spv::OpIAdd, TypeScalarU64(state), relative, ConstantDeviceAddress(state, 4)); + const auto in_bounds = Binary(state, spv::OpULessThanEqual, TypeBool(state), end, size); + const auto address = Binary(state, spv::OpIAdd, TypeScalarU64(state), + DeviceAddressFromWords(state, low, high), relative); + return LoadBda(ctx, address, in_bounds, 32u); +} + +// The hardware's range check of a raw DWORD buffer access, from the V# words the shader holds. +struct IndirectBufferAccess { + uint32_t base = 0; + uint32_t stride = 0; + uint32_t swizzle = 0; + uint32_t index_stride = 0; + uint32_t index = 0; + uint32_t soffset = 0; + uint32_t valid_format = 0; + uint32_t mode = 0; + uint32_t records = 0; + uint32_t index_in_bounds = 0; + uint32_t scalar_in_bounds = 0; + uint32_t raw_records = 0; + uint32_t raw_index_in_bounds = 0; +}; + +IndirectBufferAccess PrepareIndirectBufferAccess(ValueEmitContext& ctx, const IR::Inst& inst) { + auto& state = ctx.state; + const auto& handle = *inst.Arg(0).ResolveInstruction(); + const auto word1 = ctx.Arg(handle, 1); + const auto word3 = ctx.Arg(handle, 3); + const auto field = [&](uint32_t word, uint32_t first, uint32_t count) { + return EmitBitFieldUExtract(state, word, ConstantU32(state, first), + ConstantU32(state, count)); + }; + const auto nonzero = [&](uint32_t value) { + return Binary(state, spv::OpINotEqual, TypeBool(state), value, ConstantU32(state, 0)); + }; + IndirectBufferAccess access; + access.records = ctx.Arg(handle, 2); + access.stride = field(word1, 16, 14); + access.swizzle = AndCondition(state, nonzero(access.stride), nonzero(field(word1, 31, 1))); + access.index_stride = field(word3, 21, 2); + const auto add_tid = nonzero(field(word3, 23, 1)); + access.index = + Binary(state, spv::OpIAdd, TypeU32(state), ctx.Arg(inst, 1), + Select(state, TypeU32(state), add_tid, BufferLane(state), ConstantU32(state, 0))); + access.soffset = ctx.Arg(inst, 3); + access.valid_format = nonzero(field(word3, 12, 7)); + access.mode = field(word3, 28, 2); + access.index_in_bounds = + Binary(state, spv::OpULessThan, TypeBool(state), access.index, access.records); + access.scalar_in_bounds = + Binary(state, spv::OpULessThanEqual, TypeBool(state), access.soffset, access.records); + access.raw_records = + Binary(state, spv::OpISub, TypeU32(state), access.records, access.soffset); + access.raw_index_in_bounds = + Binary(state, spv::OpULessThan, TypeBool(state), access.index, access.raw_records); + return access; +} + +// The byte address (relative to the V# base) of one DWORD of the access, and whether the +// hardware performs it. +std::pair<uint32_t, uint32_t> IndirectBufferComponent(ValueEmitContext& ctx, const IR::Inst& inst, + const IndirectBufferAccess& access, + uint32_t component) { + auto& state = ctx.state; + const auto nonzero = [&](uint32_t value) { + return Binary(state, spv::OpINotEqual, TypeBool(state), value, ConstantU32(state, 0)); + }; const auto has_dword = [&](uint32_t offset, uint32_t size) { return AndCondition( state, Binary(state, spv::OpUGreaterThanEqual, TypeBool(state), size, ConstantU32(state, 4)), Binary(state, spv::OpULessThanEqual, TypeBool(state), offset, Binary(state, spv::OpISub, TypeU32(state), size, ConstantU32(state, 4)))); }; - const auto stride = field(word1, 16, 14); - const auto swizzle = AndCondition(state, nonzero(stride), nonzero(field(word1, 31, 1))); - const auto index_stride = field(word3, 21, 2); - const auto add_tid = nonzero(field(word3, 23, 1)); - const auto index = - Binary(state, spv::OpIAdd, TypeU32(state), ctx.Arg(inst, 1), - Select(state, TypeU32(state), add_tid, BufferLane(state), ConstantU32(state, 0))); - const auto soffset = ctx.Arg(inst, 3); - const auto base = DeviceAddressFromWords(state, ctx.Arg(handle, 0), field(word1, 0, 16)); - const auto valid_format = nonzero(field(word3, 12, 7)); - const auto mode = field(word3, 28, 2); - const auto index_in_bounds = Binary(state, spv::OpULessThan, TypeBool(state), index, records); - const auto scalar_in_bounds = - Binary(state, spv::OpULessThanEqual, TypeBool(state), soffset, records); - const auto raw_records = Binary(state, spv::OpISub, TypeU32(state), records, soffset); - const auto raw_index_in_bounds = - Binary(state, spv::OpULessThan, TypeBool(state), index, raw_records); + const auto address = CalculateBufferAddress(state, access.index, ctx.Arg(inst, 2), + access.soffset, + ctx.Memory(inst).offset + component * 4u, + access.stride, access.swizzle, access.index_stride); + // RDNA2 raw DWORD vectors check each component, unlike formatted accesses. + const auto structured_bounds = AndCondition( + state, access.index_in_bounds, + Binary(state, spv::OpULessThan, TypeBool(state), address.offset, access.stride)); + // OOB_SELECT=3 reduces NUM_RECORDS by SOFFSET before the offset/index check. + const auto raw_bounds = AndCondition( + state, access.scalar_in_bounds, + Select(state, TypeBool(state), access.swizzle, + AndCondition(state, access.raw_index_in_bounds, + has_dword(address.offset, access.stride)), + has_dword(address.offset, access.raw_records))); + auto in_bounds = + Select(state, TypeBool(state), + Binary(state, spv::OpIEqual, TypeBool(state), access.mode, ConstantU32(state, 0)), + structured_bounds, access.index_in_bounds); + in_bounds = Select( + state, TypeBool(state), + Binary(state, spv::OpULessThan, TypeBool(state), access.mode, ConstantU32(state, 2)), + in_bounds, + Select(state, TypeBool(state), + Binary(state, spv::OpIEqual, TypeBool(state), access.mode, ConstantU32(state, 2)), + nonzero(access.records), raw_bounds)); + return {address.byte, AndCondition(state, access.valid_format, in_bounds)}; +} + +uint32_t LoadIndirectBuffer(ValueEmitContext& ctx, const IR::Inst& inst, uint32_t components) { + if (ctx.Memory(inst).formatted) return LoadIndirectFormattedBuffer(ctx, inst, components); + auto& state = ctx.state; + auto access = PrepareIndirectBufferAccess(ctx, inst); + const auto& handle = *inst.Arg(0).ResolveInstruction(); + // The device address is needed only to read; the range check alone stays 32-bit. + access.base = DeviceAddressFromWords( + state, ctx.Arg(handle, 0), + EmitBitFieldUExtract(state, ctx.Arg(handle, 1), ConstantU32(state, 0), + ConstantU32(state, 16))); std::array<uint32_t, 4> values {}; for (uint32_t component = 0; component < components; component++) { - const auto address = CalculateBufferAddress(state, index, ctx.Arg(inst, 2), soffset, - ctx.Memory(inst).offset + component * 4u, - stride, swizzle, index_stride); - // RDNA2 raw DWORD vectors check each component, unlike formatted accesses. - const auto structured_bounds = - AndCondition(state, index_in_bounds, - Binary(state, spv::OpULessThan, TypeBool(state), address.offset, stride)); - // OOB_SELECT=3 reduces NUM_RECORDS by SOFFSET before the offset/index check. - const auto raw_bounds = AndCondition( - state, scalar_in_bounds, - Select(state, TypeBool(state), swizzle, - AndCondition(state, raw_index_in_bounds, has_dword(address.offset, stride)), - has_dword(address.offset, raw_records))); - auto in_bounds = - Select(state, TypeBool(state), - Binary(state, spv::OpIEqual, TypeBool(state), mode, ConstantU32(state, 0)), - structured_bounds, index_in_bounds); - in_bounds = Select( - state, TypeBool(state), - Binary(state, spv::OpULessThan, TypeBool(state), mode, ConstantU32(state, 2)), - in_bounds, - Select(state, TypeBool(state), - Binary(state, spv::OpIEqual, TypeBool(state), mode, ConstantU32(state, 2)), - nonzero(records), raw_bounds)); + const auto [byte, in_bounds] = IndirectBufferComponent(ctx, inst, access, component); const auto guest = - Binary(state, spv::OpIAdd, TypeScalarU64(state), base, - Unary(state, spv::OpUConvert, TypeScalarU64(state), address.byte)); - values[component] = LoadBda(ctx, guest, AndCondition(state, valid_format, in_bounds), 32u); + Binary(state, spv::OpIAdd, TypeScalarU64(state), access.base, + Unary(state, spv::OpUConvert, TypeScalarU64(state), byte)); + values[component] = LoadBda(ctx, guest, in_bounds, 32u); } - return ConstructU32Composite(state, components, values); + return components == 1u ? values[0] : ConstructU32Composite(state, components, values); +} + +// Research: the enable predicate of a memory access. A buffer bound to the end of its mapping +// because only the shader knows its record count (MemoryInfo::gpu_records) also applies the +// hardware's range check with the V# words the shader computed. +uint32_t EnabledAccess(ValueEmitContext& ctx, const IR::Inst& inst) { + const auto enabled = ctx.Arg(inst, inst.NumArgs() - 1); + if (IR::BufferAccessOf(inst.GetOpcode()) == IR::BufferAccess::None) { + return enabled; + } + const auto& mem = ctx.Memory(inst); + if (mem.kind != IR::ResourceKind::Buffer || !mem.gpu_records) { + return enabled; + } + const auto access = PrepareIndirectBufferAccess(ctx, inst); + auto result = enabled; + for (uint32_t component = 0; component < std::max<uint32_t>(1u, mem.data_dwords); component++) { + result = AndCondition(ctx.state, result, + IndirectBufferComponent(ctx, inst, access, component).second); + } + return result; ``` **🎯 Functional Correctness** | **🟠 Major** | **⚡ Quick win** <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash #!/bin/bash rg -n -C3 'gpu_records' src/graphics/shader ``` Repository: KytyPS5/KytyPS5 Length of output: 8126 --- 🏁 Script executed: ```bash #!/bin/bash set -eu printf '%s\n' '--- CompileProgram references and rewrite ---' rg -n -C12 -F -- 'GetBufferResource' src/graphics/shader/recompiler/ShaderRecompiler.cpp printf '%s\n' '--- PrepareIndirectBufferAccess and EnabledAccess ---' rg -n -C20 -F -- 'PrepareIndirectBufferAccess' src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp printf '%s\n' '--- Resource-tracking handle patch context ---' sed -n '2538,2575p;2798,2825p' src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp printf '%s\n' '--- IR memory metadata and access declarations ---' sed -n '65,135p' src/graphics/shader/recompiler/ir/ShaderIR.h ``` Repository: KytyPS5/KytyPS5 Length of output: 13780 --- 🏁 Script executed: ```bash #!/bin/bash set -eu sed -n '960,1025p' src/graphics/shader/recompiler/ShaderRecompiler.cpp rg -n -C20 -F -- 'PrepareIndirectBufferAccess' src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 8408 --- 🏁 Script executed: ```bash #!/bin/bash set -eu printf '%s\n' '--- Complete indirect-buffer bounds calculation ---' sed -n '1139,1208p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp printf '%s\n' '--- EnabledAccess call sites ---' rg -n -C3 -F -- 'EnabledAccess(ctx, inst)' src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 10130 --- 🏁 Script executed: ```bash #!/bin/bash set -eu sed -n '1139,1208p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp rg -n -C3 -F -- 'EnabledAccess(ctx, inst)' src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 10045 --- </details> **Preserve descriptor words for `gpu_records` buffers.** `CompileProgram` zeroes all `GetBufferResource` arguments unless the resource is an `IndirectBuffer`. A `gpu_records` resource remains a `Buffer`, so `PrepareIndirectBufferAccess` receives zero descriptor words. Its `valid_format` predicate is then false, which disables loads and stores through `EnabledAccess`; load and atomic results become zero, and stores are skipped. <details> <summary>🐛 Suggested fix</summary> ```diff if (op == IR::ValueOpcode::GetBufferResource) { if (std::ranges::any_of(inst.Uses(), [&](const IR::Use& use) { - return ir.memory_info[use.user->Flags<IR::MemoryFlags>().index].kind == - IR::ResourceKind::IndirectBuffer; + const auto& memory = ir.memory_info[use.user->Flags<IR::MemoryFlags>().index]; + return memory.kind == IR::ResourceKind::IndirectBuffer || + (memory.kind == IR::ResourceKind::Buffer && memory.gpu_records); })) { continue; } ``` </details> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:216b8bfb9297e547ac1b9a77 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-11 19:31 UTC · original
On src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemoryHelpers.cpp line 125 (outdated):

@@ -111,9 +120,9 @@ MemoryResourceAccess PrepareStorageBufferResourceAccess(EmitterState& state,
 	state.builder.AddFunction(spv::OpAccessChain, pointer_type, access.object_pointer, variable,
 	                          ConstantU32(state, array_index));
 	access.byte_offset = state.memory_byte_offsets[array_index];
-	access.length      = state.builder.AllocateId();
-	state.builder.AddFunction(spv::OpArrayLength, TypeU32(state), access.length,
-	                          access.object_pointer, 0);
+	// Some NVIDIA drivers return zero from OpArrayLength for ranges over 2 GiB.
+	// Use the actual bound range, including alignment, without truncating guest memory.
+	access.length = state.memory_dword_lengths[array_index];

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

64-bit buffer atomics compare a qword index against a dword length.

access.length is now memory_dword_lengths[...], which counts dwords. EmitBufferAtomic64 (src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp, Lines 1463-1468) computes a qword index (byte_address >> 3) and passes it to EmitMemoryElementInBounds with this length. Before this change, OpArrayLength on the u64 runtime array returned a qword count. Now the check allows indices up to twice the bound range. An out-of-bounds guest atomic can then change memory beyond the buffer instead of being dropped.

Scale the length when the pointer type is the u64 array.

Proposed fix
 	access.length = state.memory_dword_lengths[array_index];
+	if (pointer_type == TypeStorageBufferU64Pointer(state)) {
+		access.length = EmitBinaryU32(state, spv::OpShiftRightLogical, access.length,
+		                              ConstantU32(state, 1u));
+	}
📝 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.

	// Some NVIDIA drivers return zero from OpArrayLength for ranges over 2 GiB.
	// Use the actual bound range, including alignment, without truncating guest memory.
	access.length = state.memory_dword_lengths[array_index];
	if (pointer_type == TypeStorageBufferU64Pointer(state)) {
		access.length = EmitBinaryU32(state, spv::OpShiftRightLogical, access.length,
		                              ConstantU32(state, 1u));
	}
**@⁠coderabbitai[bot]** on GitHub · 2026-10-11 19:31 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/937#discussion_r4242913440) On `src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemoryHelpers.cpp` line 125 (outdated): ```diff @@ -111,9 +120,9 @@ MemoryResourceAccess PrepareStorageBufferResourceAccess(EmitterState& state, state.builder.AddFunction(spv::OpAccessChain, pointer_type, access.object_pointer, variable, ConstantU32(state, array_index)); access.byte_offset = state.memory_byte_offsets[array_index]; - access.length = state.builder.AllocateId(); - state.builder.AddFunction(spv::OpArrayLength, TypeU32(state), access.length, - access.object_pointer, 0); + // Some NVIDIA drivers return zero from OpArrayLength for ranges over 2 GiB. + // Use the actual bound range, including alignment, without truncating guest memory. + access.length = state.memory_dword_lengths[array_index]; ``` **🗄️ Data Integrity & Integration** | **🟡 Minor** | **⚡ Quick win** **64-bit buffer atomics compare a qword index against a dword length.** `access.length` is now `memory_dword_lengths[...]`, which counts dwords. `EmitBufferAtomic64` (`src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp`, Lines 1463-1468) computes a qword index (`byte_address >> 3`) and passes it to `EmitMemoryElementInBounds` with this length. Before this change, `OpArrayLength` on the u64 runtime array returned a qword count. Now the check allows indices up to twice the bound range. An out-of-bounds guest atomic can then change memory beyond the buffer instead of being dropped. Scale the length when the pointer type is the u64 array. <details> <summary>Proposed fix</summary> ```diff access.length = state.memory_dword_lengths[array_index]; + if (pointer_type == TypeStorageBufferU64Pointer(state)) { + access.length = EmitBinaryU32(state, spv::OpShiftRightLogical, access.length, + ConstantU32(state, 1u)); + } ``` </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 // Some NVIDIA drivers return zero from OpArrayLength for ranges over 2 GiB. // Use the actual bound range, including alignment, without truncating guest memory. access.length = state.memory_dword_lengths[array_index]; if (pointer_type == TypeStorageBufferU64Pointer(state)) { access.length = EmitBinaryU32(state, spv::OpShiftRightLogical, access.length, ConstantU32(state, 1u)); } ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:a6b9ba2798479815fb7616b3 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-11 19:31 UTC · original
On src/graphics/shader/recompiler/frontend/translate/Memory.cpp line 657 (outdated):

@@ -580,7 +578,121 @@ void Translator::DS_ATOMIC(const Decoder::Instruction& inst, IR::ValueOpcode opc
 	}
 }
 
+// DS_ADD_U64 (no return) as two 32-bit atomics: the low dword's add, then the high dword's add
+// with the low one's carry. The sum is exact; only a read between the two could see one half
+// updated.
+void Translator::DS_ADD_U64(const Decoder::Instruction& inst) {
+	auto memory            = MemoryInfoFromDecoded(inst);
+	memory.data_dwords     = 1u;
+	memory.component_count = 1u;
+	const auto address     = ReadU32(MemorySourceAt(inst, 1));
+	const auto data        = MemorySourceAt(inst, 0);
+	const auto low         = IR::U32(ReadU32(OffsetOperand(data, 0)));
+	const auto high        = IR::U32(ReadU32(OffsetOperand(data, 1)));
+	const auto old_low     = IR::U32(ir.Emit(IR::ValueOpcode::SharedAtomicIAdd32,
+	                                         {address, low, ir.GetExec()},
+	                                         AddMemoryInfo(memory, inst.pc)));
+	const auto carry = ir.Select(ir.ULessThan(ir.IAdd(old_low, low), old_low),
+	                             IR::U32(IR::Value(1u)), IR::U32(IR::Value(0u)));
+	auto high_memory = memory;
+	high_memory.offset += 4u;
+	ir.Emit(IR::ValueOpcode::SharedAtomicIAdd32, {address, ir.IAdd(high, carry), ir.GetExec()},
+	        AddMemoryInfo(high_memory, inst.pc));
+}
+
+void Translator::FLAT_APERTURE(const Decoder::Instruction& inst, bool store) {
+	const auto      memory = MemoryInfoFromDecoded(inst);
+	const auto      bits   = memory.data_bits;
+	IR::ValueOpcode address_op;
+	IR::ValueOpcode shared_op;
+	switch (bits) {
+		case 8u:
+			address_op = store ? IR::ValueOpcode::StoreAddressU8 : IR::ValueOpcode::LoadAddressU8;
+			shared_op  = store ? IR::ValueOpcode::WriteSharedU8 : IR::ValueOpcode::LoadSharedU8;
+			break;
+		case 16u:
+			address_op = store ? IR::ValueOpcode::StoreAddressU16 : IR::ValueOpcode::LoadAddressU16;
+			shared_op  = store ? IR::ValueOpcode::WriteSharedU16 : IR::ValueOpcode::LoadSharedU16;
+			break;
+		case 32u:
+			address_op = store ? IR::ValueOpcode::StoreAddressU32 : IR::ValueOpcode::LoadAddressU32;
+			shared_op  = store ? IR::ValueOpcode::WriteSharedU32 : IR::ValueOpcode::LoadSharedU32;
+			break;
+		default:
+			EXIT("opcode %s at pc 0x%08x has unsupported flat aperture width %u",
+			     Decoder::InstructionToString(inst).c_str(), inst.pc, bits);
+			return;
+	}
+	const auto address = ReadAddressOperands(inst, store ? 1u : 0u);
+	const auto zero    = IR::U32(IR::Value(0u));
+	const auto active  = ir.GetExec();
+	const auto count   = bits == 32u ? std::min(memory.data_dwords, 4u) : 1u;
+	for (uint32_t index = 0; index < count; ++index) {
+		// Classify the effective 64-bit address, including carry from the instruction
+		// offset and each component. A local offset must not wrap into its aperture.
+		const auto low =
+		    ir.IAdd(IR::U32(address.low), IR::U32(IR::Value(memory.offset + index * 4u)));
+		const auto carry =
+		    ir.Select(ir.ULessThan(low, IR::U32(address.low)), IR::U32(IR::Value(1u)), zero);
+		const auto high           = ir.IAdd(IR::U32(address.high), carry);
+		const auto shared         = ir.IEqual(high, IR::U32(IR::Value(IR::SharedApertureHigh)));
+		const auto private_memory = ir.IEqual(high, IR::U32(IR::Value(IR::PrivateApertureHigh)));
+		const auto global_active =
+		    ir.LogicalAnd(active, ir.LogicalNot(ir.LogicalOr(shared, private_memory)));
+		const auto shared_active    = ir.LogicalAnd(active, shared);
+		const auto private_active   = ir.LogicalAnd(active, private_memory);
+		auto       global_info      = memory;
+		global_info.offset          = 0;
+		global_info.data_dwords     = 1;
+		global_info.component_index = index;
+		global_info.kind            = IR::ResourceKind::Global;
+		auto shared_info            = global_info;
+		shared_info.kind            = IR::ResourceKind::Lds;
+		auto private_info           = global_info;
+		private_info.kind           = IR::ResourceKind::Scratch;
+		const auto resource         = GetAddressResource(low, high);
+		if (store) {
+			auto value = IR::Value(ReadU32(OffsetOperand(MemorySourceAt(inst, 0), index)));
+			if (bits != 32u) value = NarrowSubdword(IR::U32(value), bits);
+			ir.Emit(shared_op, {low, value, shared_active}, AddMemoryInfo(shared_info, inst.pc));

🚀 Performance & Scalability | 🟠 Major | ⚡ Quick win

FLAT_APERTURE emits LDS accesses in stages without workgroup LDS, which brings back the 8192-dword per-invocation array.

Every segment-0 flat access now also emits LoadSharedU* or WriteSharedU* with the raw address low. In a vertex or pixel shader, AnalyzeProgramRequirements sets function_lds for these accesses. UpperBoundU32(low) has no bound, so function_lds_unbounded is true. LdsDwordCount then falls back to 8192 dwords of Function storage per invocation. The comment in SpirvEmitter.cpp (Line 263-265) says this costs several GB of local memory across the GPU on NVIDIA. Before this change, flat accesses did not create any function LDS.

Emit the shared path only when the stage has workgroup LDS (ShaderWorkgroupInput(...) != nullptr). In other stages, treat the shared aperture as returning zero or as not supported.

Also applies to: 675-676

**@⁠coderabbitai[bot]** on GitHub · 2026-10-11 19:31 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/937#discussion_r4242913446) On `src/graphics/shader/recompiler/frontend/translate/Memory.cpp` line 657 (outdated): ```diff @@ -580,7 +578,121 @@ void Translator::DS_ATOMIC(const Decoder::Instruction& inst, IR::ValueOpcode opc } } +// DS_ADD_U64 (no return) as two 32-bit atomics: the low dword's add, then the high dword's add +// with the low one's carry. The sum is exact; only a read between the two could see one half +// updated. +void Translator::DS_ADD_U64(const Decoder::Instruction& inst) { + auto memory = MemoryInfoFromDecoded(inst); + memory.data_dwords = 1u; + memory.component_count = 1u; + const auto address = ReadU32(MemorySourceAt(inst, 1)); + const auto data = MemorySourceAt(inst, 0); + const auto low = IR::U32(ReadU32(OffsetOperand(data, 0))); + const auto high = IR::U32(ReadU32(OffsetOperand(data, 1))); + const auto old_low = IR::U32(ir.Emit(IR::ValueOpcode::SharedAtomicIAdd32, + {address, low, ir.GetExec()}, + AddMemoryInfo(memory, inst.pc))); + const auto carry = ir.Select(ir.ULessThan(ir.IAdd(old_low, low), old_low), + IR::U32(IR::Value(1u)), IR::U32(IR::Value(0u))); + auto high_memory = memory; + high_memory.offset += 4u; + ir.Emit(IR::ValueOpcode::SharedAtomicIAdd32, {address, ir.IAdd(high, carry), ir.GetExec()}, + AddMemoryInfo(high_memory, inst.pc)); +} + +void Translator::FLAT_APERTURE(const Decoder::Instruction& inst, bool store) { + const auto memory = MemoryInfoFromDecoded(inst); + const auto bits = memory.data_bits; + IR::ValueOpcode address_op; + IR::ValueOpcode shared_op; + switch (bits) { + case 8u: + address_op = store ? IR::ValueOpcode::StoreAddressU8 : IR::ValueOpcode::LoadAddressU8; + shared_op = store ? IR::ValueOpcode::WriteSharedU8 : IR::ValueOpcode::LoadSharedU8; + break; + case 16u: + address_op = store ? IR::ValueOpcode::StoreAddressU16 : IR::ValueOpcode::LoadAddressU16; + shared_op = store ? IR::ValueOpcode::WriteSharedU16 : IR::ValueOpcode::LoadSharedU16; + break; + case 32u: + address_op = store ? IR::ValueOpcode::StoreAddressU32 : IR::ValueOpcode::LoadAddressU32; + shared_op = store ? IR::ValueOpcode::WriteSharedU32 : IR::ValueOpcode::LoadSharedU32; + break; + default: + EXIT("opcode %s at pc 0x%08x has unsupported flat aperture width %u", + Decoder::InstructionToString(inst).c_str(), inst.pc, bits); + return; + } + const auto address = ReadAddressOperands(inst, store ? 1u : 0u); + const auto zero = IR::U32(IR::Value(0u)); + const auto active = ir.GetExec(); + const auto count = bits == 32u ? std::min(memory.data_dwords, 4u) : 1u; + for (uint32_t index = 0; index < count; ++index) { + // Classify the effective 64-bit address, including carry from the instruction + // offset and each component. A local offset must not wrap into its aperture. + const auto low = + ir.IAdd(IR::U32(address.low), IR::U32(IR::Value(memory.offset + index * 4u))); + const auto carry = + ir.Select(ir.ULessThan(low, IR::U32(address.low)), IR::U32(IR::Value(1u)), zero); + const auto high = ir.IAdd(IR::U32(address.high), carry); + const auto shared = ir.IEqual(high, IR::U32(IR::Value(IR::SharedApertureHigh))); + const auto private_memory = ir.IEqual(high, IR::U32(IR::Value(IR::PrivateApertureHigh))); + const auto global_active = + ir.LogicalAnd(active, ir.LogicalNot(ir.LogicalOr(shared, private_memory))); + const auto shared_active = ir.LogicalAnd(active, shared); + const auto private_active = ir.LogicalAnd(active, private_memory); + auto global_info = memory; + global_info.offset = 0; + global_info.data_dwords = 1; + global_info.component_index = index; + global_info.kind = IR::ResourceKind::Global; + auto shared_info = global_info; + shared_info.kind = IR::ResourceKind::Lds; + auto private_info = global_info; + private_info.kind = IR::ResourceKind::Scratch; + const auto resource = GetAddressResource(low, high); + if (store) { + auto value = IR::Value(ReadU32(OffsetOperand(MemorySourceAt(inst, 0), index))); + if (bits != 32u) value = NarrowSubdword(IR::U32(value), bits); + ir.Emit(shared_op, {low, value, shared_active}, AddMemoryInfo(shared_info, inst.pc)); ``` **🚀 Performance & Scalability** | **🟠 Major** | **⚡ Quick win** **`FLAT_APERTURE` emits LDS accesses in stages without workgroup LDS, which brings back the 8192-dword per-invocation array.** Every segment-0 flat access now also emits `LoadSharedU*` or `WriteSharedU*` with the raw address `low`. In a vertex or pixel shader, `AnalyzeProgramRequirements` sets `function_lds` for these accesses. `UpperBoundU32(low)` has no bound, so `function_lds_unbounded` is true. `LdsDwordCount` then falls back to 8192 dwords of Function storage per invocation. The comment in `SpirvEmitter.cpp` (Line 263-265) says this costs several GB of local memory across the GPU on NVIDIA. Before this change, flat accesses did not create any function LDS. Emit the shared path only when the stage has workgroup LDS (`ShaderWorkgroupInput(...) != nullptr`). In other stages, treat the shared aperture as returning zero or as not supported. Also applies to: 675-676 <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:f02350f8589d61608f66873f --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-11 19:31 UTC · original
On src/graphics/shader/recompiler/frontend/translate/Translate.cpp line 142 (outdated):

@@ -135,7 +135,11 @@ IR::U32 Translator::ReadRawU32(const Decoder::Operand& operand) {
 		case Decoder::OperandKind::IntegerInlineConstant:
 		case Decoder::OperandKind::FloatInlineConstant: return IR::U32(IR::Value(operand.value));
 		case Decoder::OperandKind::Null:
+		case Decoder::OperandKind::SharedBase:
+		case Decoder::OperandKind::PrivateBase:
 		case Decoder::OperandKind::PopsExitingWaveId: return IR::U32(IR::Value(0u));
+		case Decoder::OperandKind::SharedLimit:
+		case Decoder::OperandKind::PrivateLimit: return IR::U32(IR::Value(UINT32_MAX));

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🌐 Web query:

RDNA2 ISA SRC_SHARED_BASE 32-bit operand returns high 32 bits aperture

💡 Result:

**Yes—but with an important distinction:** `SRC_SHARED_BASE` used as a 32-bit scalar source gives you the low 32-bit *portion of the aperture register*, and that portion represents the **upper 32 bits of the 64-bit base address**. The address’s lower 32 bits are implicitly zero. LLVM’s AMDGPU implementation notes this layout and says the high half of the aperture register cannot be read as a 32-bit operand. ([lists.llvm.org](https://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20221121/1098211.html))

So it is **not** returning the address’s low 32 bits; for the full 64-bit aperture value, the 32-bit operand alone is insufficient. The RDNA2 ISA lists `SHARED_BASE` as a scalar source operand. ([amd.com](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf?utm_source=openai))

Citations:

- 1: https://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20221121/1098211.html
- 2: https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf?utm_source=openai

🏁 Script executed:

set -eu
printf '%s\n' '--- Translate.cpp target and nearby helpers ---'
nl -ba src/graphics/shader/recompiler/frontend/translate/Translate.cpp | sed -n '90,175p'
printf '%s\n' '--- aperture symbols and consumers ---'
rg -n -F --glob '*.{cpp,h,hpp}' -- 'SharedApertureHigh' src
rg -n -F --glob '*.{cpp,h,hpp}' -- 'PrivateApertureHigh' src
printf '%s\n' '--- relevant diff ---'
git diff --unified=30 b7a1fac898be93bfe0c282752a7a386fd5202486 41c7b27b738ce882c93108e8b882405e33a78d8d -- src/graphics/shader/recompiler/frontend/translate/Translate.cpp

Repository: KytyPS5/KytyPS5

Length of output: 19605


🏁 Script executed:

set -eu
printf '%s\n' '--- Translate pair readers and callers ---'
nl -ba src/graphics/shader/recompiler/frontend/translate/Translate.cpp | sed -n '465,525p'
rg -n -F --glob '*.{cpp,h,hpp}' -- 'ReadU32Pair(' src/graphics/shader/recompiler/frontend/translate
rg -n -F --glob '*.{cpp,h,hpp}' -- 'ReadU64(' src/graphics/shader/recompiler/frontend/translate
printf '%s\n' '--- operand packing and flat aperture classification ---'
rg -n -F --glob '*.{cpp,h,hpp}' -- 'ReadOperand(' src/graphics/shader/recompiler/frontend/translate
nl -ba src/graphics/shader/recompiler/frontend/translate/Memory.cpp | sed -n '600,665p'
printf '%s\n' '--- aperture constants ---'
nl -ba src/graphics/shader/recompiler/ir/ShaderIR.h | sed -n '20,42p'

Repository: KytyPS5/KytyPS5

Length of output: 16091


🏁 Script executed:

set -eu
nl -ba src/graphics/shader/recompiler/frontend/translate/Translate.cpp | sed -n '200,245p'

Repository: KytyPS5/KytyPS5

Length of output: 2568


🏁 Script executed:

set -eu
nl -ba src/graphics/shader/recompiler/frontend/translate/Translate.cpp | sed -n '233,258p'

Repository: KytyPS5/KytyPS5

Length of output: 1620


Preserve 64-bit aperture pairs while fixing 32-bit base reads.

ReadU32 reaches ReadRawU32, so 32-bit SRC_SHARED_BASE and SRC_PRIVATE_BASE reads currently return zero. These operands provide the aperture high word. Return the matching aperture constant for direct 32-bit reads.

ReadU32Pair also uses ReadRawU32 as the low word. Keep that low word zero for 64-bit aperture reads, or the aperture high word will be written into both halves.

Suggested fix
 		case Decoder::OperandKind::Null:
-		case Decoder::OperandKind::SharedBase:
-		case Decoder::OperandKind::PrivateBase:
 		case Decoder::OperandKind::PopsExitingWaveId: return IR::U32(IR::Value(0u));
+		case Decoder::OperandKind::SharedBase:
+			return IR::U32(IR::Value(IR::SharedApertureHigh));
+		case Decoder::OperandKind::PrivateBase:
+			return IR::U32(IR::Value(IR::PrivateApertureHigh));
 		case Decoder::OperandKind::SharedLimit:
 		case Decoder::OperandKind::PrivateLimit: return IR::U32(IR::Value(UINT32_MAX));
 
 		// ...
 
 		if (operand.kind == Decoder::OperandKind::SharedBase ||
 		    operand.kind == Decoder::OperandKind::SharedLimit) {
-			return {ReadRawU32(operand), IR::U32(IR::Value(IR::SharedApertureHigh))};
+			const auto low = operand.kind == Decoder::OperandKind::SharedBase
+			                   ? IR::U32(IR::Value(0u))
+			                   : ReadRawU32(operand);
+			return {low, IR::U32(IR::Value(IR::SharedApertureHigh))};
 		}
 		if (operand.kind == Decoder::OperandKind::PrivateBase ||
 		    operand.kind == Decoder::OperandKind::PrivateLimit) {
-			return {ReadRawU32(operand), IR::U32(IR::Value(IR::PrivateApertureHigh))};
+			const auto low = operand.kind == Decoder::OperandKind::PrivateBase
+			                   ? IR::U32(IR::Value(0u))
+			                   : ReadRawU32(operand);
+			return {low, IR::U32(IR::Value(IR::PrivateApertureHigh))};
 		}
**@⁠coderabbitai[bot]** on GitHub · 2026-10-11 19:31 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/937#discussion_r4242913448) On `src/graphics/shader/recompiler/frontend/translate/Translate.cpp` line 142 (outdated): ```diff @@ -135,7 +135,11 @@ IR::U32 Translator::ReadRawU32(const Decoder::Operand& operand) { case Decoder::OperandKind::IntegerInlineConstant: case Decoder::OperandKind::FloatInlineConstant: return IR::U32(IR::Value(operand.value)); case Decoder::OperandKind::Null: + case Decoder::OperandKind::SharedBase: + case Decoder::OperandKind::PrivateBase: case Decoder::OperandKind::PopsExitingWaveId: return IR::U32(IR::Value(0u)); + case Decoder::OperandKind::SharedLimit: + case Decoder::OperandKind::PrivateLimit: return IR::U32(IR::Value(UINT32_MAX)); ``` **🎯 Functional Correctness** | **🟡 Minor** | **⚡ Quick win** <details> <summary>🔎 Supported by static analysis</summary> 🌐 Web query: `RDNA2 ISA SRC_SHARED_BASE 32-bit operand returns high 32 bits aperture` 💡 Result: ``` **Yes—but with an important distinction:** `SRC_SHARED_BASE` used as a 32-bit scalar source gives you the low 32-bit *portion of the aperture register*, and that portion represents the **upper 32 bits of the 64-bit base address**. The address’s lower 32 bits are implicitly zero. LLVM’s AMDGPU implementation notes this layout and says the high half of the aperture register cannot be read as a 32-bit operand. ([lists.llvm.org](https://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20221121/1098211.html)) So it is **not** returning the address’s low 32 bits; for the full 64-bit aperture value, the 32-bit operand alone is insufficient. The RDNA2 ISA lists `SHARED_BASE` as a scalar source operand. ([amd.com](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf?utm_source=openai)) Citations: - 1: https://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20221121/1098211.html - 2: https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf?utm_source=openai ``` --- 🏁 Script executed: ```bash set -eu printf '%s\n' '--- Translate.cpp target and nearby helpers ---' nl -ba src/graphics/shader/recompiler/frontend/translate/Translate.cpp | sed -n '90,175p' printf '%s\n' '--- aperture symbols and consumers ---' rg -n -F --glob '*.{cpp,h,hpp}' -- 'SharedApertureHigh' src rg -n -F --glob '*.{cpp,h,hpp}' -- 'PrivateApertureHigh' src printf '%s\n' '--- relevant diff ---' git diff --unified=30 b7a1fac898be93bfe0c282752a7a386fd5202486 41c7b27b738ce882c93108e8b882405e33a78d8d -- src/graphics/shader/recompiler/frontend/translate/Translate.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 19605 --- 🏁 Script executed: ```bash set -eu printf '%s\n' '--- Translate pair readers and callers ---' nl -ba src/graphics/shader/recompiler/frontend/translate/Translate.cpp | sed -n '465,525p' rg -n -F --glob '*.{cpp,h,hpp}' -- 'ReadU32Pair(' src/graphics/shader/recompiler/frontend/translate rg -n -F --glob '*.{cpp,h,hpp}' -- 'ReadU64(' src/graphics/shader/recompiler/frontend/translate printf '%s\n' '--- operand packing and flat aperture classification ---' rg -n -F --glob '*.{cpp,h,hpp}' -- 'ReadOperand(' src/graphics/shader/recompiler/frontend/translate nl -ba src/graphics/shader/recompiler/frontend/translate/Memory.cpp | sed -n '600,665p' printf '%s\n' '--- aperture constants ---' nl -ba src/graphics/shader/recompiler/ir/ShaderIR.h | sed -n '20,42p' ``` Repository: KytyPS5/KytyPS5 Length of output: 16091 --- 🏁 Script executed: ```bash set -eu nl -ba src/graphics/shader/recompiler/frontend/translate/Translate.cpp | sed -n '200,245p' ``` Repository: KytyPS5/KytyPS5 Length of output: 2568 --- 🏁 Script executed: ```bash set -eu nl -ba src/graphics/shader/recompiler/frontend/translate/Translate.cpp | sed -n '233,258p' ``` Repository: KytyPS5/KytyPS5 Length of output: 1620 --- </details> **Preserve 64-bit aperture pairs while fixing 32-bit base reads.** `ReadU32` reaches `ReadRawU32`, so 32-bit `SRC_SHARED_BASE` and `SRC_PRIVATE_BASE` reads currently return zero. These operands provide the aperture high word. Return the matching aperture constant for direct 32-bit reads. `ReadU32Pair` also uses `ReadRawU32` as the low word. Keep that low word zero for 64-bit aperture reads, or the aperture high word will be written into both halves. <details> <summary>Suggested fix</summary> ```diff case Decoder::OperandKind::Null: - case Decoder::OperandKind::SharedBase: - case Decoder::OperandKind::PrivateBase: case Decoder::OperandKind::PopsExitingWaveId: return IR::U32(IR::Value(0u)); + case Decoder::OperandKind::SharedBase: + return IR::U32(IR::Value(IR::SharedApertureHigh)); + case Decoder::OperandKind::PrivateBase: + return IR::U32(IR::Value(IR::PrivateApertureHigh)); case Decoder::OperandKind::SharedLimit: case Decoder::OperandKind::PrivateLimit: return IR::U32(IR::Value(UINT32_MAX)); // ... if (operand.kind == Decoder::OperandKind::SharedBase || operand.kind == Decoder::OperandKind::SharedLimit) { - return {ReadRawU32(operand), IR::U32(IR::Value(IR::SharedApertureHigh))}; + const auto low = operand.kind == Decoder::OperandKind::SharedBase + ? IR::U32(IR::Value(0u)) + : ReadRawU32(operand); + return {low, IR::U32(IR::Value(IR::SharedApertureHigh))}; } if (operand.kind == Decoder::OperandKind::PrivateBase || operand.kind == Decoder::OperandKind::PrivateLimit) { - return {ReadRawU32(operand), IR::U32(IR::Value(IR::PrivateApertureHigh))}; + const auto low = operand.kind == Decoder::OperandKind::PrivateBase + ? IR::U32(IR::Value(0u)) + : ReadRawU32(operand); + return {low, IR::U32(IR::Value(IR::PrivateApertureHigh))}; } ``` </details> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:df10287eedb4d773901ecae2 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-11 19:31 UTC · original
On src/graphics/shader/recompiler/ShaderRecompiler.cpp line 548 (outdated):

@@ -480,9 +485,263 @@ Decoder::Program DecodeFusedProgram(std::span<const uint32_t> front, std::span<c
 	return result;
 }
 
+// Research: S_SWAPPC_B64 through a pointer the dispatch passes in user data (a BVH builder calls
+// a per-geometry index-fetch function this way). Each call site gets its own copy of the callee,
+// appended after the program: the call becomes a branch to the copy, which first sets sD to the
+// return address as the call would, and each of the callee's returns (S_SETPC_B64 sD) becomes a
+// branch back to the instruction after the call. Only callees without further calls, S_GETPC_B64
+// or S_ENDPGM are inlined; anything else leaves the call unsupported, as before.
+namespace Sub {
+constexpr uint32_t Sop1Encoding   = 0x17du;
+constexpr uint32_t SoppEncoding   = 0x17fu;
+constexpr uint32_t Mov32          = 0x03u;
+constexpr uint32_t GetPc          = 0x1fu;
+constexpr uint32_t SetPc          = 0x20u;
+constexpr uint32_t SwapPc         = 0x21u;
+constexpr uint32_t EndPgm         = 0x01u;
+constexpr uint32_t NullSgpr       = 125u; // SGPR_NULL: s_swappc_b64 null, sN is a plain jump
+constexpr uint32_t MaxCalleeWords = 16384;
+constexpr uint32_t MaxScanBack    = 64;
+
+bool IsSop1(uint32_t word, uint32_t op) {
+	return (word >> 23u) == Sop1Encoding && ((word >> 8u) & 0xffu) == op;
+}
+bool IsSopp(uint32_t word, uint32_t op) {
+	return (word >> 23u) == SoppEncoding && ((word >> 16u) & 0x7fu) == op;
+}
+uint32_t Sop1Dst(uint32_t word) {
+	return (word >> 16u) & 0x7fu;
+}
+uint32_t Sop1Src(uint32_t word) {
+	return word & 0xffu;
+}
+bool IsCall(uint32_t word) {
+	return IsSop1(word, SwapPc) && Sop1Dst(word) != NullSgpr;
+}
+// A return through `reg`: s_setpc_b64 reg, or s_swappc_b64 null, reg.
+bool IsReturn(uint32_t word, uint32_t reg) {
+	return Sop1Src(word) == reg &&
+	       (IsSop1(word, SetPc) || (IsSop1(word, SwapPc) && Sop1Dst(word) == NullSgpr));
+}
+bool IsJump(uint32_t word) {
+	return IsSop1(word, SetPc) || (IsSop1(word, SwapPc) && Sop1Dst(word) == NullSgpr);
+}
+uint32_t Sop1Word(uint32_t op, uint32_t dst, uint32_t src) {
+	return (Sop1Encoding << 23u) | (dst << 16u) | (op << 8u) | src;
+}
+std::optional<uint32_t> BranchWord(uint32_t from_pc, uint32_t to_pc) {
+	const auto delta = (static_cast<int64_t>(to_pc) - static_cast<int64_t>(from_pc) - 4) / 4;
+	if (delta < INT16_MIN || delta > INT16_MAX) {
+		return std::nullopt;
+	}
+	return 0xbf820000u | (static_cast<uint32_t>(delta) & 0xffffu);
+}
+
+// The user-data dword a straight-line S_MOV_B32 copied into `reg` before instruction `index`.
+std::optional<uint32_t> UserDataSource(const Decoder::Program& program,
+                                       std::span<const uint32_t> code,
+                                       const std::set<uint32_t>& targets, size_t index,
+                                       uint32_t reg, const CompileOptions& options) {
+	const auto writes = [&](const Decoder::Operand& operand) {
+		return operand.kind == Decoder::OperandKind::Sgpr &&
+		       (operand.reg == reg || operand.reg + 1u == reg);
+	};

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

UserDataSource misses writes from multi-dword instructions.

The writes lambda checks only operand.reg == reg and operand.reg + 1u == reg. An instruction that writes more than two SGPRs, such as S_LOAD_DWORDX4 s[8:11], overwrites s10 but does not stop the backward scan. The scan then continues past the overwrite and returns an earlier S_MOV_B32 s10, sN as the source. InlineSubroutineCalls then reads the callee from the wrong user-data address and inlines the wrong code. Before this change, such calls stayed unsupported. Now the GPU runs code the guest did not call, which can hang it.

Use the destination width:

Proposed fix
--- "a/src/graphics/shader/recompiler/ShaderRecompiler.cpp"
+++ "b/src/graphics/shader/recompiler/ShaderRecompiler.cpp"
@@ -542,10 +542,11 @@
                                        std::span<const uint32_t> code,
                                        const std::set<uint32_t>& targets, size_t index,
                                        uint32_t reg, const CompileOptions& options) {
-	const auto writes = [&](const Decoder::Operand& operand) {
-		return operand.kind == Decoder::OperandKind::Sgpr &&
-		       (operand.reg == reg || operand.reg + 1u == reg);
-	};
+	const auto writes = [&](const Decoder::Operand& operand, uint32_t dwords) {
+		const auto width = std::max(dwords, 2u); // 64-bit ops report one dword
+		return operand.kind == Decoder::OperandKind::Sgpr && operand.reg <= reg &&
+		       reg < operand.reg + width;
+	};
 	for (size_t i = index; i-- > 0 && index - i <= MaxScanBack;) {
 		const auto& inst = program.instructions[i];
 		if (Decoder::IsDirectBranch(inst.opcode) || inst.opcode == Decoder::Opcode::S_ENDPGM) {

Then call writes(inst.dst, inst.data_dwords) and writes(inst.dst2, 2u).

**@⁠coderabbitai[bot]** on GitHub · 2026-10-11 19:31 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/937#discussion_r4242913450) On `src/graphics/shader/recompiler/ShaderRecompiler.cpp` line 548 (outdated): ```diff @@ -480,9 +485,263 @@ Decoder::Program DecodeFusedProgram(std::span<const uint32_t> front, std::span<c return result; } +// Research: S_SWAPPC_B64 through a pointer the dispatch passes in user data (a BVH builder calls +// a per-geometry index-fetch function this way). Each call site gets its own copy of the callee, +// appended after the program: the call becomes a branch to the copy, which first sets sD to the +// return address as the call would, and each of the callee's returns (S_SETPC_B64 sD) becomes a +// branch back to the instruction after the call. Only callees without further calls, S_GETPC_B64 +// or S_ENDPGM are inlined; anything else leaves the call unsupported, as before. +namespace Sub { +constexpr uint32_t Sop1Encoding = 0x17du; +constexpr uint32_t SoppEncoding = 0x17fu; +constexpr uint32_t Mov32 = 0x03u; +constexpr uint32_t GetPc = 0x1fu; +constexpr uint32_t SetPc = 0x20u; +constexpr uint32_t SwapPc = 0x21u; +constexpr uint32_t EndPgm = 0x01u; +constexpr uint32_t NullSgpr = 125u; // SGPR_NULL: s_swappc_b64 null, sN is a plain jump +constexpr uint32_t MaxCalleeWords = 16384; +constexpr uint32_t MaxScanBack = 64; + +bool IsSop1(uint32_t word, uint32_t op) { + return (word >> 23u) == Sop1Encoding && ((word >> 8u) & 0xffu) == op; +} +bool IsSopp(uint32_t word, uint32_t op) { + return (word >> 23u) == SoppEncoding && ((word >> 16u) & 0x7fu) == op; +} +uint32_t Sop1Dst(uint32_t word) { + return (word >> 16u) & 0x7fu; +} +uint32_t Sop1Src(uint32_t word) { + return word & 0xffu; +} +bool IsCall(uint32_t word) { + return IsSop1(word, SwapPc) && Sop1Dst(word) != NullSgpr; +} +// A return through `reg`: s_setpc_b64 reg, or s_swappc_b64 null, reg. +bool IsReturn(uint32_t word, uint32_t reg) { + return Sop1Src(word) == reg && + (IsSop1(word, SetPc) || (IsSop1(word, SwapPc) && Sop1Dst(word) == NullSgpr)); +} +bool IsJump(uint32_t word) { + return IsSop1(word, SetPc) || (IsSop1(word, SwapPc) && Sop1Dst(word) == NullSgpr); +} +uint32_t Sop1Word(uint32_t op, uint32_t dst, uint32_t src) { + return (Sop1Encoding << 23u) | (dst << 16u) | (op << 8u) | src; +} +std::optional<uint32_t> BranchWord(uint32_t from_pc, uint32_t to_pc) { + const auto delta = (static_cast<int64_t>(to_pc) - static_cast<int64_t>(from_pc) - 4) / 4; + if (delta < INT16_MIN || delta > INT16_MAX) { + return std::nullopt; + } + return 0xbf820000u | (static_cast<uint32_t>(delta) & 0xffffu); +} + +// The user-data dword a straight-line S_MOV_B32 copied into `reg` before instruction `index`. +std::optional<uint32_t> UserDataSource(const Decoder::Program& program, + std::span<const uint32_t> code, + const std::set<uint32_t>& targets, size_t index, + uint32_t reg, const CompileOptions& options) { + const auto writes = [&](const Decoder::Operand& operand) { + return operand.kind == Decoder::OperandKind::Sgpr && + (operand.reg == reg || operand.reg + 1u == reg); + }; ``` **🎯 Functional Correctness** | **🟠 Major** | **⚡ Quick win** **`UserDataSource` misses writes from multi-dword instructions.** The `writes` lambda checks only `operand.reg == reg` and `operand.reg + 1u == reg`. An instruction that writes more than two SGPRs, such as `S_LOAD_DWORDX4 s[8:11]`, overwrites `s10` but does not stop the backward scan. The scan then continues past the overwrite and returns an earlier `S_MOV_B32 s10, sN` as the source. `InlineSubroutineCalls` then reads the callee from the wrong user-data address and inlines the wrong code. Before this change, such calls stayed unsupported. Now the GPU runs code the guest did not call, which can hang it. Use the destination width: <details> <summary>Proposed fix</summary> ```diff --- "a/src/graphics/shader/recompiler/ShaderRecompiler.cpp" +++ "b/src/graphics/shader/recompiler/ShaderRecompiler.cpp" @@ -542,10 +542,11 @@ std::span<const uint32_t> code, const std::set<uint32_t>& targets, size_t index, uint32_t reg, const CompileOptions& options) { - const auto writes = [&](const Decoder::Operand& operand) { - return operand.kind == Decoder::OperandKind::Sgpr && - (operand.reg == reg || operand.reg + 1u == reg); - }; + const auto writes = [&](const Decoder::Operand& operand, uint32_t dwords) { + const auto width = std::max(dwords, 2u); // 64-bit ops report one dword + return operand.kind == Decoder::OperandKind::Sgpr && operand.reg <= reg && + reg < operand.reg + width; + }; for (size_t i = index; i-- > 0 && index - i <= MaxScanBack;) { const auto& inst = program.instructions[i]; if (Decoder::IsDirectBranch(inst.opcode) || inst.opcode == Decoder::Opcode::S_ENDPGM) { ``` Then call `writes(inst.dst, inst.data_dwords)` and `writes(inst.dst2, 2u)`. </details> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:cc30d4e453ae13213a682b5c --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -548,0 +729,4 @@
const auto command_buffer_addr = reinterpret_cast<uint64_t>(command_buffer);
const auto id =
AprShared::AllocateSubmissionId(command_buffer_addr, reinterpret_cast<uint64_t>(result));
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-11 19:31 UTC · original

🚀 Performance & Scalability | 🟡 Minor | ⚡ Quick win

Submissions with a result but no ID leak their tracking entries.

SubmitCommandBufferAndGetResult always calls AllocateSubmissionId, even when out_submission_id is null. With a null out_submission_id, the guest gets no ID and cannot call WaitCommandBuffer. CompleteSubmission is the only path that erases a completed entry. As a result, every such submission leaves one SubmissionState in g_submissions permanently. A title that submits this way every frame grows the map without bound.

AmmSubmitCommandBufferAndGetResult (lines 3181-3183) has the same defect. The result already reaches the guest through Execute, which calls WriteResult with submission.result. Also, if the final WriteGuest of the ID fails, the entry is never retired.

Allocate an ID only when the caller can receive it. Otherwise pass 0.

Proposed fix
--- "a/src/libs/libAmpr.cpp"
+++ "b/src/libs/libAmpr.cpp"
@@ -741,9 +741,11 @@
 		return KernelSyscallResult(LibKernel::KERNEL_ERROR_EINVAL);
 	}
 
 	const auto command_buffer_addr = reinterpret_cast<uint64_t>(command_buffer);
-	const auto id =
-	    AprShared::AllocateSubmissionId(command_buffer_addr, reinterpret_cast<uint64_t>(result));
+	const auto id = out_submission_id != nullptr
+	                    ? AprShared::AllocateSubmissionId(command_buffer_addr,
+	                                                      reinterpret_cast<uint64_t>(result))
+	                    : 0u;
 
 	const auto submit_result = LibAmpr::Ampr::EnqueueCommandBuffer(
 	    command_buffer_addr, false, static_cast<uint32_t>(priority), id,

Apply the same change in AmmSubmitCommandBufferAndGetResult. Guard each DiscardSubmission(id) call with id != 0.

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

	const auto command_buffer_addr = reinterpret_cast<uint64_t>(command_buffer);
	const auto id = out_submission_id != nullptr
	                    ? AprShared::AllocateSubmissionId(command_buffer_addr,
	                                                      reinterpret_cast<uint64_t>(result))
	                    : 0u;

**@⁠coderabbitai[bot]** on GitHub · 2026-10-11 19:31 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/937#discussion_r4242913452) **🚀 Performance & Scalability** | **🟡 Minor** | **⚡ Quick win** **Submissions with a result but no ID leak their tracking entries.** `SubmitCommandBufferAndGetResult` always calls `AllocateSubmissionId`, even when `out_submission_id` is null. With a null `out_submission_id`, the guest gets no ID and cannot call `WaitCommandBuffer`. `CompleteSubmission` is the only path that erases a completed entry. As a result, every such submission leaves one `SubmissionState` in `g_submissions` permanently. A title that submits this way every frame grows the map without bound. `AmmSubmitCommandBufferAndGetResult` (lines 3181-3183) has the same defect. The result already reaches the guest through `Execute`, which calls `WriteResult` with `submission.result`. Also, if the final `WriteGuest` of the ID fails, the entry is never retired. Allocate an ID only when the caller can receive it. Otherwise pass `0`. <details> <summary>Proposed fix</summary> ```diff --- "a/src/libs/libAmpr.cpp" +++ "b/src/libs/libAmpr.cpp" @@ -741,9 +741,11 @@ return KernelSyscallResult(LibKernel::KERNEL_ERROR_EINVAL); } const auto command_buffer_addr = reinterpret_cast<uint64_t>(command_buffer); - const auto id = - AprShared::AllocateSubmissionId(command_buffer_addr, reinterpret_cast<uint64_t>(result)); + const auto id = out_submission_id != nullptr + ? AprShared::AllocateSubmissionId(command_buffer_addr, + reinterpret_cast<uint64_t>(result)) + : 0u; const auto submit_result = LibAmpr::Ampr::EnqueueCommandBuffer( command_buffer_addr, false, static_cast<uint32_t>(priority), id, ``` Apply the same change in `AmmSubmitCommandBufferAndGetResult`. Guard each `DiscardSubmission(id)` call with `id != 0`. </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 const auto command_buffer_addr = reinterpret_cast<uint64_t>(command_buffer); const auto id = out_submission_id != nullptr ? AprShared::AllocateSubmissionId(command_buffer_addr, reinterpret_cast<uint64_t>(result)) : 0u; ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:b8518ec94e3486fa5c7f2ec5 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-11 19:31 UTC · original
On src/libs/libAudio2.cpp line 599 (outdated):

@@ -513,42 +529,89 @@ int KYTY_SYSV_ABI AudioOut2ContextAdvance(AudioOut2ContextHandle ctx) {
 	return OK;
 }
 
-int KYTY_SYSV_ABI AudioOut2ContextPush(AudioOut2ContextHandle ctx, uint32_t blocking) {
-	uint32_t sleep_micros = audioout2_grain_micros(512);
+// Queue time SDL may hold beyond the queue depth before it counts.
+constexpr uint64_t AUDIOOUT2_DEVICE_CUSHION_US = 20000;
+
+// Microseconds the context's device still has to play (its first port with PCM and a device), or
+// -1 when it has none: then the timer model applies.
+static int64_t audioout2_device_queued_us(AudioOut2ContextHandle ctx) {
+	int handle = 0;
+	{
+		Common::LockGuard lock(g_audioout2_port_mutex);
+		for (const auto& state: g_audioout2_ports) {
+			if (state.used && state.context == ctx && state.audio_handle > 0 &&
+			    !state.pcm_data.empty()) {
+				handle = state.audio_handle;
+				break;
+			}
+		}
+	}
+	return handle > 0 ? AudioInternal::AudioOutQueuedUs(handle) : -1;
+}
+
+// Caller holds g_audioout2_context_mutex. The level from the device's queue, or from the timer.
+static uint32_t audioout2_level_locked(AudioOut2ContextState* state, int64_t device_queued_us) {
+	if (device_queued_us < 0) {
+		audioout2_update_context_locked(state);
+		return state->queued;
+	}
+	const auto grain_us = static_cast<uint64_t>(audioout2_grain_micros(state->num_grains));
+	const auto beyond   = static_cast<uint64_t>(device_queued_us) > AUDIOOUT2_DEVICE_CUSHION_US
+	                          ? static_cast<uint64_t>(device_queued_us) - AUDIOOUT2_DEVICE_CUSHION_US
+	                          : 0;
+	state->queued      = static_cast<uint32_t>(
+        std::min<uint64_t>((beyond + grain_us - 1) / grain_us, state->queue_depth));
+	state->last_update = LibKernel::KernelGetProcessTime();
+	return state->queued;
+}
 
+static int audioout2_push_device_queue(AudioOut2ContextHandle ctx, uint32_t blocking) {
 	for (;;) {
-		// Only a synchronous submission carrying PCM to a real device can rely on the SDL queue for
-		// pacing. Async pushes must retain queue-depth backpressure, and a handle without PCM (or a
-		// vibration/failed-open handle) has no downstream operation that can block this call.
-		const bool use_device_clock =
-		    blocking != 0 && audioout2_context_has_queueable_device(ctx);
+		const auto device_us = audioout2_device_queued_us(ctx);
 
 		g_audioout2_context_mutex.Lock();
-		if (auto* state = audioout2_find_context_locked(ctx); state != nullptr) {
-			audioout2_update_context_locked(state);
-			sleep_micros = audioout2_grain_micros(state->num_grains);
-			if (state->queued < state->queue_depth || use_device_clock) {
-				if (state->queued == 0) {
-					state->last_update = LibKernel::KernelGetProcessTime();
-				}
-				if (state->queued < state->queue_depth) {
-					state->queued++;
+		auto* state = audioout2_find_context_locked(ctx);
+		if (state == nullptr) {
+			g_audioout2_context_mutex.Unlock();
+			return AUDIO_OUT2_ERROR_INVALID_PARAM;
+		}
+		const auto level = audioout2_level_locked(state, device_us);
+		if (level < state->queue_depth) {
+			if (device_us < 0 && state->queued == 0) {
+				state->last_update = LibKernel::KernelGetProcessTime();
+			}
+			state->queued++;
+			const auto depth = state->queue_depth;
+			const auto grain = state->num_grains;
+			g_audioout2_context_mutex.Unlock();
+			// The level paces the pushes: the device takes the grain at once.
+			audioout2_queue_context_audio(ctx, device_us < 0 && blocking != 0);
+			// A blocking push returns once the queue has room for the next grain.
+			if (blocking != 0 && device_us >= 0) {
+				const auto grain_us  = static_cast<uint64_t>(audioout2_grain_micros(grain));
+				const auto cushion   = AUDIOOUT2_DEVICE_CUSHION_US;
+				const auto full_us   = cushion + (depth - 1) * grain_us;
+				for (int64_t queued_us = audioout2_device_queued_us(ctx);
+				     queued_us >= 0 && static_cast<uint64_t>(queued_us) > full_us;
+				     queued_us = audioout2_device_queued_us(ctx)) {
+					Common::Thread::SleepMicro(500);
 				}
-				g_audioout2_context_mutex.Unlock();
-				audioout2_queue_context_audio(ctx, blocking != 0);
-				return OK;
 			}

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Blocking device pushes can wait forever if the device stops draining.

A device-backed push now calls AudioOutOutputs with blocking == false. This bypasses the 200 ms SDL_ClearAudioStream fallback in Audio::QueueSdlAudio. After that, the loop at lines 594-598 sleeps until AudioOutQueuedUs drops to full_us or below. The loop has no timeout.

The SDL queue stops draining in these cases:

  • The audio device is lost.
  • The audio device is paused.
  • Device migration stalls.

In those cases the queued time stays above full_us. The guest audio thread then hangs inside AudioOut2ContextPush. The outer loop at lines 569-608 has the same problem: while the device level stays at queue_depth, a blocking push sleeps in 1 ms steps indefinitely.

Add a deadline to both waits, for example about 200 ms, to match the old backend behavior. When the deadline passes, return or clear the stream.

Proposed fix (post-push wait)
-				for (int64_t queued_us = audioout2_device_queued_us(ctx);
-				     queued_us >= 0 && static_cast<uint64_t>(queued_us) > full_us;
-				     queued_us = audioout2_device_queued_us(ctx)) {
+				const auto deadline = LibKernel::KernelGetProcessTime() + 200000;
+				for (int64_t queued_us = audioout2_device_queued_us(ctx);
+				     queued_us >= 0 && static_cast<uint64_t>(queued_us) > full_us &&
+				     LibKernel::KernelGetProcessTime() < deadline;
+				     queued_us = audioout2_device_queued_us(ctx)) {
 					Common::Thread::SleepMicro(500);
 				}
📝 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.

			audioout2_queue_context_audio(ctx, device_us < 0 && blocking != 0);
			// A blocking push returns once the queue has room for the next grain.
			if (blocking != 0 && device_us >= 0) {
				const auto grain_us  = static_cast<uint64_t>(audioout2_grain_micros(grain));
				const auto cushion   = AUDIOOUT2_DEVICE_CUSHION_US;
				const auto full_us   = cushion + (depth - 1) * grain_us;
				const auto deadline = LibKernel::KernelGetProcessTime() + 200000;
				for (int64_t queued_us = audioout2_device_queued_us(ctx);
				     queued_us >= 0 && static_cast<uint64_t>(queued_us) > full_us &&
				     LibKernel::KernelGetProcessTime() < deadline;
				     queued_us = audioout2_device_queued_us(ctx)) {
					Common::Thread::SleepMicro(500);
				}
			}
**@⁠coderabbitai[bot]** on GitHub · 2026-10-11 19:31 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/937#discussion_r4242913459) On `src/libs/libAudio2.cpp` line 599 (outdated): ```diff @@ -513,42 +529,89 @@ int KYTY_SYSV_ABI AudioOut2ContextAdvance(AudioOut2ContextHandle ctx) { return OK; } -int KYTY_SYSV_ABI AudioOut2ContextPush(AudioOut2ContextHandle ctx, uint32_t blocking) { - uint32_t sleep_micros = audioout2_grain_micros(512); +// Queue time SDL may hold beyond the queue depth before it counts. +constexpr uint64_t AUDIOOUT2_DEVICE_CUSHION_US = 20000; + +// Microseconds the context's device still has to play (its first port with PCM and a device), or +// -1 when it has none: then the timer model applies. +static int64_t audioout2_device_queued_us(AudioOut2ContextHandle ctx) { + int handle = 0; + { + Common::LockGuard lock(g_audioout2_port_mutex); + for (const auto& state: g_audioout2_ports) { + if (state.used && state.context == ctx && state.audio_handle > 0 && + !state.pcm_data.empty()) { + handle = state.audio_handle; + break; + } + } + } + return handle > 0 ? AudioInternal::AudioOutQueuedUs(handle) : -1; +} + +// Caller holds g_audioout2_context_mutex. The level from the device's queue, or from the timer. +static uint32_t audioout2_level_locked(AudioOut2ContextState* state, int64_t device_queued_us) { + if (device_queued_us < 0) { + audioout2_update_context_locked(state); + return state->queued; + } + const auto grain_us = static_cast<uint64_t>(audioout2_grain_micros(state->num_grains)); + const auto beyond = static_cast<uint64_t>(device_queued_us) > AUDIOOUT2_DEVICE_CUSHION_US + ? static_cast<uint64_t>(device_queued_us) - AUDIOOUT2_DEVICE_CUSHION_US + : 0; + state->queued = static_cast<uint32_t>( + std::min<uint64_t>((beyond + grain_us - 1) / grain_us, state->queue_depth)); + state->last_update = LibKernel::KernelGetProcessTime(); + return state->queued; +} +static int audioout2_push_device_queue(AudioOut2ContextHandle ctx, uint32_t blocking) { for (;;) { - // Only a synchronous submission carrying PCM to a real device can rely on the SDL queue for - // pacing. Async pushes must retain queue-depth backpressure, and a handle without PCM (or a - // vibration/failed-open handle) has no downstream operation that can block this call. - const bool use_device_clock = - blocking != 0 && audioout2_context_has_queueable_device(ctx); + const auto device_us = audioout2_device_queued_us(ctx); g_audioout2_context_mutex.Lock(); - if (auto* state = audioout2_find_context_locked(ctx); state != nullptr) { - audioout2_update_context_locked(state); - sleep_micros = audioout2_grain_micros(state->num_grains); - if (state->queued < state->queue_depth || use_device_clock) { - if (state->queued == 0) { - state->last_update = LibKernel::KernelGetProcessTime(); - } - if (state->queued < state->queue_depth) { - state->queued++; + auto* state = audioout2_find_context_locked(ctx); + if (state == nullptr) { + g_audioout2_context_mutex.Unlock(); + return AUDIO_OUT2_ERROR_INVALID_PARAM; + } + const auto level = audioout2_level_locked(state, device_us); + if (level < state->queue_depth) { + if (device_us < 0 && state->queued == 0) { + state->last_update = LibKernel::KernelGetProcessTime(); + } + state->queued++; + const auto depth = state->queue_depth; + const auto grain = state->num_grains; + g_audioout2_context_mutex.Unlock(); + // The level paces the pushes: the device takes the grain at once. + audioout2_queue_context_audio(ctx, device_us < 0 && blocking != 0); + // A blocking push returns once the queue has room for the next grain. + if (blocking != 0 && device_us >= 0) { + const auto grain_us = static_cast<uint64_t>(audioout2_grain_micros(grain)); + const auto cushion = AUDIOOUT2_DEVICE_CUSHION_US; + const auto full_us = cushion + (depth - 1) * grain_us; + for (int64_t queued_us = audioout2_device_queued_us(ctx); + queued_us >= 0 && static_cast<uint64_t>(queued_us) > full_us; + queued_us = audioout2_device_queued_us(ctx)) { + Common::Thread::SleepMicro(500); } - g_audioout2_context_mutex.Unlock(); - audioout2_queue_context_audio(ctx, blocking != 0); - return OK; } ``` **🩺 Stability & Availability** | **🟠 Major** | **⚡ Quick win** **Blocking device pushes can wait forever if the device stops draining.** A device-backed push now calls `AudioOutOutputs` with `blocking == false`. This bypasses the 200 ms `SDL_ClearAudioStream` fallback in `Audio::QueueSdlAudio`. After that, the loop at lines 594-598 sleeps until `AudioOutQueuedUs` drops to `full_us` or below. The loop has no timeout. The SDL queue stops draining in these cases: - The audio device is lost. - The audio device is paused. - Device migration stalls. In those cases the queued time stays above `full_us`. The guest audio thread then hangs inside `AudioOut2ContextPush`. The outer loop at lines 569-608 has the same problem: while the device level stays at `queue_depth`, a blocking push sleeps in 1 ms steps indefinitely. Add a deadline to both waits, for example about 200 ms, to match the old backend behavior. When the deadline passes, return or clear the stream. <details> <summary>Proposed fix (post-push wait)</summary> ```diff - for (int64_t queued_us = audioout2_device_queued_us(ctx); - queued_us >= 0 && static_cast<uint64_t>(queued_us) > full_us; - queued_us = audioout2_device_queued_us(ctx)) { + const auto deadline = LibKernel::KernelGetProcessTime() + 200000; + for (int64_t queued_us = audioout2_device_queued_us(ctx); + queued_us >= 0 && static_cast<uint64_t>(queued_us) > full_us && + LibKernel::KernelGetProcessTime() < deadline; + queued_us = audioout2_device_queued_us(ctx)) { Common::Thread::SleepMicro(500); } ``` </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 audioout2_queue_context_audio(ctx, device_us < 0 && blocking != 0); // A blocking push returns once the queue has room for the next grain. if (blocking != 0 && device_us >= 0) { const auto grain_us = static_cast<uint64_t>(audioout2_grain_micros(grain)); const auto cushion = AUDIOOUT2_DEVICE_CUSHION_US; const auto full_us = cushion + (depth - 1) * grain_us; const auto deadline = LibKernel::KernelGetProcessTime() + 200000; for (int64_t queued_us = audioout2_device_queued_us(ctx); queued_us >= 0 && static_cast<uint64_t>(queued_us) > full_us && LibKernel::KernelGetProcessTime() < deadline; queued_us = audioout2_device_queued_us(ctx)) { Common::Thread::SleepMicro(500); } } ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:a27152a411159d7022841405 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-11 19:31 UTC · original · reviewed

Actionable comments posted: 11

🧹 Nitpick comments (1)
tests/X64LoadEmulationTests.cpp (1)

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

Initialize vec with a value that a non-merging write would change.

In Result, vec starts as zeros. The VEC cases write the full YMM register into r.vec, so these initial zeros are never compared. That part is correct. The GPR cases have a gap, though. They check only gpr[0]. The FLAGS cases write only flags, and the flags mask hides every bit outside OF/SF/ZF/AF/PF/CF. As a result, this test cannot detect emulation that corrupts other registers, for example clobbering RSI or RDX. The emulator under test writes directly into CONTEXT.

This is a coverage gap, not a defect. Consider recording RSI and RDX after each case.


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 574f992b-462b-4755-b7bd-dcba69b1b021
📥 Commits

Reviewing files that changed from the base of the PR and between cc6c83e34c404e2197c4d7b7c5ddc217b8ccda9c and 41c7b27b738ce882c93108e8b882405e33a78d8d.

📒 Files selected for processing (122)
  • CMakeLists.txt
  • src/common/CMakeLists.txt
  • src/common/emulatorConfig.cpp
  • src/common/emulatorConfig.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/graphicContext.h
  • src/graphics/host_gpu/memoryTracker.cpp
  • src/graphics/host_gpu/memoryTracker.h
  • src/graphics/host_gpu/pageManager.cpp
  • src/graphics/host_gpu/pageManager.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/faultManager.h
  • src/graphics/host_gpu/renderer/cache/streamBuffer.h
  • 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/context.cpp
  • src/graphics/host_gpu/renderer/image/image.h
  • src/graphics/host_gpu/renderer/image/imageInfo.h
  • src/graphics/host_gpu/renderer/image/imageView.h
  • src/graphics/host_gpu/renderer/indirectDispatch.cpp
  • src/graphics/host_gpu/renderer/indirectDispatch.h
  • src/graphics/host_gpu/renderer/pipeline/bindlessTable.cpp
  • src/graphics/host_gpu/renderer/pipeline/bindlessTable.h
  • src/graphics/host_gpu/renderer/pipeline/descriptors.cpp
  • src/graphics/host_gpu/renderer/pipeline/descriptors.h
  • src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp
  • src/graphics/host_gpu/renderer/pipeline/pipelineCache.h
  • src/graphics/host_gpu/renderer/pipeline/shaders.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/shaders/dispatch_indirect_groups.comp
  • src/graphics/presentation/window/vulkanWindow.cpp
  • src/graphics/shader/recompiler/ShaderRecompiler.cpp
  • src/graphics/shader/recompiler/ShaderRecompiler.h
  • src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.cpp
  • src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.h
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterAnalysis.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterFlow.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterHelpers.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.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/spirvEmitterMesh.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterModule.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp
  • src/graphics/shader/recompiler/frontend/cfg/ShaderCFG.cpp
  • src/graphics/shader/recompiler/frontend/decode/ImageOps.cpp
  • src/graphics/shader/recompiler/frontend/decode/MemoryOps.cpp
  • src/graphics/shader/recompiler/frontend/decode/ScalarAluOps.cpp
  • src/graphics/shader/recompiler/frontend/decode/ShaderDecoder.cpp
  • src/graphics/shader/recompiler/frontend/decode/ShaderDecoder.h
  • src/graphics/shader/recompiler/frontend/decode/VectorAluOps.cpp
  • src/graphics/shader/recompiler/frontend/translate/Bvh.cpp
  • src/graphics/shader/recompiler/frontend/translate/Compare.cpp
  • src/graphics/shader/recompiler/frontend/translate/Control.cpp
  • src/graphics/shader/recompiler/frontend/translate/Memory.cpp
  • src/graphics/shader/recompiler/frontend/translate/Scalar.cpp
  • src/graphics/shader/recompiler/frontend/translate/Translate.cpp
  • src/graphics/shader/recompiler/frontend/translate/Translator.h
  • src/graphics/shader/recompiler/frontend/translate/Vector.cpp
  • src/graphics/shader/recompiler/ir/BindlessBindings.h
  • src/graphics/shader/recompiler/ir/Program.cpp
  • src/graphics/shader/recompiler/ir/ResourceSnapshot.h
  • src/graphics/shader/recompiler/ir/ShaderIR.h
  • src/graphics/shader/recompiler/ir/Value.cpp
  • src/graphics/shader/recompiler/ir/Value.h
  • src/graphics/shader/recompiler/ir/opcodes/ValueOpcodes.cpp
  • src/graphics/shader/recompiler/ir/opcodes/ValueOpcodes.inc
  • src/graphics/shader/recompiler/ir/passes/BindingLayout.cpp
  • src/graphics/shader/recompiler/ir/passes/ConstantPropagation.cpp
  • src/graphics/shader/recompiler/ir/passes/ConstantPropagation.h
  • src/graphics/shader/recompiler/ir/passes/DeadCodeElimination.cpp
  • src/graphics/shader/recompiler/ir/passes/DeadCodeElimination.h
  • src/graphics/shader/recompiler/ir/passes/LocalAddressStores.cpp
  • src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp
  • src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.h
  • src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp
  • src/graphics/shader/recompiler/ir/passes/ShaderInfoCollection.cpp
  • src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp
  • src/graphics/shader/recompiler/ir/passes/SrtWalker.h
  • src/graphics/shader/shader.cpp
  • src/graphics/shader/shader.h
  • src/kernel/eventQueue.cpp
  • src/kernel/fileSystem.cpp
  • src/kernel/fileSystem.h
  • src/kernel/memory.cpp
  • src/kernel/memory.h
  • src/kernel/memoryAddressSpace.inc
  • src/launcher/forms/configuration_edit_dialog.ui
  • src/launcher/include/configuration.h
  • src/launcher/src/configurationEditDialog.cpp
  • src/launcher/src/mainDialog.cpp
  • src/libs/agc.cpp
  • src/libs/audio.cpp
  • src/libs/audio_internal.h
  • src/libs/dialog.cpp
  • src/libs/libAmpr.cpp
  • src/libs/libAudio2.cpp
  • src/libs/libKernel.cpp
  • src/libs/libNet.cpp
  • src/loader/runtimeLinker.cpp
  • src/loader/x64InstructionEmulator.cpp
  • src/loader/x64InstructionEmulator.h
  • src/main.cpp
  • tests/AudioOut2PortTests.cpp
  • tests/ResourceTrackingTests.cpp
  • tests/ScalarProvenanceTests.cpp
  • tests/ShaderRayTracingTests.inc
  • tests/ShaderRecompilerComputeTests.cpp
  • tests/X64LoadEmulationTests.cpp
  • tests/shaderCfgTests.cpp
💤 Files with no reviewable changes (1)
  • src/graphics/shader/recompiler/ir/Value.cpp

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

**@⁠coderabbitai[bot]** on GitHub · 2026-10-11 19:31 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/937#pullrequestreview-5484636469) · **reviewed** **Actionable comments posted: 11** <details> <summary>🧹 Nitpick comments (1)</summary><blockquote> <details> <summary>tests/X64LoadEmulationTests.cpp (1)</summary><blockquote> `65-65`: **📐 Maintainability & Code Quality** | **🔵 Trivial** | **💤 Low value** **Initialize `vec` with a value that a non-merging write would change.** In `Result`, `vec` starts as zeros. The VEC cases write the full YMM register into `r.vec`, so these initial zeros are never compared. That part is correct. The GPR cases have a gap, though. They check only `gpr[0]`. The FLAGS cases write only `flags`, and the `flags` mask hides every bit outside OF/SF/ZF/AF/PF/CF. As a result, this test cannot detect emulation that corrupts other registers, for example clobbering RSI or RDX. The emulator under test writes directly into `CONTEXT`. This is a coverage gap, not a defect. Consider recording RSI and RDX after each case. <!-- cr-comment:v1:35883651b921586619a90f9a --> </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**: `574f992b-462b-4755-b7bd-dcba69b1b021` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between cc6c83e34c404e2197c4d7b7c5ddc217b8ccda9c and 41c7b27b738ce882c93108e8b882405e33a78d8d. </details> <details> <summary>📒 Files selected for processing (122)</summary> * `CMakeLists.txt` * `src/common/CMakeLists.txt` * `src/common/emulatorConfig.cpp` * `src/common/emulatorConfig.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/graphicContext.h` * `src/graphics/host_gpu/memoryTracker.cpp` * `src/graphics/host_gpu/memoryTracker.h` * `src/graphics/host_gpu/pageManager.cpp` * `src/graphics/host_gpu/pageManager.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/faultManager.h` * `src/graphics/host_gpu/renderer/cache/streamBuffer.h` * `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/context.cpp` * `src/graphics/host_gpu/renderer/image/image.h` * `src/graphics/host_gpu/renderer/image/imageInfo.h` * `src/graphics/host_gpu/renderer/image/imageView.h` * `src/graphics/host_gpu/renderer/indirectDispatch.cpp` * `src/graphics/host_gpu/renderer/indirectDispatch.h` * `src/graphics/host_gpu/renderer/pipeline/bindlessTable.cpp` * `src/graphics/host_gpu/renderer/pipeline/bindlessTable.h` * `src/graphics/host_gpu/renderer/pipeline/descriptors.cpp` * `src/graphics/host_gpu/renderer/pipeline/descriptors.h` * `src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp` * `src/graphics/host_gpu/renderer/pipeline/pipelineCache.h` * `src/graphics/host_gpu/renderer/pipeline/shaders.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/shaders/dispatch_indirect_groups.comp` * `src/graphics/presentation/window/vulkanWindow.cpp` * `src/graphics/shader/recompiler/ShaderRecompiler.cpp` * `src/graphics/shader/recompiler/ShaderRecompiler.h` * `src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.cpp` * `src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.h` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterAnalysis.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterFlow.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterHelpers.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.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/spirvEmitterMesh.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterModule.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp` * `src/graphics/shader/recompiler/frontend/cfg/ShaderCFG.cpp` * `src/graphics/shader/recompiler/frontend/decode/ImageOps.cpp` * `src/graphics/shader/recompiler/frontend/decode/MemoryOps.cpp` * `src/graphics/shader/recompiler/frontend/decode/ScalarAluOps.cpp` * `src/graphics/shader/recompiler/frontend/decode/ShaderDecoder.cpp` * `src/graphics/shader/recompiler/frontend/decode/ShaderDecoder.h` * `src/graphics/shader/recompiler/frontend/decode/VectorAluOps.cpp` * `src/graphics/shader/recompiler/frontend/translate/Bvh.cpp` * `src/graphics/shader/recompiler/frontend/translate/Compare.cpp` * `src/graphics/shader/recompiler/frontend/translate/Control.cpp` * `src/graphics/shader/recompiler/frontend/translate/Memory.cpp` * `src/graphics/shader/recompiler/frontend/translate/Scalar.cpp` * `src/graphics/shader/recompiler/frontend/translate/Translate.cpp` * `src/graphics/shader/recompiler/frontend/translate/Translator.h` * `src/graphics/shader/recompiler/frontend/translate/Vector.cpp` * `src/graphics/shader/recompiler/ir/BindlessBindings.h` * `src/graphics/shader/recompiler/ir/Program.cpp` * `src/graphics/shader/recompiler/ir/ResourceSnapshot.h` * `src/graphics/shader/recompiler/ir/ShaderIR.h` * `src/graphics/shader/recompiler/ir/Value.cpp` * `src/graphics/shader/recompiler/ir/Value.h` * `src/graphics/shader/recompiler/ir/opcodes/ValueOpcodes.cpp` * `src/graphics/shader/recompiler/ir/opcodes/ValueOpcodes.inc` * `src/graphics/shader/recompiler/ir/passes/BindingLayout.cpp` * `src/graphics/shader/recompiler/ir/passes/ConstantPropagation.cpp` * `src/graphics/shader/recompiler/ir/passes/ConstantPropagation.h` * `src/graphics/shader/recompiler/ir/passes/DeadCodeElimination.cpp` * `src/graphics/shader/recompiler/ir/passes/DeadCodeElimination.h` * `src/graphics/shader/recompiler/ir/passes/LocalAddressStores.cpp` * `src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp` * `src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.h` * `src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp` * `src/graphics/shader/recompiler/ir/passes/ShaderInfoCollection.cpp` * `src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp` * `src/graphics/shader/recompiler/ir/passes/SrtWalker.h` * `src/graphics/shader/shader.cpp` * `src/graphics/shader/shader.h` * `src/kernel/eventQueue.cpp` * `src/kernel/fileSystem.cpp` * `src/kernel/fileSystem.h` * `src/kernel/memory.cpp` * `src/kernel/memory.h` * `src/kernel/memoryAddressSpace.inc` * `src/launcher/forms/configuration_edit_dialog.ui` * `src/launcher/include/configuration.h` * `src/launcher/src/configurationEditDialog.cpp` * `src/launcher/src/mainDialog.cpp` * `src/libs/agc.cpp` * `src/libs/audio.cpp` * `src/libs/audio_internal.h` * `src/libs/dialog.cpp` * `src/libs/libAmpr.cpp` * `src/libs/libAudio2.cpp` * `src/libs/libKernel.cpp` * `src/libs/libNet.cpp` * `src/loader/runtimeLinker.cpp` * `src/loader/x64InstructionEmulator.cpp` * `src/loader/x64InstructionEmulator.h` * `src/main.cpp` * `tests/AudioOut2PortTests.cpp` * `tests/ResourceTrackingTests.cpp` * `tests/ScalarProvenanceTests.cpp` * `tests/ShaderRayTracingTests.inc` * `tests/ShaderRecompilerComputeTests.cpp` * `tests/X64LoadEmulationTests.cpp` * `tests/shaderCfgTests.cpp` </details> <details> <summary>💤 Files with no reviewable changes (1)</summary> * src/graphics/shader/recompiler/ir/Value.cpp </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 6 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
This pull request has changes conflicting with the target branch.
  • src/common/CMakeLists.txt
  • src/common/assert.cpp
  • src/common/assert.h
  • src/common/emulatorConfig.cpp
  • src/common/emulatorConfig.h
  • src/common/threads.cpp
  • 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/graphicContext.h
  • src/graphics/host_gpu/renderer/cache/bufferCache.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/context.cpp
  • src/graphics/host_gpu/renderer/depthRenderTarget.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/pipeline/pipelineCache.h
  • src/graphics/host_gpu/renderer/pipeline/shaderResourceBarrier.cpp
  • src/graphics/host_gpu/renderer/pipeline/shaders.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/renderDraw.cpp
  • src/graphics/host_gpu/renderer/sync.cpp
  • src/graphics/presentation/window/swapchain.cpp
  • src/graphics/presentation/window/vulkanWindow.cpp
  • src/graphics/shader/recompiler/ShaderRecompiler.cpp
  • src/graphics/shader/recompiler/Tessellation.cpp
  • src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterAlu.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterAluHelpers.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterFlow.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.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/translate/Memory.cpp
  • src/graphics/shader/recompiler/frontend/translate/Scalar.cpp
  • src/graphics/shader/recompiler/ir/ShaderIR.h
  • src/graphics/shader/recompiler/ir/opcodes/ValueOpcodes.inc
  • src/graphics/shader/recompiler/ir/passes/ReadLaneElimination.cpp
  • src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp
  • src/graphics/shader/recompiler/ir/passes/ResourceMaterialization.h
  • src/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp
  • src/graphics/shader/recompiler/ir/passes/ResourceTracking.h
  • src/graphics/shader/recompiler/ir/passes/ShaderInfoCollection.cpp
  • src/graphics/shader/recompiler/ir/passes/SrtWalker.cpp
  • src/graphics/shader/recompiler/ir/passes/SrtWalker.h
  • src/graphics/shader/shader.cpp
  • src/graphics/shader/shaderCompiler.h
  • src/kernel/eventQueue.cpp
  • src/kernel/fileSystem.cpp
  • src/kernel/memory.cpp
  • src/kernel/memory.h
  • src/kernel/pthread.cpp
  • src/libs/acm.cpp
  • src/libs/ajm/atrac9_decoder.h
  • src/libs/ajm/opus_decoder.h
  • src/libs/libAmpr.cpp
  • src/libs/libKernel.cpp
  • src/libs/libNet.cpp
  • src/libs/libSaveData.cpp
  • src/main.cpp
  • tests/ScalarProvenanceTests.cpp
  • tests/ShaderRecompilerComputeTests.cpp
  • tests/shaderCfgTests.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/937/head:github-bot/gh-937'
git switch 'github-bot/gh-937'

Merge

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