shader: cap loop iterations so a bad shader cannot hang the GPU #986

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

@⁠wuboo on GitHub · 2026-10-02 21:01 UTC · original
wuboo:pr/shader-loop-watchdog → main · +283 −7 · 4 files · 7 commits · closed without merging

Problem

A guest shader can contain a loop that does not exit when it is fed values it never sees in a correct frame: a null descriptor, a ballot that stays false, a compare-exchange that never lands. The GPU then runs that loop until the process is killed.

On Astro Bot's world scene this showed up as frames of about 50 seconds. The loops were pinned by a wave-wide *Zero test (fixed separately in #985) and each one ran to the iteration cap, once per vertex. At 65536 iterations that was already ~50 s/frame. A cap of 2^20 on the same shader would be about sixteen times longer, which is still a hang from the player's point of view.

Current main has no KYTY_SHADER_LOOP_LIMIT and no iteration counter on emitted loops.

Change

Every latch of a structured loop increments a function-scope counter. A conditional branch that already leaves that loop for its merge block is forced to take that exit once the counter reaches the cap. No new edge is added: the loop takes an exit it already had.

The same cap stops two loops that are not in the guest CFG:

  • the compare-exchange retry used by float and merge atomics
  • a buffer-device-address page index past the guest page table, which is treated as a missing page instead of an access chain off the end of the table

The cap is on by default at 65536. KYTY_SHADER_LOOP_LIMIT overrides it. 0 disables it, which is how the SPIR-V size baselines are measured (the counters add variables, loads and stores that those fixtures reject).

65536 is the cap that was measured against the pinned world-scene shader. It is large next to loops that actually terminate, and small enough that a shader which hits it returns in tens of seconds rather than minutes. Raising the default to 2^20 would change the semantics less often for a genuinely long loop, and would make the failure mode we already hit much worse.

Tests

shader_cfg_tests, Release, macOS, KYTY_VS_LANE_FROM_INDEX=0: exit 0.

Size baselines run with KYTY_SHADER_LOOP_LIMIT=0 and keep their previous word counts. With the limit set to 65536, the structured-loop fixture still validates and gains a function variable, and the dispatcher loop gains a third phi (opcode 245 count goes from 2 to 3).

Release kyty_emulator from this branch links.

Limits

The forced exit returns whatever values the existing edge produces. A loop that needed more than 65536 iterations for a correct result will stop early. Set KYTY_SHADER_LOOP_LIMIT higher, or to 0, if a title has a legitimate loop that long.

The cap is counted per back edge, not per guest instruction. Nested loops each have their own counter. The dispatcher fallback counts dispatched blocks instead of latches.

**@⁠wuboo** on GitHub · 2026-10-02 21:01 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/986) `wuboo:pr/shader-loop-watchdog` → `main` · +283 −7 · 4 files · 7 commits · closed without merging ### Problem A guest shader can contain a loop that does not exit when it is fed values it never sees in a correct frame: a null descriptor, a ballot that stays false, a compare-exchange that never lands. The GPU then runs that loop until the process is killed. On Astro Bot's world scene this showed up as frames of about 50 seconds. The loops were pinned by a wave-wide `*Zero` test (fixed separately in #985) and each one ran to the iteration cap, once per vertex. At 65536 iterations that was already ~50 s/frame. A cap of 2^20 on the same shader would be about sixteen times longer, which is still a hang from the player's point of view. Current main has no `KYTY_SHADER_LOOP_LIMIT` and no iteration counter on emitted loops. ### Change Every latch of a structured loop increments a function-scope counter. A conditional branch that already leaves that loop for its merge block is forced to take that exit once the counter reaches the cap. No new edge is added: the loop takes an exit it already had. The same cap stops two loops that are not in the guest CFG: - the compare-exchange retry used by float and merge atomics - a buffer-device-address page index past the guest page table, which is treated as a missing page instead of an access chain off the end of the table The cap is on by default at 65536. `KYTY_SHADER_LOOP_LIMIT` overrides it. `0` disables it, which is how the SPIR-V size baselines are measured (the counters add variables, loads and stores that those fixtures reject). 65536 is the cap that was measured against the pinned world-scene shader. It is large next to loops that actually terminate, and small enough that a shader which hits it returns in tens of seconds rather than minutes. Raising the default to 2^20 would change the semantics less often for a genuinely long loop, and would make the failure mode we already hit much worse. ### Tests `shader_cfg_tests`, Release, macOS, `KYTY_VS_LANE_FROM_INDEX=0`: exit 0. Size baselines run with `KYTY_SHADER_LOOP_LIMIT=0` and keep their previous word counts. With the limit set to 65536, the structured-loop fixture still validates and gains a function variable, and the dispatcher loop gains a third phi (opcode 245 count goes from 2 to 3). Release `kyty_emulator` from this branch links. ### Limits The forced exit returns whatever values the existing edge produces. A loop that needed more than 65536 iterations for a correct result will stop early. Set `KYTY_SHADER_LOOP_LIMIT` higher, or to 0, if a title has a legitimate loop that long. The cap is counted per back edge, not per guest instruction. Nested loops each have their own counter. The dispatcher fallback counts dispatched blocks instead of latches.
A pinned loop in a world scene held the GPU for about 50 seconds a frame
once it was allowed to run to 65536 iterations. Count each back edge and
take an exit the loop already has past that cap, and stop a compare-exchange
that never lands and a page-table index past the guest space the same way.
KYTY_SHADER_LOOP_LIMIT=0 turns the cap off.
A value that did not parse as a plain decimal was read as 0, which turns the
watchdog off. Only a valid number now overrides the default.
A structured loop whose latch is an unconditional branch had no edge the watchdog could force, so a loop with no counted break still ran unbounded. Branch to the loop merge once the back-edge count reaches the cap.
Count the cap compares in the structured loop, add an endless-loop fixture, and set KYTY_SHADER_LOOP_LIMIT through a helper that uses _putenv_s on Windows.
strtoull accepts leading whitespace and a sign, so "+0" or " 0" parsed
as 0 and silently turned the loop watchdog off. Only a value that starts
with a digit overrides the default now; an explicit 0 still disables it.
Compile a conditional latch that branches straight back to its header with
the limit on and assert one OpUGreaterThanEqual and one OpSelect. With the
limit off the check fails, so it does exercise the guard.
The forced exit from an unconditional latch is a new edge into the loop's
exit block. If that block starts with an OpPhi, the phi is one incoming
value short and the module fails validation (incoming blocks 2 vs
predecessors 3); some drivers crash on it instead of rejecting it.

Skip the forced exit for such loops; they keep the exit they already have.
Add a test with an unconditional latch whose exit block reads a phi.
Without the change it fails spirv-val at the default limit.

Co-authored-by: Rohit Mahto <[email protected]>
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:39:22 +00:00
github-bot closed this pull request 2026-11-26 09:39:22 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-02 21:12 UTC · original · edited 2026-10-05 23:33 UTC

Review in Change Stack →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The SPIR-V emitter now applies a configurable limit to atomic retries and to structured and dispatcher loops. BDA pointer lookup checks page indexes before accessing the page table. Tests check watchdog-enabled loop output, malformed and out-of-range limits, and watchdog-disabled size baselines.

Suggested reviewers: nmzik

Priority: ⬆️ High

Change: Bug fix

Merge Risk: 🟡 Moderate · up to fb0ae

Some shaders can still run without a loop bound, and heavily contended subword stores can silently fail. These paths should be corrected before merging.

Security Architecture Review

Security architecture risk: 🟡 Moderate · up to fb0ae

The change reduces hang and invalid-memory risks, but exhausting the retry limit can silently discard shared-memory updates while execution continues. Protection against nonterminating loops also remains incomplete.

Retained concerns

  • Medium · reliability · observed: Under sustained contention, the new retry cap exits AtomicUpdate even when the final compare-exchange failed, then performs the barrier and returns the ordinary observed value. Callers receive no failure indication, and emulated non-scratch subword stores discard the return value. Unlike the base, execution can therefore continue after an unapplied shared-state update rather than containing the timeout as a distinct failure. The demonstrated effect is guest-visible update loss; host-memory corruption or privilege escalation is not established.
Security review details

Security Blast Radius

  • inferred — The demonstrated attackable surface is guest shader execution: guest-derived addresses reach BDA translation, and concurrent updates can contend on shader-accessible buffer or workgroup words. The inspected update paths retain active-lane and resource-bound checks. These observations do not establish access to unrelated host memory or another tenant’s resources.

Security Findings and Attack Paths

  • inferred — If concurrent invocations keep changing a target word until the retry budget expires, a failed update can be followed by ordinary shader execution without a timeout signal. This creates a partial-completion outcome for shared state. Its occurrence in a real workload and any downstream host-security consequence remain unverified.

Trust Boundaries and Controls

  • observed — Out-of-range BDA pages use table index zero only for a bounded lookup. The original out-of-range predicate independently forces the fault branch, whose Phi result is zero even when table entry zero contains a valid address. LoadBdaDword checks this result before converting it to a physical pointer. Thus the fallback does not grant access to page-zero contents. The fault bitmap records page zero, losing the original invalid-page identity.

Resilience and Maintainability Implications

  • inferred — A structured loop can still lack a cap-tested exit when its unconditional latch targets a Phi-bearing merge and its exits pass through intermediate unconditional break arms. Registration guards direct conditional merge exits, while the latch’s new edge is suppressed. This is incomplete coverage of the new safeguard, not worsened exposure relative to the uncapped base. The added Phi-exit fixture checks validity but does not demonstrate this indirect-break topology or runtime termination.

Hardening Proposals

  • proposed — Give CAS-budget exhaustion a distinct failure outcome so callers can contain an incomplete update instead of treating timeout as ordinary completion.
  • proposed — For structured loops without a proven cap-tested exit, consider a bounded fallback or a Phi-aware termination path, with evidence demonstrating termination of indirect-break topologies.
🚥 Pre-merge checks | ✅ 4 | ❓ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ❓ Inconclusive Docstring coverage is 23.08% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 13 functions across 3 files. (1 skipped: … Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: capping shader loop iterations to prevent hangs.
Description check ✅ Passed The description explains the problem, loop and atomic retry caps, configuration, tests, and known behavior limits. It is directly related to the changeset.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Full details: Docstring Coverage

Explanation

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

  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Autopilot is currently an internal CodeRabbit preview.


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

❤️ Share

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

**@⁠coderabbitai[bot]** on GitHub · 2026-10-02 21:12 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/986#issuecomment-5961555729) · edited 2026-10-05 23:33 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/986?scope=ghh_OusAJGA4HG8ljoOV0wJvVx8NmnZIjc2DdjmxOu0xZWA&amp;cs_source=review_comment"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui-dark.svg?v=2" alt="Review in Change Stack →" width="220" height="32"></a> <!-- review_stack_entry_end --> <!-- This is an auto-generated comment: review paused by coderabbit.ai --> > [!NOTE] > ## Reviews paused > > It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the `reviews.auto_review.auto_pause_after_reviewed_commits` setting. > > Use the following commands to manage reviews: > - `@coderabbitai resume` to resume automatic reviews. > - `@coderabbitai review` to trigger a single review. > > Use the checkboxes below for quick actions: > - [ ] <!-- {"checkboxId":"7f6cc2e2-2e4e-497a-8c31-c9e4573e93d1"} --> ▶️ Resume reviews > - [ ] <!-- {"checkboxId":"e9bb8d72-00e8-4f67-9cb2-caf3b22574fe"} --> 🔍 Trigger review <!-- end of auto-generated comment: review paused by coderabbit.ai --> <!-- walkthrough_start --> <details> <summary>📝 Walkthrough</summary> ## Walkthrough The SPIR-V emitter now applies a configurable limit to atomic retries and to structured and dispatcher loops. BDA pointer lookup checks page indexes before accessing the page table. Tests check watchdog-enabled loop output, malformed and out-of-range limits, and watchdog-disabled size baselines. **Suggested reviewers:** `nmzik` </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ⬆️ High <!-- change_assessment_commit:"fb0aec0bad972993dd20921955855a0f1b2d712a" --> **Change:** Bug fix <!-- change_assessment_end --> <!-- final_review_risk_start --> **Merge Risk:** _🟡 Moderate_ · up to `fb0ae` <!-- final_review_risk_coverage:{"sourceCommitId":"fb0aec0bad972993dd20921955855a0f1b2d712a","coveredCommitId":"fb0aec0bad972993dd20921955855a0f1b2d712a","kind":"reviewed"} --> Some shaders can still run without a loop bound, and heavily contended subword stores can silently fail. These paths should be corrected before merging. <!-- final_review_risk_end --> <!-- architecture_review_start --> ### Security Architecture Review **Security architecture risk:** _🟡 Moderate_ · up to `fb0ae` The change reduces hang and invalid-memory risks, but exhausting the retry limit can silently discard shared-memory updates while execution continues. Protection against nonterminating loops also remains incomplete. **Retained concerns** - **Medium · reliability · observed:** Under sustained contention, the new retry cap exits AtomicUpdate even when the final compare-exchange failed, then performs the barrier and returns the ordinary observed value. Callers receive no failure indication, and emulated non-scratch subword stores discard the return value. Unlike the base, execution can therefore continue after an unapplied shared-state update rather than containing the timeout as a distinct failure. The demonstrated effect is guest-visible update loss; host-memory corruption or privilege escalation is not established. <details> <summary>Security review details</summary> **Security Blast Radius** - _inferred_ — The demonstrated attackable surface is guest shader execution: guest-derived addresses reach BDA translation, and concurrent updates can contend on shader-accessible buffer or workgroup words. The inspected update paths retain active-lane and resource-bound checks. These observations do not establish access to unrelated host memory or another tenant’s resources. **Security Findings and Attack Paths** - _inferred_ — If concurrent invocations keep changing a target word until the retry budget expires, a failed update can be followed by ordinary shader execution without a timeout signal. This creates a partial-completion outcome for shared state. Its occurrence in a real workload and any downstream host-security consequence remain unverified. **Trust Boundaries and Controls** - _observed_ — Out-of-range BDA pages use table index zero only for a bounded lookup. The original out-of-range predicate independently forces the fault branch, whose Phi result is zero even when table entry zero contains a valid address. LoadBdaDword checks this result before converting it to a physical pointer. Thus the fallback does not grant access to page-zero contents. The fault bitmap records page zero, losing the original invalid-page identity. **Resilience and Maintainability Implications** - _inferred_ — A structured loop can still lack a cap-tested exit when its unconditional latch targets a Phi-bearing merge and its exits pass through intermediate unconditional break arms. Registration guards direct conditional merge exits, while the latch’s new edge is suppressed. This is incomplete coverage of the new safeguard, not worsened exposure relative to the uncapped base. The added Phi-exit fixture checks validity but does not demonstrate this indirect-break topology or runtime termination. **Hardening Proposals** - _proposed_ — Give CAS-budget exhaustion a distinct failure outcome so callers can contain an incomplete update instead of treating timeout as ordinary completion. - _proposed_ — For structured loops without a proven cap-tested exit, consider a bounded fallback or a Phi-aware termination path, with evidence demonstrating termination of indirect-break topologies. </details> <!-- architecture_review_end --> <!-- pre_merge_checks_walkthrough_start --> <details> <summary>🚥 Pre-merge checks | ✅ 4 | ❓ 1</summary> ### ❌ Failed checks (1 inconclusive) | Check name | Status | Explanation | Resolution | | :----------------: | :------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------- | | Docstring Coverage | ❓ Inconclusive | Docstring coverage is 23.08% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 13 functions across 3 files. (1 skipped: … | Write docstrings for the functions missing them to satisfy the coverage threshold. | <details> <summary>✅ Passed checks (4 passed)</summary> | Check name | Status | Explanation | | :------------------------: | :------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------- | | Title check | ✅ Passed | The title clearly summarizes the main change: capping shader loop iterations to prevent hangs. | | Description check | ✅ Passed | The description explains the problem, loop and atomic retry caps, configuration, tests, and known behavior limits. It is directly related to the changeset. | | Linked Issues check | ✅ Passed | Check skipped because no linked issues were found for this pull request. | | Out of Scope Changes check | ✅ Passed | Check skipped because no linked issues were found for this pull request. | </details> <details> <summary>Full details: Docstring Coverage</summary> **Explanation** Docstring coverage is 23.08% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 13 functions across 3 files. (1 skipped: 1 too large.) </details> </details> <!-- pre_merge_checks_walkthrough_end --> <!-- autopilot:start --> - [ ] <!-- {"checkboxId":"2708ad07-9f24-4260-9c11-7dc76a49f2e3"} --> <strong title="Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts">Autopilot</strong> · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts > Autopilot is currently an internal CodeRabbit preview. <!-- autopilot:end --> <!-- tips_start --> --- Thanks for using [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=KytyPS5/KytyPS5&utm_content=986)! 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 -->
@ -362,0 +385,4 @@
return kDefaultLimit;
}
return static_cast<uint32_t>(parsed);
}
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-02 21:12 UTC · original · edited 2026-10-02 22:07 UTC

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

ShaderLoopLimit() turns invalid input into "disabled".

strtoul returns 0 for a non-numeric string such as "off" or "abc", and 0 disables the watchdog. A typo in KYTY_SHADER_LOOP_LIMIT therefore removes the GPU-hang protection without any warning.

Treat input that does not parse as the default limit instead of 0.

Proposed fix
 inline uint32_t ShaderLoopLimit() {
 	const char* value = std::getenv("KYTY_SHADER_LOOP_LIMIT");
-	return value != nullptr ? static_cast<uint32_t>(std::strtoul(value, nullptr, 10)) : (1u << 16u);
+	if (value == nullptr) {
+		return 1u << 16u;
+	}
+	char* end = nullptr;
+	const auto parsed = std::strtoul(value, &end, 10);
+	return end != value && *end == '\0' ? static_cast<uint32_t>(parsed) : (1u << 16u);
 }
📝 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.

inline uint32_t ShaderLoopLimit() {
	const char* value = std::getenv("KYTY_SHADER_LOOP_LIMIT");
	if (value == nullptr) {
		return 1u << 16u;
	}
	char* end = nullptr;
	const auto parsed = std::strtoul(value, &end, 10);
	return end != value && *end == '\0' ? static_cast<uint32_t>(parsed) : (1u << 16u);
}

✅ Addressed in commits af3d1fe to def17ab

**@⁠coderabbitai[bot]** on GitHub · 2026-10-02 21:12 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/986#discussion_r4169877981) · edited 2026-10-02 22:07 UTC _🎯 Functional Correctness_ | _🟡 Minor_ | _⚡ Quick win_ **`ShaderLoopLimit()` turns invalid input into "disabled".** `strtoul` returns 0 for a non-numeric string such as `"off"` or `"abc"`, and 0 disables the watchdog. A typo in `KYTY_SHADER_LOOP_LIMIT` therefore removes the GPU-hang protection without any warning. Treat input that does not parse as the default limit instead of 0. <details> <summary>Proposed fix</summary> ```diff inline uint32_t ShaderLoopLimit() { const char* value = std::getenv("KYTY_SHADER_LOOP_LIMIT"); - return value != nullptr ? static_cast<uint32_t>(std::strtoul(value, nullptr, 10)) : (1u << 16u); + if (value == nullptr) { + return 1u << 16u; + } + char* end = nullptr; + const auto parsed = std::strtoul(value, &end, 10); + return end != value && *end == '\0' ? static_cast<uint32_t>(parsed) : (1u << 16u); } ``` </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 inline uint32_t ShaderLoopLimit() { const char* value = std::getenv("KYTY_SHADER_LOOP_LIMIT"); if (value == nullptr) { return 1u << 16u; } char* end = nullptr; const auto parsed = std::strtoul(value, &end, 10); return end != value && *end == '\0' ? static_cast<uint32_t>(parsed) : (1u << 16u); } ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:b0003d914fbd3ad224a14d94 --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Addressed in commits af3d1fe to def17ab
@ -724,0 +857,4 @@
state.loop_counter_variables.emplace(info.id, std::pair {counter, merge});
}
}
}
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-02 21:12 UTC · original · edited 2026-10-02 21:55 UTC

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '355,445p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp
sed -n '775,835p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp
sed -n '1360,1410p' src/graphics/shader/recompiler/frontend/cfg/ShaderCFG.cpp

Repository: KytyPS5/KytyPS5

Length of output: 9310


🏁 Script executed:

set -eu
printf '%s\n' '--- structured terminator and counter consumers ---'
rg -n -C 12 'EmitStructuredTerminator|loop_counter_variables|back_edge_counters|GuardLoopCondition|ShaderLoopLimit' src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp
printf '%s\n' '--- changed diff for target file and structurizer ---'
git diff --unified=35 e317465d8a773b33482ad367ad2f856154c8bc6d 2ec78118ddaadc17cfcb3cdda73ef55e9cc1ac33 -- src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp src/graphics/shader/recompiler/frontend/cfg/ShaderCFG.cpp
printf '%s\n' '--- loop construction references ---'
rg -n -C 8 'condition == 1|Kind::Loop|loop_header|merge_block|KYTY_SHADER_LOOP_LIMIT' src/graphics/shader/recompiler src | head -n 500

Repository: KytyPS5/KytyPS5

Length of output: 41978


🏁 Script executed:

set -eu
printf '%s\n' '--- structured terminator and counter consumers ---'
rg -n -C 14 'EmitStructuredTerminator|loop_counter_variables|back_edge_counters|GuardLoopCondition|ShaderLoopLimit' src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp
printf '%s\n' '--- changed diff ---'
git diff --unified=35 e317465d8a773b33482ad367ad2f856154c8bc6d 2ec78118ddaadc17cfcb3cdda73ef55e9cc1ac33 -- src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp src/graphics/shader/recompiler/frontend/cfg/ShaderCFG.cpp
printf '%s\n' '--- loop references ---'
rg -n -C 8 'condition == 1|Kind::Loop|loop_header|merge_block|KYTY_SHADER_LOOP_LIMIT' src/graphics/shader/recompiler src | head -n 500

Repository: KytyPS5/KytyPS5

Length of output: 41757


🏁 Script executed:

sed -n '250,365p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp; sed -n '365,455p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp; sed -n '790,835p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp; git diff --unified=20 e317465d8a773b33482ad367ad2f856154c8bc6d 2ec78118ddaadc17cfcb3cdda73ef55e9cc1ac33 -- src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp

Repository: KytyPS5/KytyPS5

Length of output: 25276


Guard unconditional loop latches before branching back to the header.

When a structured loop has node->condition == 1, ShaderCFG.cpp emits an unconditional branch from repeat to header. EmitBackEdgeGuard only increments the counter. GuardLoopCondition runs only for ConditionalBranch, and the counter setup excludes unconditional branches to the loop merge. Therefore, this loop has no cap-triggered exit and can execute without an emitter-enforced bound even when KYTY_SHADER_LOOP_LIMIT is nonzero. This violates the documented guarantee that bad shader data cannot hang the GPU.

Suggested fix
 		case CFG::TerminatorKind::Branch: {
 			const auto* target = TargetBlock(program, term.true_block);
 			if (target == nullptr) {
 				EmitReturn(ctx);
 				return;
 			}
+			if (const auto found = ctx.state.loop_counter_variables.find(info.id);
+			    found != ctx.state.loop_counter_variables.end()) {
+				const auto* exit = TargetBlock(program, found->second.second);
+				if (exit == nullptr) {
+					EmitReturn(ctx);
+					return;
+				}
+				const auto condition =
+				    GuardLoopCondition(ctx, info, ConstantBool(ctx.state, true));
+				ctx.state.builder.AddFunction(spv::OpBranchConditional, condition,
+				                              ctx.Label(target), ctx.Label(exit));
+				return;
+			}
 			emit_merge();
 			ctx.state.builder.AddFunction(spv::OpBranch, ctx.Label(target));
 			return;
 		}
-				if (term.kind == CFG::TerminatorKind::ConditionalBranch &&
-				    (term.true_block == merge) != (term.false_block == merge) &&
+				if (((term.kind == CFG::TerminatorKind::ConditionalBranch &&
+				      (term.true_block == merge) != (term.false_block == merge)) ||
+				     (term.kind == CFG::TerminatorKind::Branch && term.true_block == header)) &&
 				    !state.loop_counter_variables.contains(info.id)) {
 					state.loop_counter_variables.emplace(info.id, std::pair {counter, merge});
 				}

✅ Confirmed as addressed by @⁠wuboo

**@⁠coderabbitai[bot]** on GitHub · 2026-10-02 21:12 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/986#discussion_r4169878001) · edited 2026-10-02 21:55 UTC _🩺 Stability & Availability_ | _🟠 Major_ | _⚡ Quick win_ <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash sed -n '355,445p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp sed -n '775,835p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp sed -n '1360,1410p' src/graphics/shader/recompiler/frontend/cfg/ShaderCFG.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 9310 --- 🏁 Script executed: ```bash set -eu printf '%s\n' '--- structured terminator and counter consumers ---' rg -n -C 12 'EmitStructuredTerminator|loop_counter_variables|back_edge_counters|GuardLoopCondition|ShaderLoopLimit' src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp printf '%s\n' '--- changed diff for target file and structurizer ---' git diff --unified=35 e317465d8a773b33482ad367ad2f856154c8bc6d 2ec78118ddaadc17cfcb3cdda73ef55e9cc1ac33 -- src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp src/graphics/shader/recompiler/frontend/cfg/ShaderCFG.cpp printf '%s\n' '--- loop construction references ---' rg -n -C 8 'condition == 1|Kind::Loop|loop_header|merge_block|KYTY_SHADER_LOOP_LIMIT' src/graphics/shader/recompiler src | head -n 500 ``` Repository: KytyPS5/KytyPS5 Length of output: 41978 --- 🏁 Script executed: ```bash set -eu printf '%s\n' '--- structured terminator and counter consumers ---' rg -n -C 14 'EmitStructuredTerminator|loop_counter_variables|back_edge_counters|GuardLoopCondition|ShaderLoopLimit' src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp printf '%s\n' '--- changed diff ---' git diff --unified=35 e317465d8a773b33482ad367ad2f856154c8bc6d 2ec78118ddaadc17cfcb3cdda73ef55e9cc1ac33 -- src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp src/graphics/shader/recompiler/frontend/cfg/ShaderCFG.cpp printf '%s\n' '--- loop references ---' rg -n -C 8 'condition == 1|Kind::Loop|loop_header|merge_block|KYTY_SHADER_LOOP_LIMIT' src/graphics/shader/recompiler src | head -n 500 ``` Repository: KytyPS5/KytyPS5 Length of output: 41757 --- 🏁 Script executed: ```bash sed -n '250,365p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp; sed -n '365,455p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp; sed -n '790,835p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp; git diff --unified=20 e317465d8a773b33482ad367ad2f856154c8bc6d 2ec78118ddaadc17cfcb3cdda73ef55e9cc1ac33 -- src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 25276 --- </details> **Guard unconditional loop latches before branching back to the header.** When a structured loop has `node->condition == 1`, `ShaderCFG.cpp` emits an unconditional branch from `repeat` to `header`. `EmitBackEdgeGuard` only increments the counter. `GuardLoopCondition` runs only for `ConditionalBranch`, and the counter setup excludes unconditional branches to the loop merge. Therefore, this loop has no cap-triggered exit and can execute without an emitter-enforced bound even when `KYTY_SHADER_LOOP_LIMIT` is nonzero. This violates the documented guarantee that bad shader data cannot hang the GPU. <details> <summary>Suggested fix</summary> ```diff case CFG::TerminatorKind::Branch: { const auto* target = TargetBlock(program, term.true_block); if (target == nullptr) { EmitReturn(ctx); return; } + if (const auto found = ctx.state.loop_counter_variables.find(info.id); + found != ctx.state.loop_counter_variables.end()) { + const auto* exit = TargetBlock(program, found->second.second); + if (exit == nullptr) { + EmitReturn(ctx); + return; + } + const auto condition = + GuardLoopCondition(ctx, info, ConstantBool(ctx.state, true)); + ctx.state.builder.AddFunction(spv::OpBranchConditional, condition, + ctx.Label(target), ctx.Label(exit)); + return; + } emit_merge(); ctx.state.builder.AddFunction(spv::OpBranch, ctx.Label(target)); return; } ``` ```diff - if (term.kind == CFG::TerminatorKind::ConditionalBranch && - (term.true_block == merge) != (term.false_block == merge) && + if (((term.kind == CFG::TerminatorKind::ConditionalBranch && + (term.true_block == merge) != (term.false_block == merge)) || + (term.kind == CFG::TerminatorKind::Branch && term.true_block == header)) && !state.loop_counter_variables.contains(info.id)) { state.loop_counter_variables.emplace(info.id, std::pair {counter, merge}); } ``` </details> <!-- fingerprinting:phantom:medusa:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:3fce67c90ff5e377a4c99c90 --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Confirmed as addressed by @⁠wuboo <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-02 21:12 UTC · original · edited 2026-10-02 21:55 UTC
On tests/shaderCfgTests.cpp line 14274 (outdated):

@@ -14256,6 +14256,22 @@ void TestNewShaderRecompilerSpirvSizeBaselines() {
             SpirvInstructionOpcodeCount(dispatcher_result.spirv, 251u) == 1u,
         "dispatcher size fixture lost its two control Phis or switch");
   CheckSpirvPhiParents(dispatcher_result.spirv);
+
+  // The baselines above run with the loop watchdog off. With it on, the guarded
+  // structured loop and the dispatcher loop must still validate and carry a counter.
+  setenv("KYTY_SHADER_LOOP_LIMIT", "65536", 1);
+  {
+    auto options = MakeCompileOptions(ShaderType::Compute);
+    const auto guarded_structured = RecompileForTest(structured_phi, options);
+    CheckSpirvBinaryValidates(guarded_structured.spirv);
+    Check(MeasureSpirv(guarded_structured.spirv).function_variables >= 1u,
+          "loop watchdog added no counter to a structured loop");
+    const auto guarded_dispatcher = RecompileForTest(dispatcher, options);
+    CheckSpirvBinaryValidates(guarded_dispatcher.spirv);
+    Check(SpirvInstructionOpcodeCount(guarded_dispatcher.spirv, 245u) == 3u,
+          "loop watchdog did not count the dispatcher loop");
+  }
+  setenv("KYTY_SHADER_LOOP_LIMIT", "0", 1);

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '1,135p' CMakeLists.txt
sed -n '370,405p' CMakeLists.txt
rg -n 'MSVC|CMAKE_CXX_COMPILER|setenv\(|_putenv_s|KYTY_SHADER_LOOP_LIMIT|TestNewShaderRecompilerSpirvSizeBaselines' CMakeLists.txt cmake tests src/graphics/shader/recompiler | head -130
sed -n '14270,14385p' tests/shaderCfgTests.cpp

Repository: KytyPS5/KytyPS5

Length of output: 13391


🏁 Script executed:

set -eu
printf '%s\n' '--- target helper and platform/compiler mapping ---'
rg -n -C 5 'function\(add_kyty_full_emulator_test|add_kyty_full_emulator_test|KYTY_PLATFORM_WINDOWS|CMAKE_CXX_COMPILER_ID|setenv|_putenv_s|putenv|getenv' CMakeLists.txt src tests --glob '!tests/shaderCfgTests.cpp' --glob '!src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h' | head -240
printf '%s\n' '--- all loop-limit consumers and environment writes ---'
rg -n -C 4 'KYTY_SHADER_LOOP_LIMIT|setenv\(|_putenv_s\(|putenv\(|getenv\(' tests src CMakeLists.txt | head -320
printf '%s\n' '--- target helper definition ---'
rg -n 'function\(add_kyty_full_emulator_test|macro\(add_kyty_full_emulator_test' . -g '*.cmake' -g 'CMakeLists.txt'
printf '%s\n' '--- relevant test order and post-baseline region ---'
sed -n '14280,14480p' tests/shaderCfgTests.cpp

Repository: KytyPS5/KytyPS5

Length of output: 29173


Use a portable environment helper for KYTY_SHADER_LOOP_LIMIT.

shader_cfg_tests supports Windows Clang toolchains, including clang-cl. These unqualified calls use the POSIX setenv, which the Windows CRT does not provide. Use a helper that calls _putenv_s on Windows and setenv elsewhere.

Do not add RAII restoration of the original environment value. main intentionally sets the watchdog to "0" before the suite, and the test restores that same baseline for later tests.

✅ Confirmed as addressed by @⁠wuboo

**@⁠coderabbitai[bot]** on GitHub · 2026-10-02 21:12 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/986#discussion_r4169878006) · edited 2026-10-02 21:55 UTC On `tests/shaderCfgTests.cpp` line 14274 (outdated): ```diff @@ -14256,6 +14256,22 @@ void TestNewShaderRecompilerSpirvSizeBaselines() { SpirvInstructionOpcodeCount(dispatcher_result.spirv, 251u) == 1u, "dispatcher size fixture lost its two control Phis or switch"); CheckSpirvPhiParents(dispatcher_result.spirv); + + // The baselines above run with the loop watchdog off. With it on, the guarded + // structured loop and the dispatcher loop must still validate and carry a counter. + setenv("KYTY_SHADER_LOOP_LIMIT", "65536", 1); + { + auto options = MakeCompileOptions(ShaderType::Compute); + const auto guarded_structured = RecompileForTest(structured_phi, options); + CheckSpirvBinaryValidates(guarded_structured.spirv); + Check(MeasureSpirv(guarded_structured.spirv).function_variables >= 1u, + "loop watchdog added no counter to a structured loop"); + const auto guarded_dispatcher = RecompileForTest(dispatcher, options); + CheckSpirvBinaryValidates(guarded_dispatcher.spirv); + Check(SpirvInstructionOpcodeCount(guarded_dispatcher.spirv, 245u) == 3u, + "loop watchdog did not count the dispatcher loop"); + } + setenv("KYTY_SHADER_LOOP_LIMIT", "0", 1); ``` _🎯 Functional Correctness_ | _🟡 Minor_ | _⚡ Quick win_ <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash sed -n '1,135p' CMakeLists.txt sed -n '370,405p' CMakeLists.txt rg -n 'MSVC|CMAKE_CXX_COMPILER|setenv\(|_putenv_s|KYTY_SHADER_LOOP_LIMIT|TestNewShaderRecompilerSpirvSizeBaselines' CMakeLists.txt cmake tests src/graphics/shader/recompiler | head -130 sed -n '14270,14385p' tests/shaderCfgTests.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 13391 --- 🏁 Script executed: ```bash set -eu printf '%s\n' '--- target helper and platform/compiler mapping ---' rg -n -C 5 'function\(add_kyty_full_emulator_test|add_kyty_full_emulator_test|KYTY_PLATFORM_WINDOWS|CMAKE_CXX_COMPILER_ID|setenv|_putenv_s|putenv|getenv' CMakeLists.txt src tests --glob '!tests/shaderCfgTests.cpp' --glob '!src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h' | head -240 printf '%s\n' '--- all loop-limit consumers and environment writes ---' rg -n -C 4 'KYTY_SHADER_LOOP_LIMIT|setenv\(|_putenv_s\(|putenv\(|getenv\(' tests src CMakeLists.txt | head -320 printf '%s\n' '--- target helper definition ---' rg -n 'function\(add_kyty_full_emulator_test|macro\(add_kyty_full_emulator_test' . -g '*.cmake' -g 'CMakeLists.txt' printf '%s\n' '--- relevant test order and post-baseline region ---' sed -n '14280,14480p' tests/shaderCfgTests.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 29173 --- </details> **Use a portable environment helper for `KYTY_SHADER_LOOP_LIMIT`.** `shader_cfg_tests` supports Windows Clang toolchains, including `clang-cl`. These unqualified calls use the POSIX `setenv`, which the Windows CRT does not provide. Use a helper that calls `_putenv_s` on Windows and `setenv` elsewhere. Do not add RAII restoration of the original environment value. `main` intentionally sets the watchdog to `"0"` before the suite, and the test restores that same baseline for later tests. <!-- fingerprinting:phantom:medusa:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:dd4b596e2a567ecb7a456d96 --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Confirmed as addressed by @⁠wuboo <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-02 21:12 UTC · original · reviewed

Actionable comments posted: 3

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

14260-14270: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Assert the structured watchdog condition.

The structured case checks only SPIR-V validity and counter allocation. EmitBackEdgeGuard creates and increments that counter independently. Removing GuardLoopCondition can therefore leave these checks passing while the loop cap no longer forces the existing exit. Check the guard operations in the emitted structured-loop SPIR-V.

Suggested fix
     const auto guarded_structured = RecompileForTest(structured_phi, options);
     CheckSpirvBinaryValidates(guarded_structured.spirv);
     Check(MeasureSpirv(guarded_structured.spirv).function_variables >= 1u,
           "loop watchdog added no counter to a structured loop");
+    const auto guarded_structured_source =
+        DisassembleSpirvBinary(guarded_structured.spirv);
+    Check(CountSourceOccurrences(guarded_structured_source, "OpUGreaterThanEqual") == 1u &&
+              CountSourceOccurrences(guarded_structured_source, "OpSelect") == 1u,
+          "loop watchdog did not guard the structured loop condition");
     const auto guarded_dispatcher = RecompileForTest(dispatcher, options);

ℹ️ Review info
⚙️ Run configuration

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

Review profile: CHILL

Plan: Advanced

Run ID: a461b09e-8c1e-490a-a9d2-abd871fa3ef2

📥 Commits

Reviewing files that changed from the base of the PR and between e317465d8a and 2ec78118ddaadc17cfcb3cdda73ef55e9cc1ac33.

📒 Files selected for processing (4)
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp
  • tests/shaderCfgTests.cpp

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

**@⁠coderabbitai[bot]** on GitHub · 2026-10-02 21:12 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/986#pullrequestreview-5396900694) · **reviewed** **Actionable comments posted: 3** <details> <summary>🧹 Nitpick comments (1)</summary><blockquote> <details> <summary>tests/shaderCfgTests.cpp (1)</summary><blockquote> `14260-14270`: _🎯 Functional Correctness_ | _🔵 Trivial_ | _⚡ Quick win_ **Assert the structured watchdog condition.** The structured case checks only SPIR-V validity and counter allocation. `EmitBackEdgeGuard` creates and increments that counter independently. Removing `GuardLoopCondition` can therefore leave these checks passing while the loop cap no longer forces the existing exit. Check the guard operations in the emitted structured-loop SPIR-V. <details> <summary>Suggested fix</summary> ```diff const auto guarded_structured = RecompileForTest(structured_phi, options); CheckSpirvBinaryValidates(guarded_structured.spirv); Check(MeasureSpirv(guarded_structured.spirv).function_variables >= 1u, "loop watchdog added no counter to a structured loop"); + const auto guarded_structured_source = + DisassembleSpirvBinary(guarded_structured.spirv); + Check(CountSourceOccurrences(guarded_structured_source, "OpUGreaterThanEqual") == 1u && + CountSourceOccurrences(guarded_structured_source, "OpSelect") == 1u, + "loop watchdog did not guard the structured loop condition"); const auto guarded_dispatcher = RecompileForTest(dispatcher, options); ``` </details> <!-- cr-comment:v1:431de3f52c90f6077753adf7 --> </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**: `a461b09e-8c1e-490a-a9d2-abd871fa3ef2` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between e317465d8a773b33482ad367ad2f856154c8bc6d and 2ec78118ddaadc17cfcb3cdda73ef55e9cc1ac33. </details> <details> <summary>📒 Files selected for processing (4)</summary> * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp` * `tests/shaderCfgTests.cpp` </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 3 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
@ -724,0 +857,4 @@
state.loop_counter_variables.emplace(info.id, std::pair {counter, merge});
}
}
}
Author
Owner

@⁠wuboo on GitHub · 2026-10-02 21:54 UTC · original

Partly right. Breaks to the loop merge were already capped, but a loop with an unconditional latch and no counted break (or one that only leaves via return) had no edge to force. Fixed in d0c393c5: the latch now branches to the loop merge once the back-edge count reaches the cap. A no-break fixture covers it.

**@⁠wuboo** on GitHub · 2026-10-02 21:54 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/986#discussion_r4170148981) Partly right. Breaks to the loop merge were already capped, but a loop with an unconditional latch and no counted break (or one that only leaves via return) had no edge to force. Fixed in d0c393c5: the latch now branches to the loop merge once the back-edge count reaches the cap. A no-break fixture covers it.
Author
Owner

@⁠wuboo on GitHub · 2026-10-02 21:54 UTC · original
On tests/shaderCfgTests.cpp line 14274 (outdated):

@@ -14256,6 +14256,22 @@ void TestNewShaderRecompilerSpirvSizeBaselines() {
             SpirvInstructionOpcodeCount(dispatcher_result.spirv, 251u) == 1u,
         "dispatcher size fixture lost its two control Phis or switch");
   CheckSpirvPhiParents(dispatcher_result.spirv);
+
+  // The baselines above run with the loop watchdog off. With it on, the guarded
+  // structured loop and the dispatcher loop must still validate and carry a counter.
+  setenv("KYTY_SHADER_LOOP_LIMIT", "65536", 1);
+  {
+    auto options = MakeCompileOptions(ShaderType::Compute);
+    const auto guarded_structured = RecompileForTest(structured_phi, options);
+    CheckSpirvBinaryValidates(guarded_structured.spirv);
+    Check(MeasureSpirv(guarded_structured.spirv).function_variables >= 1u,
+          "loop watchdog added no counter to a structured loop");
+    const auto guarded_dispatcher = RecompileForTest(dispatcher, options);
+    CheckSpirvBinaryValidates(guarded_dispatcher.spirv);
+    Check(SpirvInstructionOpcodeCount(guarded_dispatcher.spirv, 245u) == 3u,
+          "loop watchdog did not count the dispatcher loop");
+  }
+  setenv("KYTY_SHADER_LOOP_LIMIT", "0", 1);

Fixed in def17ab4. The test sets KYTY_SHADER_LOOP_LIMIT through SetEnvForTest(), which uses _putenv_s on Windows and setenv elsewhere.

**@⁠wuboo** on GitHub · 2026-10-02 21:54 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/986#discussion_r4170149121) On `tests/shaderCfgTests.cpp` line 14274 (outdated): ```diff @@ -14256,6 +14256,22 @@ void TestNewShaderRecompilerSpirvSizeBaselines() { SpirvInstructionOpcodeCount(dispatcher_result.spirv, 251u) == 1u, "dispatcher size fixture lost its two control Phis or switch"); CheckSpirvPhiParents(dispatcher_result.spirv); + + // The baselines above run with the loop watchdog off. With it on, the guarded + // structured loop and the dispatcher loop must still validate and carry a counter. + setenv("KYTY_SHADER_LOOP_LIMIT", "65536", 1); + { + auto options = MakeCompileOptions(ShaderType::Compute); + const auto guarded_structured = RecompileForTest(structured_phi, options); + CheckSpirvBinaryValidates(guarded_structured.spirv); + Check(MeasureSpirv(guarded_structured.spirv).function_variables >= 1u, + "loop watchdog added no counter to a structured loop"); + const auto guarded_dispatcher = RecompileForTest(dispatcher, options); + CheckSpirvBinaryValidates(guarded_dispatcher.spirv); + Check(SpirvInstructionOpcodeCount(guarded_dispatcher.spirv, 245u) == 3u, + "loop watchdog did not count the dispatcher loop"); + } + setenv("KYTY_SHADER_LOOP_LIMIT", "0", 1); ``` Fixed in def17ab4. The test sets KYTY_SHADER_LOOP_LIMIT through SetEnvForTest(), which uses _putenv_s on Windows and setenv elsewhere.
@ -362,0 +385,4 @@
return kDefaultLimit;
}
return static_cast<uint32_t>(parsed);
}
Author
Owner

@⁠wuboo on GitHub · 2026-10-02 21:54 UTC · original

Fixed in af3d1fe2. Only a plain decimal overrides the default. An empty, non-numeric, negative or larger-than-u32 value keeps the 65536 cap, and 0 still disables it explicitly.

**@⁠wuboo** on GitHub · 2026-10-02 21:54 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/986#discussion_r4170149263) Fixed in af3d1fe2. Only a plain decimal overrides the default. An empty, non-numeric, negative or larger-than-u32 value keeps the 65536 cap, and 0 still disables it explicitly.
Author
Owner

@⁠wuboo on GitHub · 2026-10-02 21:54 UTC · original

Re the nitpick on asserting the structured condition: def17ab4 makes the structured-loop test count OpUGreaterThanEqual (2: the break and the latch) and OpSelect (1). Without the latch fix the test fails.

**@⁠wuboo** on GitHub · 2026-10-02 21:54 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/986#issuecomment-5962087206) Re the nitpick on asserting the structured condition: def17ab4 makes the structured-loop test count `OpUGreaterThanEqual` (2: the break and the latch) and `OpSelect` (1). Without the latch fix the test fails.
@ -724,0 +857,4 @@
state.loop_counter_variables.emplace(info.id, std::pair {counter, merge});
}
}
}
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-02 21:55 UTC · original

@wuboo Thanks for the clarification. My original claim was too broad: conditional breaks to the loop merge were already capped.

The supplied code now registers unconditional latches and branches to the loop merge when the back-edge count reaches the cap. This addresses the missing exit for loops without a counted break. Thanks for adding the no-break fixture.


✏️ Learnings added
Learnt from: wuboo
Repo: KytyPS5/KytyPS5 PR: 986
File: src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp:835-848
Timestamp: 2026-10-02T21:54:50.565Z
Learning: In KytyPS5's C++ SPIR-V emitter, src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp, conditional breaks to a loop merge can enforce a watchdog cap, but they do not cover an unconditional latch in a loop without a counted break, including a loop that otherwise exits only through return. Check unconditional latches separately; incrementing a back-edge counter alone does not enforce an exit.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

✅ Review thread resolved.

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-02 21:55 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/986#discussion_r4170152252) `@wuboo` Thanks for the clarification. My original claim was too broad: conditional breaks to the loop merge were already capped. The supplied code now registers unconditional latches and branches to the loop merge when the back-edge count reaches the cap. This addresses the missing exit for loops without a counted break. Thanks for adding the no-break fixture. --- <details> <summary>✏️ Learnings added</summary> ``` Learnt from: wuboo Repo: KytyPS5/KytyPS5 PR: 986 File: src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp:835-848 Timestamp: 2026-10-02T21:54:50.565Z Learning: In KytyPS5's C++ SPIR-V emitter, src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp, conditional breaks to a loop merge can enforce a watchdog cap, but they do not cover an unconditional latch in a loop without a counted break, including a loop that otherwise exits only through return. Check unconditional latches separately; incrementing a back-edge counter alone does not enforce an exit. ``` > Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure [review instructions](https://docs.coderabbit.ai/guides/review-instructions). You can manage existing learnings in the [app](https://app.coderabbit.ai/learnings). </details> --- <!-- This is an auto-generated comment: tweet message by coderabbit.ai --> If you found this review helpful, would you consider giving us a shout-out on [X](https://twitter.com/intent/tweet?related=CodeRabbitAI&text=Unconditional%20shader-loop%20latches%20could%20evade%20the%20GPU%20hang%20guard.%20%40coderabbitai%E2%80%99s%20fix%20caps%20back-edges%20and%20adds%20a%20no-break%20test%E2%80%94try%20it%20for%20safer%20shader%20execution!%20%F0%9F%9B%A1%EF%B8%8F&url=https%3A%2F%2Fgithub.com%2FKytyPS5%2FKytyPS5%2Fpull%2F986%23discussion_r4169878001)? Thank you for using CodeRabbit! <!-- end of auto-generated comment: tweet message by coderabbit.ai --> ✅ Review thread resolved. _You are interacting with an AI system._ <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-02 21:55 UTC · original
On tests/shaderCfgTests.cpp line 14274 (outdated):

@@ -14256,6 +14256,22 @@ void TestNewShaderRecompilerSpirvSizeBaselines() {
             SpirvInstructionOpcodeCount(dispatcher_result.spirv, 251u) == 1u,
         "dispatcher size fixture lost its two control Phis or switch");
   CheckSpirvPhiParents(dispatcher_result.spirv);
+
+  // The baselines above run with the loop watchdog off. With it on, the guarded
+  // structured loop and the dispatcher loop must still validate and carry a counter.
+  setenv("KYTY_SHADER_LOOP_LIMIT", "65536", 1);
+  {
+    auto options = MakeCompileOptions(ShaderType::Compute);
+    const auto guarded_structured = RecompileForTest(structured_phi, options);
+    CheckSpirvBinaryValidates(guarded_structured.spirv);
+    Check(MeasureSpirv(guarded_structured.spirv).function_variables >= 1u,
+          "loop watchdog added no counter to a structured loop");
+    const auto guarded_dispatcher = RecompileForTest(dispatcher, options);
+    CheckSpirvBinaryValidates(guarded_dispatcher.spirv);
+    Check(SpirvInstructionOpcodeCount(guarded_dispatcher.spirv, 245u) == 3u,
+          "loop watchdog did not count the dispatcher loop");
+  }
+  setenv("KYTY_SHADER_LOOP_LIMIT", "0", 1);

@wuboo, thanks for the fix. The file now defines SetEnvForTest(), which calls _putenv_s when _WIN32 is defined and setenv otherwise. TestNewShaderRecompilerSpirvSizeBaselines and main call this helper. No bare setenv call remains outside the helper.


If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

✅ Review thread resolved.

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-02 21:55 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/986#discussion_r4170152264) On `tests/shaderCfgTests.cpp` line 14274 (outdated): ```diff @@ -14256,6 +14256,22 @@ void TestNewShaderRecompilerSpirvSizeBaselines() { SpirvInstructionOpcodeCount(dispatcher_result.spirv, 251u) == 1u, "dispatcher size fixture lost its two control Phis or switch"); CheckSpirvPhiParents(dispatcher_result.spirv); + + // The baselines above run with the loop watchdog off. With it on, the guarded + // structured loop and the dispatcher loop must still validate and carry a counter. + setenv("KYTY_SHADER_LOOP_LIMIT", "65536", 1); + { + auto options = MakeCompileOptions(ShaderType::Compute); + const auto guarded_structured = RecompileForTest(structured_phi, options); + CheckSpirvBinaryValidates(guarded_structured.spirv); + Check(MeasureSpirv(guarded_structured.spirv).function_variables >= 1u, + "loop watchdog added no counter to a structured loop"); + const auto guarded_dispatcher = RecompileForTest(dispatcher, options); + CheckSpirvBinaryValidates(guarded_dispatcher.spirv); + Check(SpirvInstructionOpcodeCount(guarded_dispatcher.spirv, 245u) == 3u, + "loop watchdog did not count the dispatcher loop"); + } + setenv("KYTY_SHADER_LOOP_LIMIT", "0", 1); ``` `@wuboo`, thanks for the fix. The file now defines `SetEnvForTest()`, which calls `_putenv_s` when `_WIN32` is defined and `setenv` otherwise. `TestNewShaderRecompilerSpirvSizeBaselines` and `main` call this helper. No bare `setenv` call remains outside the helper. --- <!-- This is an auto-generated comment: tweet message by coderabbit.ai --> If you found this review helpful, would you consider giving us a shout-out on [X](https://twitter.com/intent/tweet?related=CodeRabbitAI&text=%40coderabbitai%20caught%20a%20Windows%20portability%20bug%3A%20use%20_putenv_s%20on%20Windows%20and%20setenv%20elsewhere%20for%20KYTY_SHADER_LOOP_LIMIT.%20Try%20CodeRabbit%20for%20sharper%20PR%20reviews!%20%F0%9F%90%87&url=https%3A%2F%2Fgithub.com%2FKytyPS5%2FKytyPS5%2Fpull%2F986%23discussion_r4169878006)? Thank you for using CodeRabbit! <!-- end of auto-generated comment: tweet message by coderabbit.ai --> ✅ Review thread resolved. _You are interacting with an AI system._ <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-02 22:04 UTC · original · reviewed

Caution

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

⚠️ Outside diff range comments (1)

🟡 Minor · Reject non-digit first characters in the plain-decimal parser. · spirvEmitterInternal.h:354-361

src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h:354-361
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Reject non-digit first characters in the plain-decimal parser.

std::strtoull accepts leading + and whitespace. The current guard rejects - but accepts +0 and 0, which return zero. ShaderLoopLimit() == 0 disables the loop watchdog and atomic-update cap. These malformed values should retain kDefaultLimit; explicit 0 remains a valid opt-out.

Suggested fix
-if (*end != '\0' || parsed > UINT32_MAX || *value == '-') {
+if (*end != '\0' || parsed > UINT32_MAX || *value < '0' || *value > '9') {
🧹 Nitpick comments (1)
tests/shaderCfgTests.cpp (1)

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

Add the direct conditional-latch fixture to the watchdog block.

The current watchdog checks cover a conditional break and unconditional latches only. The existing direct conditional-latch test at tests/shaderCfgTests.cpp:8186-8193 checks structured emission, but it runs with the watchdog disabled and does not inspect OpUGreaterThanEqual or OpSelect.

Add this focused fixture to the watchdog block. Its s_cbranch_scc1 targets the loop header, and its fallthrough reaches the loop merge. Assert one OpUGreaterThanEqual and one OpSelect.

Suggested fix
     Check(CountSourceOccurrences(guarded_source, "OpUGreaterThanEqual") == 2u &&
               CountSourceOccurrences(guarded_source, "OpSelect") == 1u,
           "loop watchdog did not guard the structured loop break and latch");
+    const uint32_t conditional_latch[] = {
+        EncodeSopp(0x02, 0),       // loop header -> conditional latch
+        EncodeSopc(0x06, 0, 0),    // s_cmp_eq_u32 s0, s0
+        EncodeSopp(0x05, 0xfffdu), // conditional backedge -> loop header
+        EncodeSopp(0x01),
+    };
+    const auto guarded_conditional =
+        RecompileForTest(conditional_latch, options);
+    CheckSpirvBinaryValidates(guarded_conditional.spirv);
+    const auto conditional_source =
+        DisassembleSpirvBinary(guarded_conditional.spirv);
+    Check(CountSourceOccurrences(conditional_source, "OpUGreaterThanEqual") == 1u &&
+              CountSourceOccurrences(conditional_source, "OpSelect") == 1u,
+          "loop watchdog did not guard the conditional backedge");
     const uint32_t endless[] = {

ℹ️ Review info
⚙️ Run configuration

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

Review profile: CHILL

Plan: Advanced

Run ID: b5ae0941-6fc1-42f8-9e92-b604648d6a56

📥 Commits

Reviewing files that changed from the base of the PR and between 2ec78118ddaadc17cfcb3cdda73ef55e9cc1ac33 and def17ab4a27512413f329a5dd50c4b9505dbd080.

📒 Files selected for processing (3)
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp
  • tests/shaderCfgTests.cpp
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h
  • tests/shaderCfgTests.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp

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

**@⁠coderabbitai[bot]** on GitHub · 2026-10-02 22:04 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/986#pullrequestreview-5397294474) · **reviewed** > [!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>🟡 Minor</em> · Reject non-digit first characters in the plain-decimal parser. · <code>spirvEmitterInternal.h:354-361</code></summary><blockquote> > > `src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h:354-361` > _🩺 Stability & Availability_ | _🟡 Minor_ | _⚡ Quick win_ > > **Reject non-digit first characters in the plain-decimal parser.** > > `std::strtoull` accepts leading `+` and whitespace. The current guard rejects `-` but accepts `+0` and ` 0`, which return zero. `ShaderLoopLimit() == 0` disables the loop watchdog and atomic-update cap. These malformed values should retain `kDefaultLimit`; explicit `0` remains a valid opt-out. > > <details><summary>Suggested fix</summary> > > ```diff > -if (*end != '\0' || parsed > UINT32_MAX || *value == '-') { > +if (*end != '\0' || parsed > UINT32_MAX || *value < '0' || *value > '9') { > ``` > > </details> > > <!-- cr-comment:v1:52b951b4aed651601b171e16 --> > > </blockquote></details> <details> <summary>🧹 Nitpick comments (1)</summary><blockquote> <details> <summary>tests/shaderCfgTests.cpp (1)</summary><blockquote> `14277-14291`: _📐 Maintainability & Code Quality_ | _🔵 Trivial_ | _⚡ Quick win_ **Add the direct conditional-latch fixture to the watchdog block.** The current watchdog checks cover a conditional break and unconditional latches only. The existing direct conditional-latch test at `tests/shaderCfgTests.cpp:8186-8193` checks structured emission, but it runs with the watchdog disabled and does not inspect `OpUGreaterThanEqual` or `OpSelect`. Add this focused fixture to the watchdog block. Its `s_cbranch_scc1` targets the loop header, and its fallthrough reaches the loop merge. Assert one `OpUGreaterThanEqual` and one `OpSelect`. <details> <summary>Suggested fix</summary> ```diff Check(CountSourceOccurrences(guarded_source, "OpUGreaterThanEqual") == 2u && CountSourceOccurrences(guarded_source, "OpSelect") == 1u, "loop watchdog did not guard the structured loop break and latch"); + const uint32_t conditional_latch[] = { + EncodeSopp(0x02, 0), // loop header -> conditional latch + EncodeSopc(0x06, 0, 0), // s_cmp_eq_u32 s0, s0 + EncodeSopp(0x05, 0xfffdu), // conditional backedge -> loop header + EncodeSopp(0x01), + }; + const auto guarded_conditional = + RecompileForTest(conditional_latch, options); + CheckSpirvBinaryValidates(guarded_conditional.spirv); + const auto conditional_source = + DisassembleSpirvBinary(guarded_conditional.spirv); + Check(CountSourceOccurrences(conditional_source, "OpUGreaterThanEqual") == 1u && + CountSourceOccurrences(conditional_source, "OpSelect") == 1u, + "loop watchdog did not guard the conditional backedge"); const uint32_t endless[] = { ``` </details> <!-- cr-comment:v1:dad2f9d844dabadd00101e7a --> </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**: `b5ae0941-6fc1-42f8-9e92-b604648d6a56` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 2ec78118ddaadc17cfcb3cdda73ef55e9cc1ac33 and def17ab4a27512413f329a5dd50c4b9505dbd080. </details> <details> <summary>📒 Files selected for processing (3)</summary> * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp` * `tests/shaderCfgTests.cpp` </details> <details> <summary>🚧 Files skipped from review as they are similar to previous changes (3)</summary> * src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h * tests/shaderCfgTests.cpp * src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 1 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
@ -362,0 +385,4 @@
return kDefaultLimit;
}
return static_cast<uint32_t>(parsed);
}
Author
Owner

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

@wuboo Thanks for the fix. Invalid non-numeric input now retains the 65,536 cap instead of disabling the watchdog. Explicit 0 still disables it.


If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

✅ Review thread resolved.

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-02 22:07 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/986#discussion_r4170224342) `@wuboo` Thanks for the fix. Invalid non-numeric input now retains the 65,536 cap instead of disabling the watchdog. Explicit `0` still disables it. --- <!-- This is an auto-generated comment: tweet message by coderabbit.ai --> If you found this review helpful, would you consider giving us a shout-out on [X](https://twitter.com/intent/tweet?related=CodeRabbitAI&text=A%20typo%20in%20%60KYTY_SHADER_LOOP_LIMIT%60%20shouldn%E2%80%99t%20silently%20disable%20GPU-hang%20protection.%20%40coderabbitai%20recommends%20defaulting%20invalid%20input%20to%2065%2C536%20while%20preserving%20explicit%20%600%60%E2%80%94try%20CodeRabbit%20for%20sharp%20reviews!%20%F0%9F%9B%A1%EF%B8%8F&url=https%3A%2F%2Fgithub.com%2FKytyPS5%2FKytyPS5%2Fpull%2F986%23discussion_r4169877981)? Thank you for using CodeRabbit! <!-- end of auto-generated comment: tweet message by coderabbit.ai --> ✅ Review thread resolved. _You are interacting with an AI system._ <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

@⁠wuboo on GitHub · 2026-10-02 22:19 UTC · original

Second round:

  • Parser (outside-diff Minor): fixed in e62940de. strtoull skips leading whitespace and accepts a sign, so +0 and 0 parsed as 0 and turned the watchdog off. The value now has to start with a digit; otherwise the default cap stays. An explicit 0 still disables it. +0 and 0 are added to the bad-value checks, and with the old parser the test fails.
  • Direct conditional latch (nitpick): added in 44a858b4. The fixture runs with the limit on and asserts exactly one OpUGreaterThanEqual and one OpSelect. The same check fails with the limit at 0.

Full CPU ctest matches main: 34 pass. The 16 Vulkan-dependent tests can't run in my headless setup on either side.

**@⁠wuboo** on GitHub · 2026-10-02 22:19 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/986#issuecomment-5962371925) Second round: - **Parser (outside-diff Minor):** fixed in e62940de. `strtoull` skips leading whitespace and accepts a sign, so `+0` and ` 0` parsed as 0 and turned the watchdog off. The value now has to start with a digit; otherwise the default cap stays. An explicit `0` still disables it. `+0` and ` 0` are added to the bad-value checks, and with the old parser the test fails. - **Direct conditional latch (nitpick):** added in 44a858b4. The fixture runs with the limit on and asserts exactly one `OpUGreaterThanEqual` and one `OpSelect`. The same check fails with the limit at 0. Full CPU `ctest` matches main: 34 pass. The 16 Vulkan-dependent tests can't run in my headless setup on either side.
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-02 22:26 UTC · original · reviewed

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 treat a retry-limit exit as a completed atomic update. · spirvEmitterInternal.h:601-622

src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h:601-622
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Do not treat a retry-limit exit as a completed atomic update.

When every CAS fails, AtomicUpdate can branch to merge because iteration >= ShaderLoopLimit(), even though no exchange succeeded. It then returns observed without a success indicator. The reachable non-scratch U8/U16 store path ignores that return value, so it can complete without writing the requested bits. Keep this failure visible at the AtomicUpdate boundary and handle it explicitly for each caller. The watchdog intent does not satisfy the atomic store contract.


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 550644da-07cc-43f9-bd14-2c2efa70062e
📥 Commits

Reviewing files that changed from the base of the PR and between def17ab4a27512413f329a5dd50c4b9505dbd080 and 44a858b40407991f790381300b57bafdf62db153.

📒 Files selected for processing (2)
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h
  • 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-10-02 22:26 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/986#pullrequestreview-5397431058) · **reviewed** > [!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 treat a retry-limit exit as a completed atomic update. · <code>spirvEmitterInternal.h:601-622</code></summary><blockquote> > > `src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h:601-622` > _🗄️ Data Integrity & Integration_ | _🟠 Major_ | _🏗️ Heavy lift_ > > **Do not treat a retry-limit exit as a completed atomic update.** > > When every CAS fails, `AtomicUpdate` can branch to `merge` because `iteration >= ShaderLoopLimit()`, even though no exchange succeeded. It then returns `observed` without a success indicator. The reachable non-scratch U8/U16 store path ignores that return value, so it can complete without writing the requested bits. Keep this failure visible at the `AtomicUpdate` boundary and handle it explicitly for each caller. The watchdog intent does not satisfy the atomic store contract. > > <!-- cr-comment:v1:5e4b4728930c39fd0c89ef4d --> > > </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**: `550644da-07cc-43f9-bd14-2c2efa70062e` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between def17ab4a27512413f329a5dd50c4b9505dbd080 and 44a858b40407991f790381300b57bafdf62db153. </details> <details> <summary>📒 Files selected for processing (2)</summary> * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h` * `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

@⁠rohit267 on GitHub · 2026-10-05 13:16 UTC · original

Tested this on Black Myth: Wukong (PPSA23226, RTX 4070, driver 595.71) together with #985. Both are needed there: #985 alone still ends in VK_ERROR_DEVICE_LOST on the UE5 Nanite persistent-culling shader, and with both applied the game boots to its title and menu.

One bug in the forced-exit path. In EmitStructuredTerminator, the "unconditional latch" case replaces OpBranch target with OpBranchConditional(over, exit, target). That is a new edge into the exit block, which the comment says it is not. If the exit block starts with an OpPhi, the phi is one incoming value short and the module fails validation:

OpPhi's number of incoming blocks (2) does not match block's predecessor count (3)

NVIDIA's compiler does not reject it. nvgpucomp64.dll dereferences a not-found index of -1 and the process dies with an access violation inside the driver DLL, so the symptom looks like a driver crash rather than a bad module. --shader-validation true reports it immediately.

Fix: do not force the exit when the exit block begins with a phi; those loops keep the conditional exit they already have. The patch is 14 lines in spirvEmitterProgram.cpp (BlockStartsWithPhi plus one extra condition) and is attached below.

Related note for tuning: with the 65536 default the Wukong boot/loading screen runs at about 1 fps; at KYTY_SHADER_LOOP_LIMIT=4096 the title screen runs at 5-6 fps and at 512 at about 8 fps. GPU timestamps show the three Nanite persistent-culling dispatches (1440 groups each) taking ~13-20 ms each at 4096 and ~2.6-3.1 ms at 512, i.e. their time scales with the cap, so their loops are still reaching the cap rather than exiting on their own, even with #985 applied.

diff --git a/src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp b/src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp
index 6f726dc..ce054ae 100644
--- a/src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp
+++ b/src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp
@@ -109,6 +109,19 @@ uint32_t GuardLoopCondition(ValueEmitContext& ctx, const IR::BlockInfo& info, ui
 	return guarded;
 }
 
+// A forced exit from an unconditional latch is a NEW edge into the exit block, so a phi
+// there would be left one incoming value short and the module fails validation. Those loops
+// keep whatever conditional exit they already had instead.
+bool BlockStartsWithPhi(const IR::Block* block) {
+	if (block == nullptr) {
+		return true;
+	}
+	for (const auto& inst: *block) {
+		return inst.GetOpcode() == IR::ValueOpcode::Phi;
+	}
+	return false;
+}
+
 const IR::Block* TargetBlock(const IR::Program& program, uint32_t id) {
 	const auto found = std::ranges::find_if(
 	    program.block_info, [&](const IR::BlockInfo& info) { return info.id == id; });
@@ -157,7 +170,7 @@ void EmitStructuredTerminator(ValueEmitContext& ctx, const IR::Block* block,
 			if (const auto* exit = latch != ctx.state.loop_counter_variables.end()
 			                           ? TargetBlock(program, latch->second.second)
 			                           : nullptr;
-			    exit != nullptr) {
+			    exit != nullptr && !BlockStartsWithPhi(exit)) {
 				ctx.state.builder.AddFunction(spv::OpBranchConditional,
 				                              LoopCapReached(ctx, latch->second.first),
 				                              ctx.Label(exit), ctx.Label(target));
**@⁠rohit267** on GitHub · 2026-10-05 13:16 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/986#issuecomment-5995226943) Tested this on Black Myth: Wukong (PPSA23226, RTX 4070, driver 595.71) together with #985. Both are needed there: #985 alone still ends in VK_ERROR_DEVICE_LOST on the UE5 Nanite persistent-culling shader, and with both applied the game boots to its title and menu. One bug in the forced-exit path. In `EmitStructuredTerminator`, the "unconditional latch" case replaces `OpBranch target` with `OpBranchConditional(over, exit, target)`. That is a new edge into the exit block, which the comment says it is not. If the exit block starts with an `OpPhi`, the phi is one incoming value short and the module fails validation: OpPhi's number of incoming blocks (2) does not match block's predecessor count (3) NVIDIA's compiler does not reject it. `nvgpucomp64.dll` dereferences a not-found index of -1 and the process dies with an access violation inside the driver DLL, so the symptom looks like a driver crash rather than a bad module. `--shader-validation true` reports it immediately. Fix: do not force the exit when the exit block begins with a phi; those loops keep the conditional exit they already have. The patch is 14 lines in `spirvEmitterProgram.cpp` (`BlockStartsWithPhi` plus one extra condition) and is attached below. Related note for tuning: with the 65536 default the Wukong boot/loading screen runs at about 1 fps; at `KYTY_SHADER_LOOP_LIMIT=4096` the title screen runs at 5-6 fps and at 512 at about 8 fps. GPU timestamps show the three Nanite persistent-culling dispatches (1440 groups each) taking ~13-20 ms each at 4096 and ~2.6-3.1 ms at 512, i.e. their time scales with the cap, so their loops are still reaching the cap rather than exiting on their own, even with #985 applied. ```diff diff --git a/src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp b/src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp index 6f726dc..ce054ae 100644 --- a/src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp +++ b/src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp @@ -109,6 +109,19 @@ uint32_t GuardLoopCondition(ValueEmitContext& ctx, const IR::BlockInfo& info, ui return guarded; } +// A forced exit from an unconditional latch is a NEW edge into the exit block, so a phi +// there would be left one incoming value short and the module fails validation. Those loops +// keep whatever conditional exit they already had instead. +bool BlockStartsWithPhi(const IR::Block* block) { + if (block == nullptr) { + return true; + } + for (const auto& inst: *block) { + return inst.GetOpcode() == IR::ValueOpcode::Phi; + } + return false; +} + const IR::Block* TargetBlock(const IR::Program& program, uint32_t id) { const auto found = std::ranges::find_if( program.block_info, [&](const IR::BlockInfo& info) { return info.id == id; }); @@ -157,7 +170,7 @@ void EmitStructuredTerminator(ValueEmitContext& ctx, const IR::Block* block, if (const auto* exit = latch != ctx.state.loop_counter_variables.end() ? TargetBlock(program, latch->second.second) : nullptr; - exit != nullptr) { + exit != nullptr && !BlockStartsWithPhi(exit)) { ctx.state.builder.AddFunction(spv::OpBranchConditional, LoopCapReached(ctx, latch->second.first), ctx.Label(exit), ctx.Label(target)); ```
Author
Owner

@⁠wuboo on GitHub · 2026-10-05 13:50 UTC · original

Thanks for testing this on Wukong, and for the patch. That's a real bug: the forced exit from an unconditional latch adds an edge into the exit block, so a leading OpPhi ends up one incoming value short. NVIDIA's compiler crashing on it instead of rejecting it matches what you saw.

I took your approach: loops whose exit block starts with a phi keep the exit they already have, and don't get the forced one. I considered adding a phi operand for the new edge instead, but there is no real value to supply for an edge that never carried data, so skipping is simpler and safer. Your change is in the branch with you as co-author, plus a test: an unconditional latch whose exit block reads a phi. Without the change it fails validation with exactly the 2-vs-3 error you quoted; with it, it passes. The other CPU tests are unchanged.

On the limit: 65536 is a correctness safety net, not a performance setting. If the Nanite persistent-culling loops still hit the cap at 4096 and 512 (their time scaling with the cap), they aren't exiting on their own. That looks like a separate problem, probably in how that shader's loop condition is translated, so I'd track it in its own issue rather than tune the default here. If you can share the shader hash or a dump, that would help.

**@⁠wuboo** on GitHub · 2026-10-05 13:50 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/986#issuecomment-5995825617) Thanks for testing this on Wukong, and for the patch. That's a real bug: the forced exit from an unconditional latch adds an edge into the exit block, so a leading `OpPhi` ends up one incoming value short. NVIDIA's compiler crashing on it instead of rejecting it matches what you saw. I took your approach: loops whose exit block starts with a phi keep the exit they already have, and don't get the forced one. I considered adding a phi operand for the new edge instead, but there is no real value to supply for an edge that never carried data, so skipping is simpler and safer. Your change is in the branch with you as co-author, plus a test: an unconditional latch whose exit block reads a phi. Without the change it fails validation with exactly the 2-vs-3 error you quoted; with it, it passes. The other CPU tests are unchanged. On the limit: 65536 is a correctness safety net, not a performance setting. If the Nanite persistent-culling loops still hit the cap at 4096 and 512 (their time scaling with the cap), they aren't exiting on their own. That looks like a separate problem, probably in how that shader's loop condition is translated, so I'd track it in its own issue rather than tune the default here. If you can share the shader hash or a dump, that would help.
Author
Owner

@⁠rohit267 on GitHub · 2026-10-05 15:09 UTC · original

Thanks for testing this on Wukong, and for the patch. That's a real bug: the forced exit from an unconditional latch adds an edge into the exit block, so a leading OpPhi ends up one incoming value short. NVIDIA's compiler crashing on it instead of rejecting it matches what you saw.

I took your approach: loops whose exit block starts with a phi keep the exit they already have, and don't get the forced one. I considered adding a phi operand for the new edge instead, but there is no real value to supply for an edge that never carried data, so skipping is simpler and safer. Your change is in the branch with you as co-author, plus a test: an unconditional latch whose exit block reads a phi. Without the change it fails validation with exactly the 2-vs-3 error you quoted; with it, it passes. The other CPU tests are unchanged.

On the limit: 65536 is a correctness safety net, not a performance setting. If the Nanite persistent-culling loops still hit the cap at 4096 and 512 (their time scaling with the cap), they aren't exiting on their own. That looks like a separate problem, probably in how that shader's loop condition is translated, so I'd track it in its own issue rather than tune the default here. If you can share the shader hash or a dump, that would help.

Thanks, and thanks for the co-author credit.

Shader details for the loop-cap issue. Black Myth: Wukong (PPSA23226, v01.000.021), RTX 4070, Windows, #985 + #986 applied.

The Nanite persistent-culling compute shaders are all dispatched as 1440 groups x 64 threads (GPU time per dispatch, from Vulkan timestamp queries):

  • 539ebc039e965dfd: 20.4 ms at cap 4096, 2.6 ms at cap 512
  • 7851ac82b44e6ec6: 18.7 ms at 4096, 10.6 ms at 2048, 3.1 ms at 512
  • 1a77a43e9fa6a44e: 13.6 ms at 4096, 5.8 ms at 2048
  • 70a429e729343769: same dispatch shape; 13.1 ms at 4096 (not measured at other caps)

That is close to linear in the cap, so every group runs to the cap.

539ebc039e965dfd in Kyty's log: code_words=4448, 3047 decoded instructions, CFG 132 blocks / 3 loops / 3 back edges (157 blocks after structurizing), 283072 SPIR-V words, wave64, 64 S_CBRANCH_EXECZ.

What I saw in the decoded RDNA2 listing of 539ebc039e965dfd:

  • The back edge is s_branch 0x100 at 0x4198, with s_endpgm at 0x419c. The only branches to the endpgm are s_cbranch_vccnz at 0x2c0 and 0x324.
  • The 0x2c0 exit needs v36 == 0 && s58 <= LDS[0]. LDS[0] holds the old value returned by buffer_atomic_add v1(=1), ... offset:4 glc, a claim counter that lane 0 writes with exec=1.
  • The constant buffer has dword[4]=0x00800000, so s58 = 0x20000, and dword[68]=0x00200000, which is s60. They look like capacities (8M and 2M) rather than produced-work counts.
  • v36 only becomes 0 on the path at 0x190, when a 16-wide slot claim (buffer_atomic_add ... 16, offset:12) returns an index >= s60.
  • Slots are 8 bytes with 0xFFFFFFFF/0xFFFFFFFF as the empty marker. Loads at 0x1bc use glc+dlc, and consumed slots are reset with buffer_store_dwordx2 -1,-1 glc at 0x417c.
  • A 44-byte state buffer read from the CPU at dispatch time had 0x23b2 in dwords 4 and 5. That is a CPU-side view and may be stale.

I deleted the game and my dumps, so I can't attadentifies the shader in any Wukong run. Happy toopen this as its own issue.

**@⁠rohit267** on GitHub · 2026-10-05 15:09 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/986#issuecomment-5997268020) > Thanks for testing this on Wukong, and for the patch. That's a real bug: the forced exit from an unconditional latch adds an edge into the exit block, so a leading `OpPhi` ends up one incoming value short. NVIDIA's compiler crashing on it instead of rejecting it matches what you saw. > > I took your approach: loops whose exit block starts with a phi keep the exit they already have, and don't get the forced one. I considered adding a phi operand for the new edge instead, but there is no real value to supply for an edge that never carried data, so skipping is simpler and safer. Your change is in the branch with you as co-author, plus a test: an unconditional latch whose exit block reads a phi. Without the change it fails validation with exactly the 2-vs-3 error you quoted; with it, it passes. The other CPU tests are unchanged. > > On the limit: 65536 is a correctness safety net, not a performance setting. If the Nanite persistent-culling loops still hit the cap at 4096 and 512 (their time scaling with the cap), they aren't exiting on their own. That looks like a separate problem, probably in how that shader's loop condition is translated, so I'd track it in its own issue rather than tune the default here. If you can share the shader hash or a dump, that would help. Thanks, and thanks for the co-author credit. Shader details for the loop-cap issue. Black Myth: Wukong (PPSA23226, v01.000.021), RTX 4070, Windows, #985 + #986 applied. The Nanite persistent-culling compute shaders are all dispatched as 1440 groups x 64 threads (GPU time per dispatch, from Vulkan timestamp queries): - 539ebc039e965dfd: 20.4 ms at cap 4096, 2.6 ms at cap 512 - 7851ac82b44e6ec6: 18.7 ms at 4096, 10.6 ms at 2048, 3.1 ms at 512 - 1a77a43e9fa6a44e: 13.6 ms at 4096, 5.8 ms at 2048 - 70a429e729343769: same dispatch shape; 13.1 ms at 4096 (not measured at other caps) That is close to linear in the cap, so every group runs to the cap. 539ebc039e965dfd in Kyty's log: code_words=4448, 3047 decoded instructions, CFG 132 blocks / 3 loops / 3 back edges (157 blocks after structurizing), 283072 SPIR-V words, wave64, 64 S_CBRANCH_EXECZ. What I saw in the decoded RDNA2 listing of 539ebc039e965dfd: - The back edge is `s_branch 0x100` at 0x4198, with `s_endpgm` at 0x419c. The only branches to the endpgm are `s_cbranch_vccnz` at 0x2c0 and 0x324. - The 0x2c0 exit needs `v36 == 0 && s58 <= LDS[0]`. LDS[0] holds the old value returned by `buffer_atomic_add v1(=1), ... offset:4 glc`, a claim counter that lane 0 writes with exec=1. - The constant buffer has dword[4]=0x00800000, so s58 = 0x20000, and dword[68]=0x00200000, which is s60. They look like capacities (8M and 2M) rather than produced-work counts. - v36 only becomes 0 on the path at 0x190, when a 16-wide slot claim (`buffer_atomic_add ... 16, offset:12`) returns an index >= s60. - Slots are 8 bytes with 0xFFFFFFFF/0xFFFFFFFF as the empty marker. Loads at 0x1bc use glc+dlc, and consumed slots are reset with `buffer_store_dwordx2 -1,-1 glc` at 0x417c. - A 44-byte state buffer read from the CPU at dispatch time had 0x23b2 in dwords 4 and 5. That is a CPU-side view and may be stale. I deleted the game and my dumps, so I can't attadentifies the shader in any Wukong run. Happy toopen this as its own issue.
Author
Owner

@⁠wuboo on GitHub · 2026-10-05 15:35 UTC · original

Thanks, that's a very useful breakdown. Yes, please open it as its own issue with these numbers and the listing notes; it's a separate problem from this PR.

From your description, the loop only leaves through the two s_cbranch_vccnz exits, and both depend on the claim counters at offsets 4 and 12 crossing the capacities in the constant buffer. Every group running to the cap suggests those counters never reach the exit condition on our side. Three things I'd check first, none of them verified yet:

  • whether the counters (and the -1 slot markers) are reset before each dispatch. If the reset is a CP fill/DMA or a small compute pass that we skip or reorder, the shader starts from a state where the exit can't be reached. The 0x23b2 you saw in the CPU-side view may be stale for the same reason.
  • how the buffer_atomic_add ... glc return value written by lane 0 with exec=1 reaches LDS[0] and the other lanes on a wave64 shader. We recently found a DPP lane op that silently degraded to identity, so a cross-lane path here is worth a targeted test.
  • forward progress between workgroups. A persistent-threads queue assumes producer groups keep running while consumers spin.

If you can dump the counter values at offsets 4 and 12 right before and after one of these dispatches, that would show which of the three it is.

**@⁠wuboo** on GitHub · 2026-10-05 15:35 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/986#issuecomment-5997740946) Thanks, that's a very useful breakdown. Yes, please open it as its own issue with these numbers and the listing notes; it's a separate problem from this PR. From your description, the loop only leaves through the two `s_cbranch_vccnz` exits, and both depend on the claim counters at offsets 4 and 12 crossing the capacities in the constant buffer. Every group running to the cap suggests those counters never reach the exit condition on our side. Three things I'd check first, none of them verified yet: - whether the counters (and the `-1` slot markers) are reset before each dispatch. If the reset is a CP fill/DMA or a small compute pass that we skip or reorder, the shader starts from a state where the exit can't be reached. The `0x23b2` you saw in the CPU-side view may be stale for the same reason. - how the `buffer_atomic_add ... glc` return value written by lane 0 with `exec=1` reaches `LDS[0]` and the other lanes on a wave64 shader. We recently found a DPP lane op that silently degraded to identity, so a cross-lane path here is worth a targeted test. - forward progress between workgroups. A persistent-threads queue assumes producer groups keep running while consumers spin. If you can dump the counter values at offsets 4 and 12 right before and after one of these dispatches, that would show which of the three it is.
Author
Owner

@⁠rohit267 on GitHub · 2026-10-05 15:46 UTC · original

Opened #1072 with the numbers and the listing notes. On the counters: I only have one before-dispatch snapshot, and it is the CPU-side view, so it may be stale. Offsets 4 and 12 read 0 and 0, offsets 16 and 20 read 0x23b2, and the slot queue started with zeros rather than 0xFFFFFFFF. I don't have after-dispatch values, and I've removed my Wukong setup, so I can't capture them now. #1072 has a short snippet that does a before/after dump; could you or someone with the game run it?

**@⁠rohit267** on GitHub · 2026-10-05 15:46 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/986#issuecomment-5997927254) Opened #1072 with the numbers and the listing notes. On the counters: I only have one before-dispatch snapshot, and it is the CPU-side view, so it may be stale. Offsets 4 and 12 read 0 and 0, offsets 16 and 20 read 0x23b2, and the slot queue started with zeros rather than 0xFFFFFFFF. I don't have after-dispatch values, and I've removed my Wukong setup, so I can't capture them now. #1072 has a short snippet that does a before/after dump; could you or someone with the game run it?
Author
Owner

@⁠overlordxrz-source on GitHub · 2026-10-05 22:04 UTC · original

Verified this branch locally (reviewed the diff, built and tested rather than just reading):

  • shader_cfg_tests: Passed (2.0s)
  • scalar_provenance_tests + resource_tracking_tests: Passed
  • Target: x86_64 macOS no-Qt build (CMAKE_OSX_ARCHITECTURES=x86_64, clang, KYTY_BUILD_LAUNCHER=OFF), Release — links clean (only the usual prebuilt-FFmpeg platform warnings).

GPU-harness tests were not runnable here (no Vulkan loader in this environment — same pre-existing failure as on clean main).

One heads-up for landing: this branch no longer rebases cleanly onto current main (cdb64bf). spirvEmitterMemory.cpp was refactored to ConstantDeviceAddress after this branch's base, so the BDA out-of-range-guard hunk needs a semantic re-merge (keep the in_range/out_of_range guard, port it onto the ConstantDeviceAddress helpers). spirvEmitterInternal.h / spirvEmitterProgram.cpp / shaderCfgTests.cpp hunks are pure additions and apply cleanly.

The watchdog approach (force an existing exit at 65536, KYTY_SHADER_LOOP_LIMIT override, 0 disables) looks right as a safety net for the Wukong Nanite spin in #1072 — it turns a kill-the-process hang into bounded GPU time while the real forward-progress root cause is investigated.

**@⁠overlordxrz-source** on GitHub · 2026-10-05 22:04 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/986#issuecomment-6004011012) Verified this branch locally (reviewed the diff, built and tested rather than just reading): - `shader_cfg_tests`: Passed (2.0s) - `scalar_provenance_tests` + `resource_tracking_tests`: Passed - Target: `x86_64` macOS no-Qt build (`CMAKE_OSX_ARCHITECTURES=x86_64`, clang, `KYTY_BUILD_LAUNCHER=OFF`), Release — links clean (only the usual prebuilt-FFmpeg platform warnings). GPU-harness tests were not runnable here (no Vulkan loader in this environment — same pre-existing failure as on clean main). One heads-up for landing: this branch no longer rebases cleanly onto current `main` (`cdb64bf`). `spirvEmitterMemory.cpp` was refactored to `ConstantDeviceAddress` after this branch's base, so the BDA out-of-range-guard hunk needs a semantic re-merge (keep the `in_range`/`out_of_range` guard, port it onto the `ConstantDeviceAddress` helpers). `spirvEmitterInternal.h` / `spirvEmitterProgram.cpp` / `shaderCfgTests.cpp` hunks are pure additions and apply cleanly. The watchdog approach (force an existing exit at 65536, `KYTY_SHADER_LOOP_LIMIT` override, `0` disables) looks right as a safety net for the Wukong Nanite spin in #1072 — it turns a kill-the-process hang into bounded GPU time while the real forward-progress root cause is investigated.
Author
Owner

@⁠wuboo on GitHub · 2026-10-05 23:19 UTC · original

Thanks for checking this against current main, and for the pointer to the spirvEmitterMemory.cpp rework.

I rebased the branch onto current main (cdb64bfd). The conflict was only in the BDA page-table guard in DefineGetBdaPointer. spirvEmitterInternal.h, spirvEmitterProgram.cpp and shaderCfgTests.cpp applied as plain additions. I kept the guard's semantics (in_range on the page index, an out-of-range page is treated as a missing page, page 0 only as a safe index for the load) and re-expressed it with the helpers that function uses on current main. Note that main no longer has ConstantDeviceAddress anywhere in src, and DefineGetBdaPointer now uses ConstantU64/ConstantU32, so the guard uses those: ULessThan(page64, ConstantU64(CACHING_NUMPAGES)), then Select for the index, then LogicalOr(base == 0, !in_range) for the fault path.

Testing: the full ctest list matches a fresh build of main exactly (the same tests need a GPU and are skipped here in both runs). shader_cfg passes. I also checked the new tests fail without the fixes: with the emitter changes removed the watchdog test aborts, and without the phi fix spirv-val rejects the OpPhi.

The Co-authored-by trailer for Rohit Mahto on the phi fix is preserved.

**@⁠wuboo** on GitHub · 2026-10-05 23:19 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/986#issuecomment-6005262130) Thanks for checking this against current main, and for the pointer to the `spirvEmitterMemory.cpp` rework. I rebased the branch onto current `main` (cdb64bfd). The conflict was only in the BDA page-table guard in `DefineGetBdaPointer`. `spirvEmitterInternal.h`, `spirvEmitterProgram.cpp` and `shaderCfgTests.cpp` applied as plain additions. I kept the guard's semantics (`in_range` on the page index, an out-of-range page is treated as a missing page, page 0 only as a safe index for the load) and re-expressed it with the helpers that function uses on current main. Note that main no longer has `ConstantDeviceAddress` anywhere in `src`, and `DefineGetBdaPointer` now uses `ConstantU64`/`ConstantU32`, so the guard uses those: `ULessThan(page64, ConstantU64(CACHING_NUMPAGES))`, then `Select` for the index, then `LogicalOr(base == 0, !in_range)` for the fault path. Testing: the full ctest list matches a fresh build of main exactly (the same tests need a GPU and are skipped here in both runs). `shader_cfg` passes. I also checked the new tests fail without the fixes: with the emitter changes removed the watchdog test aborts, and without the phi fix spirv-val rejects the OpPhi. The Co-authored-by trailer for Rohit Mahto on the phi fix is preserved.
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-05 23:29 UTC · original · reviewed

Caution

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

⚠️ Outside diff range comments (1)

🟠 Major · Force the cap through an existing Phi-valid break path. · spirvEmitterProgram.cpp:168-178

src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp:168-178
🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Force the cap through an existing Phi-valid break path.

When an If arm contains Break, CFG lowering branches to the arm’s body, then emits a separate unconditional branch from that body to the loop merge. The watchdog guards conditional branches only when they target the merge directly. If the merge starts with OpPhi, BlockStartsWithPhi also suppresses the latch’s synthetic exit. A loop with only nested break exits can therefore increment its counter and keep taking non-break paths without testing the limit. Route the cap through an existing break path so the merge retains a valid Phi predecessor.


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 6c4376a0-ed01-4cdb-b925-d610bba5cc76
📥 Commits

Reviewing files that changed from the base of the PR and between 05eac940afad6c7c9794ac554ae0fdc82a5df41d and fb0aec0bad.

📒 Files selected for processing (4)
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.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-10-05 23:29 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/986#pullrequestreview-5421926496) · **reviewed** > [!CAUTION] > Some comments are outside the diff and can’t be posted inline due to GitHub limitations. > > **⚠️ Outside diff range comments (1)** > > <details> > <summary><strong>🟠 Major</strong> · Force the cap through an existing Phi-valid break path. · <code>spirvEmitterProgram.cpp:168-178</code></summary><blockquote> > > `src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpp:168-178` > **🩺 Stability & Availability** | **🟠 Major** | **🏗️ Heavy lift** > > **Force the cap through an existing Phi-valid break path.** > > When an `If` arm contains `Break`, CFG lowering branches to the arm’s body, then emits a separate unconditional branch from that body to the loop merge. The watchdog guards conditional branches only when they target the merge directly. If the merge starts with `OpPhi`, `BlockStartsWithPhi` also suppresses the latch’s synthetic exit. A loop with only nested break exits can therefore increment its counter and keep taking non-break paths without testing the limit. Route the cap through an existing break path so the merge retains a valid Phi predecessor. > > <!-- cr-comment:v1:efcbba3b5f67c8148b2283f8 --> > > </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**: `6c4376a0-ed01-4cdb-b925-d610bba5cc76` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 05eac940afad6c7c9794ac554ae0fdc82a5df41d and fb0aec0bad972993dd20921955855a0f1b2d712a. </details> <details> <summary>📒 Files selected for processing (4)</summary> * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.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 --> <!-- coderabbit-review-publication v1 publication=faac1c79-00fc-48e9-9c23-4b32fb008df5 attempt=6d2d8036-e8e2-4473-998d-2c967ed542e6 batch=1/1 -->
Author
Owner

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

Re-validated the rebased branch (fb0aec0b, onto cdb64bf): clean x86_64 macOS no-Qt Release build, shader_cfg passes. The rebase resolutions read right — guard semantics preserved with main's ConstantU64/ConstantU32 helpers, and the phi-exit skip is the safer choice (no synthetic value to supply). Nothing further from me; good to go from the validation side.

**@⁠overlordxrz-source** on GitHub · 2026-10-06 00:32 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/986#issuecomment-6006550416) Re-validated the rebased branch (`fb0aec0b`, onto `cdb64bf`): clean x86_64 macOS no-Qt Release build, `shader_cfg` passes. The rebase resolutions read right — guard semantics preserved with main's `ConstantU64`/`ConstantU32` helpers, and the phi-exit skip is the safer choice (no synthetic value to supply). Nothing further from me; good to go from the validation side.
Author
Owner

@⁠Nmzik on GitHub · 2026-10-08 13:40 UTC · original

This is a hack!

**@⁠Nmzik** on GitHub · 2026-10-08 13:40 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/986#issuecomment-6061163378) This is a hack!
Author
Owner

@⁠wuboo on GitHub · 2026-10-08 16:15 UTC · original

Agreed that a default-on cap changes shader semantics and can hide translation bugs — that is exactly what happened here: the world-scene "hang" turned out to be the split-Wave64 *Zero bug (#985), and rohit267's Nanite numbers show Wukong still hitting the cap. I'll drop this PR as is. Two smaller pieces seem worth keeping, if you agree:

  1. A bounds check on the BDA page-table index (an out-of-range page is treated as a missing page instead of indexing past the table). That is a correctness fix, not a cap.
  2. An opt-in diagnostic loop watchdog, off by default (no counters emitted unless the env var is set), that logs the shader hash whenever a loop is forced out, so it finds translation bugs instead of hiding them. No new CFG edges (includes rohit267's phi fix), no cap on atomic CAS retries.

Longer term, a host-side timeout on command buffers with a clear device-lost report is probably the right protection. Happy to open these separately if that direction works for you.

**@⁠wuboo** on GitHub · 2026-10-08 16:15 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/986#issuecomment-6064160629) Agreed that a default-on cap changes shader semantics and can hide translation bugs — that is exactly what happened here: the world-scene "hang" turned out to be the split-Wave64 `*Zero` bug (#985), and rohit267's Nanite numbers show Wukong still hitting the cap. I'll drop this PR as is. Two smaller pieces seem worth keeping, if you agree: 1. A bounds check on the BDA page-table index (an out-of-range page is treated as a missing page instead of indexing past the table). That is a correctness fix, not a cap. 2. An opt-in diagnostic loop watchdog, off by default (no counters emitted unless the env var is set), that logs the shader hash whenever a loop is forced out, so it finds translation bugs instead of hiding them. No new CFG edges (includes rohit267's phi fix), no cap on atomic CAS retries. Longer term, a host-side timeout on command buffers with a clear device-lost report is probably the right protection. Happy to open these separately if that direction works for you.

Pull request closed

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