shader: implement S_MEMREALTIME (SMEM 0x25) #601

Closed
github-bot wants to merge 1 commit from gh-pr/601/head into gh-pr/601/base
Owner

@⁠maximeallanic on GitHub · 2026-09-13 11:30 UTC · original
maximeallanic:smem-memrealtime → main · +157 −1 · 18 files · 1 commits · closed without merging

Ratchet & Clank: Rift Apart (PPSA01474, v01.005.003) stops during shader recompilation on a missing SMEM opcode:

ShaderRecompiler CS failed hash=0x46fa6901a17c4c27: unsupported decoded instruction in CFG
at pc 0x00000004: unsupported family=SMEM opcode=0x25 reason=SMEM opcode is not implemented

SMEM 0x25 is S_MEMREALTIME. Per the AMD ISA it "reads a 64-bit real time-counter and returns the value into a pair of SGPRS: SDST and SDST+1. The time value is from a constant 25MHz clock".

What this does

  • Decoder: S_MEMREALTIME in the SMEM table (2 dwords, no memory operands). The ISA only defines the result for an even SDST, so an odd SDST stays unsupported.
  • IR: GetRealTimeCounter(dword) reads the counter, and the side-effecting MarkRealTimeCounterRead records that an invocation has read it.
  • Bindings: two shader-data dwords are reserved after the packed memory offsets, only for shaders that use the counter.
  • Renderer: RebindBuffers samples KernelGetProcessTimeCounter — the clock the title already observes — rescaled to 25 MHz with integer arithmetic, for every draw and dispatch.
  • SPIR-V: the counter is read through EmitShaderDataDwordLoad, like user data.

The part I would like your opinion on

The failing shader does not read the clock once. It reads the clock, reads a budget from its own buffer, and then loops re-reading the clock until the deadline passes:

start = realtime(); deadline = start + budget
while (realtime() < deadline) { work }

A Vulkan shader cannot observe time passing while it runs. With a counter sampled once per dispatch that loop never exits: the GPU hangs and the driver resets (vkQueueSubmit failed: ErrorDeviceLost, nvlddmkm event 153 on Windows).

So this models the counter inside an invocation: the first read returns the sampled time and every later read returns UINT64_MAX, which retires a deadline loop after one pass instead of spinning forever. It invents no duration, but a title does get one pass of work per dispatch where hardware would get many.

Other models exist (advance by an estimated per-iteration cost, or calibrate from the measured duration of the previous dispatch). I picked the one that cannot hang and invents no number, but this is a semantic decision and I would rather follow your preference than impose mine.

Testing

Windows 11, RTX 4070, local build of d3d7bd3, PPSA01474:

build compute shaders compiled result
upstream 11 stops on the missing opcode
counter sampled per dispatch only 17 GPU hang, driver reset
this PR 34 no hang, no driver reset

shader_cfg_tests passes, including a new case covering the decode, the IR lowering, the reserved shader-data dwords, the read marker and SPIR-V validation.

The title still renders nothing. With this change it stops later, in resource tracking, with GetBufferResource dword 2 is not a valid runtime value (hash=0xf8bcd41f5f36626d): that shader builds its whole buffer descriptor in VGPRs from a BUFFER_LOAD_DWORD and an emulated unsigned division, then makes it wave-uniform with V_READFIRSTLANE_B32. That looks like a second shape of #507, and I have not touched it here.

AI disclosure

This change was implemented with AI assistance (Claude): reading the AMD ISA to identify the opcode, writing the patch, and analysing the logs and the failing shader. I reviewed the change, built it, and ran the shader tests myself on the machine described above, and I am responsible for what it does.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Added support for shader real-time counter reads.
    • Real-time counter values are sampled consistently per shader invocation.
    • Added handling for the new real-time memory instruction across shader compilation and execution.
  • Bug Fixes
    • Subsequent real-time counter reads now return a terminal value, helping deadline-based shader loops complete reliably.
  • Tests
    • Added coverage validating decoding, intermediate representation, resource layout, and SPIR-V output.
**@⁠maximeallanic** on GitHub · 2026-09-13 11:30 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/601) `maximeallanic:smem-memrealtime` → `main` · +157 −1 · 18 files · 1 commits · closed without merging Ratchet & Clank: Rift Apart (PPSA01474, v01.005.003) stops during shader recompilation on a missing SMEM opcode: ``` ShaderRecompiler CS failed hash=0x46fa6901a17c4c27: unsupported decoded instruction in CFG at pc 0x00000004: unsupported family=SMEM opcode=0x25 reason=SMEM opcode is not implemented ``` SMEM 0x25 is `S_MEMREALTIME`. Per the AMD ISA it "reads a 64-bit real time-counter and returns the value into a pair of SGPRS: SDST and SDST+1. The time value is from a constant 25MHz clock". ### What this does * Decoder: `S_MEMREALTIME` in the SMEM table (2 dwords, no memory operands). The ISA only defines the result for an even SDST, so an odd SDST stays unsupported. * IR: `GetRealTimeCounter(dword)` reads the counter, and the side-effecting `MarkRealTimeCounterRead` records that an invocation has read it. * Bindings: two shader-data dwords are reserved after the packed memory offsets, only for shaders that use the counter. * Renderer: `RebindBuffers` samples `KernelGetProcessTimeCounter` — the clock the title already observes — rescaled to 25 MHz with integer arithmetic, for every draw and dispatch. * SPIR-V: the counter is read through `EmitShaderDataDwordLoad`, like user data. ### The part I would like your opinion on The failing shader does not read the clock once. It reads the clock, reads a budget from its own buffer, and then loops re-reading the clock until the deadline passes: ``` start = realtime(); deadline = start + budget while (realtime() < deadline) { work } ``` A Vulkan shader cannot observe time passing while it runs. With a counter sampled once per dispatch that loop never exits: the GPU hangs and the driver resets (`vkQueueSubmit failed: ErrorDeviceLost`, `nvlddmkm` event 153 on Windows). So this models the counter inside an invocation: **the first read returns the sampled time and every later read returns `UINT64_MAX`**, which retires a deadline loop after one pass instead of spinning forever. It invents no duration, but a title does get one pass of work per dispatch where hardware would get many. Other models exist (advance by an estimated per-iteration cost, or calibrate from the measured duration of the previous dispatch). I picked the one that cannot hang and invents no number, but this is a semantic decision and I would rather follow your preference than impose mine. ### Testing Windows 11, RTX 4070, local build of `d3d7bd3`, PPSA01474: | build | compute shaders compiled | result | | --- | --- | --- | | upstream | 11 | stops on the missing opcode | | counter sampled per dispatch only | 17 | GPU hang, driver reset | | this PR | 34 | no hang, no driver reset | `shader_cfg_tests` passes, including a new case covering the decode, the IR lowering, the reserved shader-data dwords, the read marker and SPIR-V validation. The title still renders nothing. With this change it stops later, in resource tracking, with `GetBufferResource dword 2 is not a valid runtime value` (`hash=0xf8bcd41f5f36626d`): that shader builds its whole buffer descriptor in VGPRs from a `BUFFER_LOAD_DWORD` and an emulated unsigned division, then makes it wave-uniform with `V_READFIRSTLANE_B32`. That looks like a second shape of #507, and I have not touched it here. ### AI disclosure This change was implemented with AI assistance (Claude): reading the AMD ISA to identify the opcode, writing the patch, and analysing the logs and the failing shader. I reviewed the change, built it, and ran the shader tests myself on the machine described above, and I am responsible for what it does. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added support for shader real-time counter reads. * Real-time counter values are sampled consistently per shader invocation. * Added handling for the new real-time memory instruction across shader compilation and execution. * **Bug Fixes** * Subsequent real-time counter reads now return a terminal value, helping deadline-based shader loops complete reliably. * **Tests** * Added coverage validating decoding, intermediate representation, resource layout, and SPIR-V output. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
Ratchet & Clank: Rift Apart (PPSA01474) stops in shader recompilation on the
missing SMEM opcode 0x25 at pc 0x4. Per the AMD ISA, S_MEMREALTIME reads a
64-bit real-time counter from a constant 25 MHz clock into SDST and SDST+1.

The renderer samples the guest process time counter, rescaled to 25 MHz with
integer arithmetic, into two shader-data dwords for every draw and dispatch.

The failing shader does not read the clock once: it reads a budget from its own
buffer and loops re-reading the clock until the deadline passes. A Vulkan shader
cannot observe time passing while it runs, so a counter sampled once per dispatch
never retires that loop: the GPU hangs and the driver resets. The first read of an
invocation therefore returns the sampled time and every later read returns the end
of time, so such a loop runs one pass instead of spinning forever.

Co-Authored-By: Claude Opus 5 <[email protected]>
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:27:00 +00:00
github-bot closed this pull request 2026-11-26 09:27:00 +00:00
Author
Owner

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

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Advanced

Run ID: 3906db4f-4c04-48f6-88a2-ed044c7899ef

📥 Commits

Reviewing files that changed from the base of the PR and between d3d7bd33f8 and 07455df1d1.

📒 Files selected for processing (18)
  • src/graphics/host_gpu/renderer/pipeline/descriptors.cpp
  • src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterFlow.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterInstructions.h
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterModule.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp
  • src/graphics/shader/recompiler/frontend/decode/MemoryOps.cpp
  • src/graphics/shader/recompiler/frontend/decode/ShaderDecoder.cpp
  • src/graphics/shader/recompiler/frontend/decode/ShaderDecoder.h
  • src/graphics/shader/recompiler/frontend/translate/Memory.cpp
  • src/graphics/shader/recompiler/frontend/translate/Translator.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
  • tests/ShaderRecompilerComputeTests.cpp
  • tests/shaderCfgTests.cpp

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


📝 Walkthrough

Walkthrough

Changes

Real-Time Counter Support

Layer / File(s) Summary
Opcode decoding and translation
src/graphics/shader/recompiler/frontend/decode/..., src/graphics/shader/recompiler/frontend/translate/..., src/graphics/shader/recompiler/ir/opcodes/*
The decoder recognizes S_MEMREALTIME. The translator emits GetRealTimeCounter and MarkRealTimeCounterRead.
Counter binding and host data
src/graphics/shader/recompiler/ir/ShaderIR.h, src/graphics/shader/recompiler/ir/passes/BindingLayout.cpp, src/graphics/host_gpu/renderer/pipeline/descriptors.cpp
The binding layout reserves two counter dwords. The host packs a rescaled counter value into shader data.
SPIR-V counter state and emission
src/graphics/shader/recompiler/backend/spirv/*
The backend allocates and initializes per-invocation read state. The first read returns the counter value, and later reads return 0xffffffff.
Real-time counter validation
tests/ShaderRecompilerComputeTests.cpp, tests/shaderCfgTests.cpp
Tests cover opcode classification, decoding, IR generation, binding layout allocation, and SPIR-V validation.

Priority: ⬇️ Low

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Bug fix

Suggested reviewers: nmzik

Sequence Diagram(s)

sequenceDiagram
  participant ShaderDecoder
  participant Translator
  participant SPIRV
  participant ShaderData
  ShaderDecoder->>Translator: Decode S_MEMREALTIME
  Translator->>SPIRV: Emit counter read operations
  SPIRV->>ShaderData: Load packed counter dwords
  SPIRV->>SPIRV: Track per-invocation read state
  SPIRV-->>Translator: First read value or 0xffffffff

Merge Risk: ⚪ Minimal · up to 07455

The real-time counter support is wired through decoding, shader data, and SPIR-V emission without an identified current-head defect.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 17.86% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 28 functions across 15 files. (3 skipped:… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely identifies the main change: implementing the S_MEMREALTIME SMEM opcode, including its opcode value.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Full details: Docstring Coverage

Explanation

Docstring coverage is 17.86% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 28 functions across 15 files. (3 skipped: 1 unsupported, 2 too large.)

  • Fix all pre-merge checks with AI
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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-13 11:30 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/601#issuecomment-5652988317) · edited 2026-09-13 11:36 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/601#gh-light-mode-only"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg" alt="Review Change Stack" width="202" height="32"></a><a href="https://app.coderabbit.ai/change-stack/KytyPS5/KytyPS5/pull/601#gh-dark-mode-only"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui-dark.svg" alt="Review Change Stack" width="202" height="32"></a> <!-- review_stack_entry_end --> <!-- recent_review_start --> No actionable comments were generated in the recent review. 🎉 <details> <summary>ℹ️ Recent review info</summary> <details> <summary>⚙️ Run configuration</summary> **Configuration used**: defaults **Review profile**: CHILL **Plan**: Advanced **Run ID**: `3906db4f-4c04-48f6-88a2-ed044c7899ef` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between d3d7bd33f8eb4996cf198c430bb2e4fa4bf518eb and 07455df1d11ca0534f17a5fd4a429def582ca499. </details> <details> <summary>📒 Files selected for processing (18)</summary> * `src/graphics/host_gpu/renderer/pipeline/descriptors.cpp` * `src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterFlow.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterInstructions.h` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterModule.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp` * `src/graphics/shader/recompiler/frontend/decode/MemoryOps.cpp` * `src/graphics/shader/recompiler/frontend/decode/ShaderDecoder.cpp` * `src/graphics/shader/recompiler/frontend/decode/ShaderDecoder.h` * `src/graphics/shader/recompiler/frontend/translate/Memory.cpp` * `src/graphics/shader/recompiler/frontend/translate/Translator.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` * `tests/ShaderRecompilerComputeTests.cpp` * `tests/shaderCfgTests.cpp` </details> **Included review availability:** Your plan provides up to 8 included reviews per hour; 7 remain after this review. </details> --- <!-- recent_review_end --> <!-- walkthrough_start --> <details> <summary>📝 Walkthrough</summary> ## Walkthrough ### Changes **Real-Time Counter Support** |Layer / File(s)|Summary| |---|---| |**Opcode decoding and translation** <br> `src/graphics/shader/recompiler/frontend/decode/...`, `src/graphics/shader/recompiler/frontend/translate/...`, `src/graphics/shader/recompiler/ir/opcodes/*`|The decoder recognizes `S_MEMREALTIME`. The translator emits `GetRealTimeCounter` and `MarkRealTimeCounterRead`.| |**Counter binding and host data** <br> `src/graphics/shader/recompiler/ir/ShaderIR.h`, `src/graphics/shader/recompiler/ir/passes/BindingLayout.cpp`, `src/graphics/host_gpu/renderer/pipeline/descriptors.cpp`|The binding layout reserves two counter dwords. The host packs a rescaled counter value into shader data.| |**SPIR-V counter state and emission** <br> `src/graphics/shader/recompiler/backend/spirv/*`|The backend allocates and initializes per-invocation read state. The first read returns the counter value, and later reads return `0xffffffff`.| |**Real-time counter validation** <br> `tests/ShaderRecompilerComputeTests.cpp`, `tests/shaderCfgTests.cpp`|Tests cover opcode classification, decoding, IR generation, binding layout allocation, and SPIR-V validation.| <!-- change_assessment_start --> **Priority:** ⬇️ Low **Estimated code review effort:** 3 (Moderate) | ~25 minutes <!-- change_assessment_commit:"07455df1d11ca0534f17a5fd4a429def582ca499" --> **Change:** Bug fix <!-- change_assessment_end --> **Suggested reviewers:** `nmzik` ### Sequence Diagram(s) ```mermaid sequenceDiagram participant ShaderDecoder participant Translator participant SPIRV participant ShaderData ShaderDecoder->>Translator: Decode S_MEMREALTIME Translator->>SPIRV: Emit counter read operations SPIRV->>ShaderData: Load packed counter dwords SPIRV->>SPIRV: Track per-invocation read state SPIRV-->>Translator: First read value or 0xffffffff ``` </details> <!-- walkthrough_end --> <!-- final_review_risk_start --> **Merge Risk:** _⚪ Minimal_ · up to `07455` <!-- final_review_risk_coverage:{"sourceCommitId":"07455df1d11ca0534f17a5fd4a429def582ca499","coveredCommitId":"07455df1d11ca0534f17a5fd4a429def582ca499","kind":"reviewed"} --> The real-time counter support is wired through decoding, shader data, and SPIR-V emission without an identified current-head defect. <!-- final_review_risk_end --> <!-- pre_merge_checks_walkthrough_start --> <details> <summary>🚥 Pre-merge checks | ✅ 4 | ❌ 1</summary> ### ❌ Failed checks (1 warning) | Check name | Status | Explanation | Resolution | | :----------------: | :--------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------- | | Docstring Coverage | ⚠️ Warning | Docstring coverage is 17.86% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 28 functions across 15 files. (3 skipped:… | Write docstrings for the functions missing them to satisfy the coverage threshold. | <details> <summary>✅ Passed checks (4 passed)</summary> | Check name | Status | Explanation | | :------------------------: | :------- | :---------------------------------------------------------------------------------------------------------------------------------- | | Description Check | ✅ Passed | Check skipped - CodeRabbit’s high-level summary is enabled. | | Title check | ✅ Passed | The title clearly and concisely identifies the main change: implementing the S_MEMREALTIME SMEM opcode, including its opcode value. | | Linked Issues check | ✅ Passed | Check skipped because no linked issues were found for this pull request. | | Out of Scope Changes check | ✅ Passed | Check skipped because no linked issues were found for this pull request. | </details> <details> <summary>Full details: Docstring Coverage</summary> **Explanation** Docstring coverage is 17.86% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 28 functions across 15 files. (3 skipped: 1 unsupported, 2 too large.) </details> </details> <!-- pre_merge_checks_walkthrough_end --> - [ ] <!-- {"checkboxId":"585bb3f6-faf5-4dbf-96d2-74e382adf19a"} --> Fix all pre-merge checks with AI <!-- finishing_touch_checkbox_start --> <details> <summary>✨ Finishing Touches</summary> <details> <summary>🧪 Generate unit tests (beta)</summary> - [ ] <!-- {"checkboxId": "f47ac10b-58cc-4372-a567-0e02b2c3d479", "radioGroupId": "utg-output-choice-group-unknown_comment_id"} --> Create PR with unit tests </details> </details> <!-- finishing_touch_checkbox_end --> <!-- tips_start --> --- Thanks for using [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=KytyPS5/KytyPS5&utm_content=601)! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. <details> <summary>❤️ Share</summary> - [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai) - [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai) - [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai) - [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code) </details> <sub>Comment `@coderabbitai help` to get the list of available commands.</sub> <!-- tips_end -->
Author
Owner

@⁠copilot-pull-request-reviewer[bot] on GitHub · 2026-09-13 11:38 UTC · original · reviewed

Address the critical timer-frequency failure and wave64 per-half realtime-read state issues.

Get a fresh assessment by requesting another Copilot review.

Pull request overview

Implements AMD S_MEMREALTIME support end to end, including decoding, IR lowering, shader-data bindings, SPIR-V emission, and host counter sampling.

Changes:

  • Decodes and translates SMEM opcode 0x25, rejecting odd destinations.
  • Adds 25 MHz counter bindings and first/subsequent read behavior.
  • Adds regression and SPIR-V validation coverage.
File summaries
File Reviewed change
tests/ShaderRecompilerComputeTests.cpp Updates opcode coverage classification.
tests/shaderCfgTests.cpp Adds decode, IR, binding, and SPIR-V tests.
src/graphics/shader/recompiler/ir/ShaderIR.h Extends shader-data binding layout.
src/graphics/shader/recompiler/ir/passes/BindingLayout.cpp Detects and reserves counter data.
src/graphics/shader/recompiler/ir/opcodes/ValueOpcodes.inc Adds counter IR operations.
src/graphics/shader/recompiler/ir/opcodes/ValueOpcodes.cpp Marks counter reads as side effects.
src/graphics/shader/recompiler/frontend/translate/Translator.h Declares opcode translation support.
src/graphics/shader/recompiler/frontend/translate/Memory.cpp Lowers S_MEMREALTIME.
src/graphics/shader/recompiler/frontend/decode/ShaderDecoder.h Adds the opcode enum.
src/graphics/shader/recompiler/frontend/decode/ShaderDecoder.cpp Formats the new opcode.
src/graphics/shader/recompiler/frontend/decode/MemoryOps.cpp Decodes SMEM 0x25.
src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp Initializes per-invocation state.
src/graphics/shader/recompiler/backend/spirv/spirvEmitterModule.cpp Declares counter state.
src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h Adds emitter state fields.
src/graphics/shader/recompiler/backend/spirv/spirvEmitterInstructions.h Declares counter emitters.
src/graphics/shader/recompiler/backend/spirv/spirvEmitterFlow.cpp Emits counter loads and retirement behavior.
src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.cpp Detects counter-state requirements.
src/graphics/host_gpu/renderer/pipeline/descriptors.cpp Samples and binds the host counter.
Review details

Suppressed comments (3)

src/graphics/shader/recompiler/backend/spirv/spirvEmitterFlow.cpp:570

  • When lane_count == 2 (wave64 emulated with host subgroups of 32), EmitBlock emits each IR instruction for both half contexts sequentially in the same SPIR-V invocation. The first half's MarkRealTimeCounterRead store runs before the second half's GetRealTimeCounter, so the high half's first read observes the flag as set and returns UINT32_MAX instead of the sampled counter; SGPR results then disagree between the two halves. Emit the marker/read as one logical operation across both halves (for example, delay the store until both half emissions) and add a wave64/subgroup32 regression test.
void EmitMarkRealTimeCounterRead(EmitterState& state) {
	if (state.realtime_counter_read_variable == 0) {
		EXIT("real-time counter marker without its per-invocation state");
	}
	state.builder.AddFunction(spv::OpStore, state.realtime_counter_read_variable,
	                          ConstantU32(state, 1));

src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h:112

  • When lane_count == 2, the emitter visits every IR instruction for half 0 and half 1 sequentially, but both halves currently use this single function-local flag. The half-0 MarkRealTimeCounterRead store therefore sets the flag before half 1 performs its first read, making the high emulated wave half receive UINT64_MAX on its first S_MEMREALTIME instead of the sampled counter. Keep the read state per emulated half (and select it using state.lane_half, as scratch storage does) so each half has independent first-read state.
	uint32_t                   realtime_counter_read_variable        = 0;

tests/shaderCfgTests.cpp:4680

  • This regression shader executes only one S_MEMREALTIME and consumes only the low dword, so it never exercises the first == false path that returns UINT32_MAX on later reads, and the high-dword load may be dead-code eliminated. SPIR-V validation can still pass if the deadline-loop retirement logic is broken; add a two-read case (ideally across a loop/control-flow shape) and assert the generated behavior for the second read.
  const uint32_t shader[] = {
      EncodeSmem0(0x25, 12, 0),
      0u, // s_memrealtime s[12:13]
      EncodeVop1(0x01, 0, 12),
      EncodeExp0(0x00, 0x1),
  • Files reviewed: 18/18 changed files
  • Comments generated: 1
  • Review effort level: Lite

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

**@⁠copilot-pull-request-reviewer[bot]** on GitHub · 2026-09-13 11:38 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/601#pullrequestreview-5190569300) · **reviewed** ### 🟡 Changes recommended Address the critical timer-frequency failure and wave64 per-half realtime-read state issues. *Get a fresh assessment by requesting another Copilot review.* <details> <summary>Pull request overview</summary> Implements AMD `S_MEMREALTIME` support end to end, including decoding, IR lowering, shader-data bindings, SPIR-V emission, and host counter sampling. **Changes:** - Decodes and translates SMEM opcode `0x25`, rejecting odd destinations. - Adds 25 MHz counter bindings and first/subsequent read behavior. - Adds regression and SPIR-V validation coverage. </details> <details> <summary>File summaries</summary> | File | Reviewed change | |---|---| | `tests/ShaderRecompilerComputeTests.cpp` | Updates opcode coverage classification. | | `tests/shaderCfgTests.cpp` | Adds decode, IR, binding, and SPIR-V tests. | | `src/graphics/shader/recompiler/ir/ShaderIR.h` | Extends shader-data binding layout. | | `src/graphics/shader/recompiler/ir/passes/BindingLayout.cpp` | Detects and reserves counter data. | | `src/graphics/shader/recompiler/ir/opcodes/ValueOpcodes.inc` | Adds counter IR operations. | | `src/graphics/shader/recompiler/ir/opcodes/ValueOpcodes.cpp` | Marks counter reads as side effects. | | `src/graphics/shader/recompiler/frontend/translate/Translator.h` | Declares opcode translation support. | | `src/graphics/shader/recompiler/frontend/translate/Memory.cpp` | Lowers `S_MEMREALTIME`. | | `src/graphics/shader/recompiler/frontend/decode/ShaderDecoder.h` | Adds the opcode enum. | | `src/graphics/shader/recompiler/frontend/decode/ShaderDecoder.cpp` | Formats the new opcode. | | `src/graphics/shader/recompiler/frontend/decode/MemoryOps.cpp` | Decodes SMEM `0x25`. | | `src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp` | Initializes per-invocation state. | | `src/graphics/shader/recompiler/backend/spirv/spirvEmitterModule.cpp` | Declares counter state. | | `src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h` | Adds emitter state fields. | | `src/graphics/shader/recompiler/backend/spirv/spirvEmitterInstructions.h` | Declares counter emitters. | | `src/graphics/shader/recompiler/backend/spirv/spirvEmitterFlow.cpp` | Emits counter loads and retirement behavior. | | `src/graphics/shader/recompiler/backend/spirv/SpirvEmitter.cpp` | Detects counter-state requirements. | | `src/graphics/host_gpu/renderer/pipeline/descriptors.cpp` | Samples and binds the host counter. | </details> <details> <summary>Review details</summary> ### Suppressed comments (3) **src/graphics/shader/recompiler/backend/spirv/spirvEmitterFlow.cpp:570** * When `lane_count == 2` (wave64 emulated with host subgroups of 32), `EmitBlock` emits each IR instruction for both half contexts sequentially in the same SPIR-V invocation. The first half's `MarkRealTimeCounterRead` store runs before the second half's `GetRealTimeCounter`, so the high half's first read observes the flag as set and returns `UINT32_MAX` instead of the sampled counter; SGPR results then disagree between the two halves. Emit the marker/read as one logical operation across both halves (for example, delay the store until both half emissions) and add a wave64/subgroup32 regression test. ``` void EmitMarkRealTimeCounterRead(EmitterState& state) { if (state.realtime_counter_read_variable == 0) { EXIT("real-time counter marker without its per-invocation state"); } state.builder.AddFunction(spv::OpStore, state.realtime_counter_read_variable, ConstantU32(state, 1)); ``` **src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h:112** * When `lane_count == 2`, the emitter visits every IR instruction for half 0 and half 1 sequentially, but both halves currently use this single function-local flag. The half-0 `MarkRealTimeCounterRead` store therefore sets the flag before half 1 performs its first read, making the high emulated wave half receive `UINT64_MAX` on its first `S_MEMREALTIME` instead of the sampled counter. Keep the read state per emulated half (and select it using `state.lane_half`, as scratch storage does) so each half has independent first-read state. ``` uint32_t realtime_counter_read_variable = 0; ``` **tests/shaderCfgTests.cpp:4680** * This regression shader executes only one `S_MEMREALTIME` and consumes only the low dword, so it never exercises the `first == false` path that returns `UINT32_MAX` on later reads, and the high-dword load may be dead-code eliminated. SPIR-V validation can still pass if the deadline-loop retirement logic is broken; add a two-read case (ideally across a loop/control-flow shape) and assert the generated behavior for the second read. ``` const uint32_t shader[] = { EncodeSmem0(0x25, 12, 0), 0u, // s_memrealtime s[12:13] EncodeVop1(0x01, 0, 12), EncodeExp0(0x00, 0x1), ``` - **Files reviewed:** 18/18 changed files - **Comments generated:** 1 - **Review effort level:** Lite </details> --- 💡 <a href="/KytyPS5/KytyPS5/new/main?filename=.github/skills/code-review/SKILL.md" class="Link--inTextBlock" target="_blank" rel="noopener noreferrer">Add a `code-review` agent skill</a> or configure MCP servers for context-aware, tailored reviews. <a href="https://docs.github.com/copilot/how-tos/use-copilot-agents/request-a-code-review/use-code-review?tool=webui#mcp-servers-and-agent-skills" class="Link--inTextBlock" target="_blank" rel="noopener noreferrer">Learn more in the docs.</a>
@ -776,0 +781,4 @@
const auto ticks = Libs::LibKernel::KernelGetProcessTimeCounter();
const auto frequency = Libs::LibKernel::KernelGetProcessTimeCounterFrequency();
return ticks / frequency * realtime_frequency +
ticks % frequency * realtime_frequency / frequency;
Author
Owner

@⁠Copilot on GitHub · 2026-09-13 11:38 UTC · original

KernelGetProcessTimeCounterFrequency() can be zero on the non-x86 path because it directly returns QueryPerformanceFrequency(), but this helper unconditionally uses it for both division and modulo. A failed host timer would therefore make any realtime shader hit undefined divide-by-zero during RebindBuffers; handle the zero case before scaling, consistent with KernelGetProcessTime().

**@⁠Copilot** on GitHub · 2026-09-13 11:38 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/601#discussion_r3999507325) `KernelGetProcessTimeCounterFrequency()` can be zero on the non-x86 path because it directly returns `QueryPerformanceFrequency()`, but this helper unconditionally uses it for both division and modulo. A failed host timer would therefore make any realtime shader hit undefined divide-by-zero during `RebindBuffers`; handle the zero case before scaling, consistent with `KernelGetProcessTime()`.
Author
Owner

@⁠Nmzik on GitHub · 2026-09-24 16:57 UTC · original

Credited

**@⁠Nmzik** on GitHub · 2026-09-24 16:57 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/601#issuecomment-5818491698) Credited

Pull request closed

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