shader: accept tessellation loops, indexed HS ring reads, integer spacing #1482

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

@⁠NeySlim on GitHub · 2026-10-13 19:05 UTC · original
NeySlim:fix/tess-gow → main · +599 −77 · 3 files · 4 commits · closed without merging

Tested in God of War Ragnarok (PPSA08332, 05.005).

The game draws its displaced terrain and snow with tessellation (patch draws, triangle domain, 3 control points). Without --tessellation these draws are skipped, so the ground is missing in the opening cutscene, on the sled track and in the Freya fight: flat white snow, holes where the background shows through, a white band across the frozen river.

With --tessellation on current main the game exits before gameplay:

Not implemented (inst.branch_target <= inst.pc) in src/graphics/shader/recompiler/Tessellation.cpp:133

Main now handles forward branches, wide DS writes, the patch range and PatchInput (4a2961cdf, 0957f088a) and caches the ring layouts (c71589124). What the game still hits:

  • Loops: one LS/HS loops before its ring stores, and main's scan only takes forward branches. The reflection now runs a forward data flow over the blocks, loops included (a register is unknown when incoming values differ), and checks the ring accesses on the final states.
  • Reads of another control point: the HS reads (cp + 1) % 3 with an address that is not affine in cp. A "multiple of c" address kind (exact product: power of two, or 24-bit multiply by at most 256) is accepted for a read when c is a multiple of the LS stride. v_add3_u32 and v_mov_b32 are tracked.
  • The HS reads back its own outputs after s_barrier (buffer_load on the HS ring). This is lowered to a read of the output variable at address / stride. Vulkan allows reading gl_out[i] of any invocation after barrier(), writes stay at gl_InvocationID.
  • Wide DS reads (B64/B96/B128, READ2_B64).
  • Integer partitioning maps to SpacingEqual, fractional even to SpacingFractionalEven. pow2 is still refused (no equivalent).
  • HS stores outside their control point record are refused instead of being taken for control point outputs, and ring attributes at fixed offsets stay static in the translated stages.

Testing (Linux, Radeon 8060S, RADV 26.2.5):

  • Host tests in --tessellation-only: TessellationBranchedRing (indexed read, output read back, integer partitioning) and CheckTessellationLoop (a loop before the LS and HS ring stores, plus a case that must be refused). Both fail on main.
  • GPU check TessellationPatchDraw in CheckRasterization: a real patch draw through RenderExecutor::DrawAuto with guest LS/HS/DS/PS. The HS of control point 0 reads control point 1's output and passes it as patch data, the DS exports it, the target must be (3, 3, 3, 1) everywhere. Fails on main.
  • ctest: same failures as main. GPU suite, one case per process: 823 cases, same 53 failures as main.
  • In game with --tessellation, on current main with my other open PRs (the game needs several of them to reach gameplay): new-game runs of about 13 minutes (opening cutscene, sled, Freya fight, end of the chapter), no exit, no device lost. The terrain and snow are drawn, the white band and the holes are gone. Screenshots below.

Tessellation is still off by default, this only makes --tessellation work for this game. Cost with it on, same build: -1.1 fps in the opening cutscene (22.9 -> 21.9, -4.7%), -0.8 fps on the sled (-3.6%), Freya fight within noise. Startup to gameplay is also slower (about 42k patch draws in the menus and intro). Most of the cutscene cost is probably the indirect patch draws, which stay on the CPU path of #1288.

Not tested on Windows. Recompiler and SPIR-V emitter code only, no platform specific code.

Before (left, without --tessellation) and after (right, with this change):

sled
cave

AI use

I used Claude Code to write the change and the test and to run the measurements above. I reviewed the code and the results before opening the PR.

**@⁠NeySlim** on GitHub · 2026-10-13 19:05 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1482) `NeySlim:fix/tess-gow` → `main` · +599 −77 · 3 files · 4 commits · closed without merging Tested in God of War Ragnarok (PPSA08332, 05.005). The game draws its displaced terrain and snow with tessellation (patch draws, triangle domain, 3 control points). Without `--tessellation` these draws are skipped, so the ground is missing in the opening cutscene, on the sled track and in the Freya fight: flat white snow, holes where the background shows through, a white band across the frozen river. With `--tessellation` on current main the game exits before gameplay: ``` Not implemented (inst.branch_target <= inst.pc) in src/graphics/shader/recompiler/Tessellation.cpp:133 ``` Main now handles forward branches, wide DS writes, the patch range and `PatchInput` (4a2961cdf, 0957f088a) and caches the ring layouts (c71589124). What the game still hits: - Loops: one LS/HS loops before its ring stores, and main's scan only takes forward branches. The reflection now runs a forward data flow over the blocks, loops included (a register is unknown when incoming values differ), and checks the ring accesses on the final states. - Reads of another control point: the HS reads `(cp + 1) % 3` with an address that is not affine in `cp`. A "multiple of c" address kind (exact product: power of two, or 24-bit multiply by at most 256) is accepted for a read when c is a multiple of the LS stride. `v_add3_u32` and `v_mov_b32` are tracked. - The HS reads back its own outputs after `s_barrier` (`buffer_load` on the HS ring). This is lowered to a read of the output variable at `address / stride`. Vulkan allows reading `gl_out[i]` of any invocation after `barrier()`, writes stay at `gl_InvocationID`. - Wide DS reads (B64/B96/B128, READ2_B64). - Integer partitioning maps to `SpacingEqual`, fractional even to `SpacingFractionalEven`. pow2 is still refused (no equivalent). - HS stores outside their control point record are refused instead of being taken for control point outputs, and ring attributes at fixed offsets stay static in the translated stages. Testing (Linux, Radeon 8060S, RADV 26.2.5): - Host tests in `--tessellation-only`: `TessellationBranchedRing` (indexed read, output read back, integer partitioning) and `CheckTessellationLoop` (a loop before the LS and HS ring stores, plus a case that must be refused). Both fail on main. - GPU check `TessellationPatchDraw` in `CheckRasterization`: a real patch draw through `RenderExecutor::DrawAuto` with guest LS/HS/DS/PS. The HS of control point 0 reads control point 1's output and passes it as patch data, the DS exports it, the target must be (3, 3, 3, 1) everywhere. Fails on main. - ctest: same failures as main. GPU suite, one case per process: 823 cases, same 53 failures as main. - In game with `--tessellation`, on current main with my other open PRs (the game needs several of them to reach gameplay): new-game runs of about 13 minutes (opening cutscene, sled, Freya fight, end of the chapter), no exit, no device lost. The terrain and snow are drawn, the white band and the holes are gone. Screenshots below. Tessellation is still off by default, this only makes `--tessellation` work for this game. Cost with it on, same build: -1.1 fps in the opening cutscene (22.9 -> 21.9, -4.7%), -0.8 fps on the sled (-3.6%), Freya fight within noise. Startup to gameplay is also slower (about 42k patch draws in the menus and intro). Most of the cutscene cost is probably the indirect patch draws, which stay on the CPU path of #1288. Not tested on Windows. Recompiler and SPIR-V emitter code only, no platform specific code. Before (left, without `--tessellation`) and after (right, with this change): ![sled](https://github.com/NeySlim/KytyPS5/raw/media/gow-tess-sled.jpg) ![cave](https://github.com/NeySlim/KytyPS5/raw/media/gow-tess-cave.jpg) ## AI use I used Claude Code to write the change and the test and to run the measurements above. I reviewed the code and the results before opening the PR.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:57:45 +00:00
github-bot closed this pull request 2026-11-26 09:57:45 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-13 19:09 UTC · original · edited 2026-10-20 19:41 UTC

Review in Change Stack →

Note

Reviews paused

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

  • Last reviewed commit: fecf7e689df03d5bcae4ae7e2371290f575bc496
  • Latest commit, not reviewed: 0f7e8bff9e

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

Tessellation address analysis now supports additional arithmetic patterns and iterates dataflow across branches and loops before validating ring accesses. Tessellation buffer classification distinguishes control-stage and evaluation-stage accesses. SPIR-V emission handles derivable record offsets, control-point output reads, and equal or fractional partitioning modes. Tests cover branched and loop-carried addresses, out-of-record stores, static offsets, and a tessellated patch draw.

Suggested reviewers: nmzik

Priority: ➖ Normal

Change: Feature

Merge Risk: 🟡 Moderate · up to fecf7

Tessellated shaders whose ring addresses add a negative constant can read or write the wrong per-control-point attribute when the record stride is not a power of two. This would cause incorrect tessellated geometry. Tessellation is disabled by default, which limits exposure, but the offset folding should be fixed before merge.

Pre-merge checks: Passed 4 · Inconclusive 1

Failed Failed checks: 1 inconclusive

Check name Status Explanation Resolution
Docstring Coverage Inconclusive Docstring coverage is 16.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 12 functions across 6 files. (1 skipped: … Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Title check Passed The title clearly summarizes the main changes: tessellation loop support, indexed HS ring reads, and integer spacing.
Description check Passed The description directly explains the tessellation changes, affected game behavior, tests, performance results, and known limitations.
Full details: Docstring Coverage

Explanation

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

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

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

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-13 19:09 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1482#issuecomment-6153123486) · edited 2026-10-20 19:41 UTC <!-- coderabbit-ai-generated:v1 --> <!-- This is an auto-generated comment: summarize by coderabbit.ai --> <!-- review_stack_entry_start --> <a href="https://app.coderabbit.ai/change-stack/KytyPS5/KytyPS5/pull/1482?scope=ghh_OusAJGA4HG8ljoOV0wJvVx8NmnZIjc2DdjmxOu0xZWA&amp;cs_source=review_comment"><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui-dark.svg?v=3"><source media="(prefers-color-scheme: light)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg?v=3"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg?v=3" alt="Review in Change Stack →" height="32"></picture></a> <!-- review_stack_entry_end --> <!-- This is an auto-generated comment: review paused by coderabbit.ai --> > [!NOTE] > ## Reviews paused > > It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the `reviews.auto_review.auto_pause_after_reviewed_commits` setting. > > - Last reviewed commit: fecf7e689df03d5bcae4ae7e2371290f575bc496 > - Latest commit, not reviewed: 0f7e8bff9e0c280b7052147f11a55efbef188380 > > 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><strong>📝 Walkthrough</strong></summary> <dl> <dd> Tessellation address analysis now supports additional arithmetic patterns and iterates dataflow across branches and loops before validating ring accesses. Tessellation buffer classification distinguishes control-stage and evaluation-stage accesses. SPIR-V emission handles derivable record offsets, control-point output reads, and equal or fractional partitioning modes. Tests cover branched and loop-carried addresses, out-of-record stores, static offsets, and a tessellated patch draw. **Suggested reviewers:** `nmzik` </dd> </dl> </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ➖ Normal <!-- change_assessment_commit:"fecf7e689df03d5bcae4ae7e2371290f575bc496" --> **Change:** Feature <!-- change_assessment_end --> <details> <summary><strong>Merge Risk:</strong> <strong>🟡 Moderate</strong> · up to <code>fecf7</code></summary> <dl> <dd> <!-- final_review_risk_start --> <!-- final_review_risk_label **Merge Risk:** **🟡 Moderate** · up to `fecf7` --> <!-- final_review_risk_coverage:{"sourceCommitId":"fecf7e689df03d5bcae4ae7e2371290f575bc496","coveredCommitId":"fecf7e689df03d5bcae4ae7e2371290f575bc496","kind":"reviewed"} --> Tessellated shaders whose ring addresses add a negative constant can read or write the wrong per-control-point attribute when the record stride is not a power of two. This would cause incorrect tessellated geometry. Tessellation is disabled by default, which limits exposure, but the offset folding should be fixed before merge. <!-- final_review_risk_end --> </dd> </dl> </details> <!-- pre_merge_checks_walkthrough_start --> <details> <summary><strong>Pre-merge checks: <sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-passed-14-v2.svg" width="14" height="14" align="middle" alt="Passed" title="Passed"></picture></sup> 4 · <sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-inconclusive-14-v2.svg" width="14" height="14" align="middle" alt="Inconclusive" title="Inconclusive"></picture></sup> 1</strong></summary> <dl> <dd> <strong><sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-failed-14-v2.svg" width="14" height="14" align="middle" alt="Failed" title="Failed"></picture></sup> Failed checks: 1 inconclusive</strong> | Check name | Status | Explanation | Resolution | | :---------------- | :--------------------------------------------------------------------------------------------------------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------- | | Docstring Coverage | ![Inconclusive](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-inconclusive.svg) | Docstring coverage is 16.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 12 functions across 6 files. (1 skipped: … | Write docstrings for the functions missing them to satisfy the coverage threshold. | <details> <summary><strong><sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-passed-14-v2.svg" width="14" height="14" align="middle" alt="Passed" title="Passed"></picture></sup> Passed checks: 4 passed</strong></summary> <dl> <dd> | Check name | Status | Explanation | | :------------------------ | :--------------------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------------------------------------------------- | | Linked Issues check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | Check skipped because no linked issues were found for this pull request. | | Out of Scope Changes check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | Check skipped because no linked issues were found for this pull request. | | Title check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The title clearly summarizes the main changes: tessellation loop support, indexed HS ring reads, and integer spacing. | | Description check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The description directly explains the tessellation changes, affected game behavior, tests, performance results, and known limitations. | </dd> </dl> </details> <details> <summary><strong>Full details: Docstring Coverage</strong></summary> <dl> <dd> **Explanation** Docstring coverage is 16.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 12 functions across 6 files. (1 skipped: 1 too large.) **Resolution** Write docstrings for the functions missing them to satisfy the coverage threshold. </dd> </dl> </details> </dd> </dl> </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">Autofix</strong> · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts <!-- autopilot:end --> <!-- tips_start --> Thanks for using [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=KytyPS5/KytyPS5&utm_content=1482)! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. <details> <summary><strong>❤️ Share</strong></summary> <dl> <dd> - [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai) - [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai) - [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai) - [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code) </dd> </dl> </details> <sub>Comment `@coderabbitai help` to get the list of available commands.</sub> <!-- tips_end -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-13 19:09 UTC · original · edited 2026-10-13 19:21 UTC
On src/graphics/shader/recompiler/Tessellation.cpp line 273 (outdated):

@@ -48,108 +72,205 @@ uint32_t ReflectTessellationStride(const Decoder::Program& program, bool local,
 		if (value.kind == Kind::PackedControlPoint && operand.sdwa_sel == 0u) return constant(0u);
 		return operand.sdwa_sel == 6u ? value : Address {};
 	};
-	const auto affine = [](uint64_t coefficient, uint64_t offset) {
+	const auto affine = [](Kind kind, uint64_t coefficient, uint64_t offset) {
 		return coefficient <= UINT32_MAX && offset <= UINT32_MAX
-		           ? Address {Kind::Affine, static_cast<uint32_t>(coefficient),
+		           ? Address {kind, static_cast<uint32_t>(coefficient),
 		                      static_cast<uint32_t>(offset)}
 		           : Address {};
 	};
 	const auto add = [&](Address lhs, Address rhs) {
-		return lhs.kind == Kind::Affine && rhs.kind == Kind::Affine
-		           ? affine(uint64_t {lhs.coefficient} + rhs.coefficient,
-		                    uint64_t {lhs.constant} + rhs.constant)
-		           : Address {};
+		if (lhs.kind == Kind::Affine && rhs.kind == Kind::Affine)
+			return affine(Kind::Affine, uint64_t {lhs.coefficient} + rhs.coefficient,
+			              uint64_t {lhs.constant} + rhs.constant);
+		// Ordinal multiples of a Scaled coefficient stay multiples of it.
+		const auto scaled = [](Address value) {
+			return value.kind == Kind::Affine || value.kind == Kind::Scaled;
+		};
+		if (!scaled(lhs) || !scaled(rhs)) return Address {};
+		const auto coefficient = std::gcd(lhs.coefficient, rhs.coefficient);
+		return affine(Kind::Scaled, coefficient, uint64_t {lhs.constant} + rhs.constant);
 	};
-	const auto multiply = [&](Address lhs, Address rhs) {
-		if ((lhs.kind == Kind::Affine && lhs.coefficient == 0u && lhs.constant == 0u) ||
-		    (rhs.kind == Kind::Affine && rhs.coefficient == 0u && rhs.constant == 0u))
-			return constant(0u);
-		if (lhs.kind != Kind::Affine || rhs.kind != Kind::Affine) return Address {};
-		if (rhs.coefficient != 0u) std::swap(lhs, rhs);
-		return rhs.coefficient == 0u ? affine(uint64_t {lhs.coefficient} * rhs.constant,
-		                                      uint64_t {lhs.constant} * rhs.constant)
-		                             : Address {};
+	const auto multiply = [&](Address lhs, Address rhs, bool u24) {
+		const auto zero = [](Address value) {
+			return value.kind == Kind::Affine && value.coefficient == 0u && value.constant == 0u;
+		};
+		if (zero(lhs) || zero(rhs)) return constant(0u);
+		if (!is_constant(rhs)) std::swap(lhs, rhs);
+		if (!is_constant(rhs)) return Address {};
+		if (lhs.kind == Kind::Affine)
+			return affine(Kind::Affine, uint64_t {lhs.coefficient} * rhs.constant,
+			              uint64_t {lhs.constant} * rhs.constant);
+		if (lhs.kind == Kind::PackedControlPoint) return Address {};
+		// A product by a power of two keeps that factor when it wraps; a 24-bit operand times at
+		// most 256 cannot wrap.
+		const bool power = std::has_single_bit(rhs.constant);
+		if (lhs.kind == Kind::Scaled && power && std::has_single_bit(lhs.coefficient))
+			return affine(Kind::Scaled, uint64_t {lhs.coefficient} * rhs.constant,
+			              uint64_t {lhs.constant} * rhs.constant);
+		return power || (u24 && rhs.constant <= 0x100u) ? Address {Kind::Scaled, rhs.constant, 0u}
+		                                                : Address {};
 	};
 	const auto low24 = [&](Address value) {
-		if (value.kind == Kind::Affine && value.coefficient == 0u)
-			return constant(value.constant & 0xffffffu);
+		if (is_constant(value)) return constant(value.constant & 0xffffffu);
 		return value.kind == Kind::Affine &&
 		               uint64_t {value.coefficient} * (control_points - 1u) + value.constant <=
 		                   0xffffffu
 		           ? value
 		           : Address {};
 	};
 	uint32_t stride = 0;
-	for (const auto& inst: program.instructions) {
-		// Stage exits preserve the active path's definitions. An internal join
-		// would require merging register definitions.
-		EXIT_NOT_IMPLEMENTED(IsDirectBranch(inst.opcode) &&
-		                     inst.branch_target != program.instructions.back().pc);
-		const bool local_store =
-		    inst.opcode == Opcode::DS_WRITE_B32 || inst.opcode == Opcode::DS_WRITE2_B32;
+	// Constant-address HS stores: {address, first byte, end byte}.
+	std::vector<std::array<uint32_t, 3>> fixed_stores;
+	// Applies one instruction; ring addresses are only checked once the states are final.
+	const auto step = [&](const Instruction& inst, Registers& registers, bool check) {
+		const bool local_store  = IsLocalWrite(inst.opcode);
 		const bool buffer_store = inst.opcode == Opcode::BUFFER_STORE_DWORD ||
 		                          inst.opcode == Opcode::BUFFER_STORE_DWORDX2 ||
 		                          inst.opcode == Opcode::BUFFER_STORE_DWORDX3 ||
 		                          inst.opcode == Opcode::BUFFER_STORE_DWORDX4;
 		const bool control_store =
 		    !local && buffer_store && inst.src2.kind == OperandKind::Sgpr && inst.src2.reg == 2u;
-		const bool control_read =
-		    !local && (inst.opcode == Opcode::DS_READ_B32 || inst.opcode == Opcode::DS_READ2_B32);
-		if ((local && local_store) || control_store || control_read) {
-			const auto address = read(inst.src0);
-			if (address.kind != Kind::Affine) {
+		const bool control_read = !local && IsLocalRead(inst.opcode);
+		if (check && ((local && local_store) || control_store || control_read)) {
+			const auto address = read(registers, inst.src0);
+			// A read may index another control point; only its record offset must be fixed.
+			const bool indexed_read = control_read && address.kind == Kind::Scaled &&
+			                          address.coefficient % input_stride == 0u;
+			if (address.kind != Kind::Affine && !indexed_read) {
 				EXIT("%s tessellation address is not affine at pc 0x%08x\n", local ? "LS" : "HS",
 				     inst.pc);
 			}
-			if (address.coefficient != 0u) {
+			if (control_store && address.coefficient == 0u) {
+				const auto first = uint64_t {address.constant} + inst.offset;
+				EXIT_NOT_IMPLEMENTED(first + 4u * inst.data_dwords > UINT32_MAX);
+				fixed_stores.push_back({address.constant, static_cast<uint32_t>(first),
+				                        static_cast<uint32_t>(first + 4u * inst.data_dwords)});
+			}
+			if (address.kind == Kind::Affine && address.coefficient != 0u) {
 				const auto expected = control_read ? input_stride : stride;
 				EXIT_NOT_IMPLEMENTED((address.coefficient & 3u) != 0u ||
 				                     (expected != 0u && expected != address.coefficient));
 				if (!control_read) stride = address.coefficient;
 			}
 		}
 		// Store vdata is a source, despite occupying the decoder's dst field.
-		if (local_store || buffer_store || inst.dst.kind != OperandKind::Vgpr) continue;
-		const auto lhs   = read(inst.src0);
-		const auto rhs   = read(inst.src1);
-		const auto third = read(inst.src2);
+		if (local_store || buffer_store || inst.dst.kind != OperandKind::Vgpr) return;
+		const auto lhs   = read(registers, inst.src0);
+		const auto rhs   = read(registers, inst.src1);
+		const auto third = read(registers, inst.src2);
 		Address    value;
 		switch (inst.opcode) {
+			case Opcode::V_MOV_B32: value = lhs; break;
 			case Opcode::V_BFE_U32:
-				if (lhs.kind == Kind::PackedControlPoint && rhs.kind == Kind::Affine &&
-				    rhs.coefficient == 0u && third.kind == Kind::Affine &&
-				    third.coefficient == 0u) {
+				if (lhs.kind == Kind::PackedControlPoint && is_constant(rhs) &&
+				    is_constant(third)) {
 					if (rhs.constant == 8u && third.constant == 5u) value = {Kind::Affine, 1u, 0u};
 					if (rhs.constant == 0u && third.constant == 8u) value = constant(0u);
 				}
 				break;
-			case Opcode::V_MUL_U32_U24: value = multiply(low24(lhs), low24(rhs)); break;
-			case Opcode::V_MAD_U32_U24: value = add(multiply(low24(lhs), low24(rhs)), third); break;
+			case Opcode::V_MUL_U32_U24: value = multiply(low24(lhs), low24(rhs), true); break;
+			case Opcode::V_MAD_U32_U24:
+				value = add(multiply(low24(lhs), low24(rhs), true), third);
+				break;
+			case Opcode::V_ADD_NC_U32: value = add(lhs, rhs); break;
+			case Opcode::V_ADD3_U32: value = add(add(lhs, rhs), third); break;
 			case Opcode::V_LSHL_ADD_U32:
-				if (rhs.kind == Kind::Affine && rhs.coefficient == 0u && rhs.constant < 32u)
-					value = add(multiply(lhs, constant(1u << rhs.constant)), third);
+				if (is_constant(rhs) && rhs.constant < 32u)
+					value = add(multiply(lhs, constant(1u << rhs.constant), false), third);
 				break;
 			case Opcode::V_LSHLREV_B32:
-				if (lhs.kind == Kind::Affine && lhs.coefficient == 0u && lhs.constant < 32u)
-					value = multiply(rhs, constant(1u << lhs.constant));
+				if (is_constant(lhs) && lhs.constant < 32u)
+					value = multiply(rhs, constant(1u << lhs.constant), false);
 				break;
 			case Opcode::V_SUB_NC_U32:
 				if (lhs.kind == Kind::Affine && rhs.kind == Kind::Affine &&
 				    lhs.coefficient >= rhs.coefficient && lhs.constant >= rhs.constant)
-					value = affine(lhs.coefficient - rhs.coefficient, lhs.constant - rhs.constant);
+					value = affine(Kind::Affine, lhs.coefficient - rhs.coefficient,
+					               lhs.constant - rhs.constant);
 				break;
 			default: break;
 		}
 		if (inst.dst.sdwa_sel != 6u || inst.dst.op_sel || inst.dst.omod || inst.dst.clamp ||
 		    inst.dst.dpp)
 			value = {};
 		for (uint32_t index = 0;
-		     index < std::max(inst.data_dwords, 1u) && inst.dst.reg + index < registers.size(); index++) {
+		     index < std::max(inst.data_dwords, 1u) && inst.dst.reg + index < registers.size();
+		     index++) {
 			registers[inst.dst.reg + index] = {};
 		}
 		registers.at(inst.dst.reg) = value;
+	};
+
+	// Forward dataflow over the stage's blocks; a register whose incoming values differ is unknown.
+	const auto& insts    = program.instructions;
+	const auto  index_of = [&](uint32_t pc) {
+		const auto it = std::ranges::lower_bound(insts, pc, {}, &Instruction::pc);
+		EXIT_IF(it == insts.end() || it->pc != pc);
+		return static_cast<size_t>(it - insts.begin());
+	};
+	std::vector<bool> leader(insts.size(), false);
+	leader.at(0) = true;
+	for (size_t index = 0; index < insts.size(); index++) {
+		if (!IsDirectBranch(insts[index].opcode)) continue;
+		leader[index_of(insts[index].branch_target)] = true;
+		if (index + 1u < insts.size()) leader[index + 1u] = true;
+	}
+	// Entry states of the reached blocks, by leader index.
+	std::unordered_map<size_t, Registers> entry;
+	entry[0].at(local ? 3u : 1u) =
+	    local ? Address {Kind::Affine, 1u, 0u} : Address {Kind::PackedControlPoint};
+	std::vector<size_t> work {0};
+	const auto          flow = [&](size_t target, const Registers& registers) {
+		const auto [it, inserted] = entry.try_emplace(target, registers);
+		bool changed              = inserted;
+		for (size_t reg = 0; !inserted && reg < registers.size(); reg++) {
+			if (it->second[reg] != registers[reg] && it->second[reg].kind != Kind::Unknown) {
+				it->second[reg] = {};
+				changed         = true;
+			}
+		}
+		if (changed) work.push_back(target);
+	};
+	const auto run = [&](size_t begin, bool check) {
+		auto registers = entry.at(begin);
+		for (size_t index = begin; index < insts.size(); index++) {
+			if (index != begin && leader[index]) {
+				if (!check) flow(index, registers);
+				return;
+			}
+			const auto& inst = insts[index];
+			step(inst, registers, check);
+			if (inst.opcode == Opcode::S_ENDPGM) return;
+			if (IsDirectBranch(inst.opcode)) {
+				if (!check) {
+					flow(index_of(inst.branch_target), registers);
+					if (IsConditionalBranch(inst.opcode) && index + 1u < insts.size())
+						flow(index + 1u, registers);
+				}
+				return;
+			}
+		}
+	};
+	while (!work.empty()) {
+		const auto begin = work.back();
+		work.pop_back();
+		run(begin, false);
+	}
+	for (size_t index = 0; index < insts.size(); index++) {
+		if (entry.contains(index)) run(index, true);
 	}
 	EXIT_NOT_IMPLEMENTED(stride == 0u);
+	if (patch != nullptr) {
+		// As in the lowering, a store address past every control point selects the patch outputs.
+		patch->patch_begin = UINT32_MAX;
+		patch->patch_end   = 0;
+		for (const auto& [address, first, end]: fixed_stores) {
+			if (address < stride * control_points) continue;
+			patch->patch_begin = std::min(patch->patch_begin, first);
+			patch->patch_end   = std::max(patch->patch_end, end);
+		}
+		if (patch->patch_end == 0u) patch->patch_begin = 0;
+	}

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

🔎 Supported by static analysis

🏁 Script executed:

set -o pipefail
printf '%s\n' '--- relevant symbols ---'
rg -n -F -- 'fixed_stores' src/graphics/shader/recompiler/Tessellation.cpp
rg -n -F -e 'patch_begin' -e 'patch_end' -e 'PatchInput' -e 'DefineTessellationInterfaces' src/graphics/shader/recompiler src
printf '%s\n' '--- Tessellation.cpp 100-290 ---'
nl -ba src/graphics/shader/recompiler/Tessellation.cpp | sed -n '100,290p'
printf '%s\n' '--- outlines ---'
ast-grep outline src/graphics/shader/recompiler/Tessellation.cpp --view expanded

Repository: KytyPS5/KytyPS5

Length of output: 16408


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- lowering and classification ---'
nl -ba src/graphics/shader/recompiler/Tessellation.cpp | sed -n '330,435p'
printf '%s\n' '--- tessellation interface emission ---'
nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterTessellation.cpp | sed -n '1,125p'
printf '%s\n' '--- relevant IR/types and shader metadata ---'
nl -ba src/graphics/shader/shader.h | sed -n '105,135p'
nl -ba src/graphics/shader/shader.cpp | sed -n '620,655p'

Repository: KytyPS5/KytyPS5

Length of output: 16349


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- address model and remaining lowering ---'
nl -ba src/graphics/shader/recompiler/Tessellation.cpp | sed -n '1,105p'
nl -ba src/graphics/shader/recompiler/Tessellation.cpp | sed -n '422,475p'
printf '%s\n' '--- tessellation tests and patch references ---'
rg -n -F -e 'TessellationBranchedRing' -e 'TessellationPatchDraw' -e 'patch_begin' -e 'PatchOutput' -e 'PatchInput' tests src | head -200
printf '%s\n' '--- PR diff for the target file ---'
git diff --no-ext-diff --unified=20 df5b9b92be7dfd463b47756b707d6d356a9f0550 412547341c1b085869ad4a2f20a3535f764aa43f -- src/graphics/shader/recompiler/Tessellation.cpp

Repository: KytyPS5/KytyPS5

Length of output: 35455


Handle affine patch stores before computing the patch range.

A non-constant affine control-store address can target the patch region, but fixed_stores records only constant addresses. If that store is the only patch producer, patch_begin and patch_end remain zero. A TES patch read can then reach DefineTessellationInterfaces, which rejects its address as outside [0, 0). Classify these stores as patch outputs, or reject the unsupported form during reflection instead of treating it as a control-point store.

✅ Addressed in commit e55a14c

**@⁠coderabbitai[bot]** on GitHub · 2026-10-13 19:09 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1482#discussion_r4262893990) · edited 2026-10-13 19:21 UTC On `src/graphics/shader/recompiler/Tessellation.cpp` line 273 (outdated): ```diff @@ -48,108 +72,205 @@ uint32_t ReflectTessellationStride(const Decoder::Program& program, bool local, if (value.kind == Kind::PackedControlPoint && operand.sdwa_sel == 0u) return constant(0u); return operand.sdwa_sel == 6u ? value : Address {}; }; - const auto affine = [](uint64_t coefficient, uint64_t offset) { + const auto affine = [](Kind kind, uint64_t coefficient, uint64_t offset) { return coefficient <= UINT32_MAX && offset <= UINT32_MAX - ? Address {Kind::Affine, static_cast<uint32_t>(coefficient), + ? Address {kind, static_cast<uint32_t>(coefficient), static_cast<uint32_t>(offset)} : Address {}; }; const auto add = [&](Address lhs, Address rhs) { - return lhs.kind == Kind::Affine && rhs.kind == Kind::Affine - ? affine(uint64_t {lhs.coefficient} + rhs.coefficient, - uint64_t {lhs.constant} + rhs.constant) - : Address {}; + if (lhs.kind == Kind::Affine && rhs.kind == Kind::Affine) + return affine(Kind::Affine, uint64_t {lhs.coefficient} + rhs.coefficient, + uint64_t {lhs.constant} + rhs.constant); + // Ordinal multiples of a Scaled coefficient stay multiples of it. + const auto scaled = [](Address value) { + return value.kind == Kind::Affine || value.kind == Kind::Scaled; + }; + if (!scaled(lhs) || !scaled(rhs)) return Address {}; + const auto coefficient = std::gcd(lhs.coefficient, rhs.coefficient); + return affine(Kind::Scaled, coefficient, uint64_t {lhs.constant} + rhs.constant); }; - const auto multiply = [&](Address lhs, Address rhs) { - if ((lhs.kind == Kind::Affine && lhs.coefficient == 0u && lhs.constant == 0u) || - (rhs.kind == Kind::Affine && rhs.coefficient == 0u && rhs.constant == 0u)) - return constant(0u); - if (lhs.kind != Kind::Affine || rhs.kind != Kind::Affine) return Address {}; - if (rhs.coefficient != 0u) std::swap(lhs, rhs); - return rhs.coefficient == 0u ? affine(uint64_t {lhs.coefficient} * rhs.constant, - uint64_t {lhs.constant} * rhs.constant) - : Address {}; + const auto multiply = [&](Address lhs, Address rhs, bool u24) { + const auto zero = [](Address value) { + return value.kind == Kind::Affine && value.coefficient == 0u && value.constant == 0u; + }; + if (zero(lhs) || zero(rhs)) return constant(0u); + if (!is_constant(rhs)) std::swap(lhs, rhs); + if (!is_constant(rhs)) return Address {}; + if (lhs.kind == Kind::Affine) + return affine(Kind::Affine, uint64_t {lhs.coefficient} * rhs.constant, + uint64_t {lhs.constant} * rhs.constant); + if (lhs.kind == Kind::PackedControlPoint) return Address {}; + // A product by a power of two keeps that factor when it wraps; a 24-bit operand times at + // most 256 cannot wrap. + const bool power = std::has_single_bit(rhs.constant); + if (lhs.kind == Kind::Scaled && power && std::has_single_bit(lhs.coefficient)) + return affine(Kind::Scaled, uint64_t {lhs.coefficient} * rhs.constant, + uint64_t {lhs.constant} * rhs.constant); + return power || (u24 && rhs.constant <= 0x100u) ? Address {Kind::Scaled, rhs.constant, 0u} + : Address {}; }; const auto low24 = [&](Address value) { - if (value.kind == Kind::Affine && value.coefficient == 0u) - return constant(value.constant & 0xffffffu); + if (is_constant(value)) return constant(value.constant & 0xffffffu); return value.kind == Kind::Affine && uint64_t {value.coefficient} * (control_points - 1u) + value.constant <= 0xffffffu ? value : Address {}; }; uint32_t stride = 0; - for (const auto& inst: program.instructions) { - // Stage exits preserve the active path's definitions. An internal join - // would require merging register definitions. - EXIT_NOT_IMPLEMENTED(IsDirectBranch(inst.opcode) && - inst.branch_target != program.instructions.back().pc); - const bool local_store = - inst.opcode == Opcode::DS_WRITE_B32 || inst.opcode == Opcode::DS_WRITE2_B32; + // Constant-address HS stores: {address, first byte, end byte}. + std::vector<std::array<uint32_t, 3>> fixed_stores; + // Applies one instruction; ring addresses are only checked once the states are final. + const auto step = [&](const Instruction& inst, Registers& registers, bool check) { + const bool local_store = IsLocalWrite(inst.opcode); const bool buffer_store = inst.opcode == Opcode::BUFFER_STORE_DWORD || inst.opcode == Opcode::BUFFER_STORE_DWORDX2 || inst.opcode == Opcode::BUFFER_STORE_DWORDX3 || inst.opcode == Opcode::BUFFER_STORE_DWORDX4; const bool control_store = !local && buffer_store && inst.src2.kind == OperandKind::Sgpr && inst.src2.reg == 2u; - const bool control_read = - !local && (inst.opcode == Opcode::DS_READ_B32 || inst.opcode == Opcode::DS_READ2_B32); - if ((local && local_store) || control_store || control_read) { - const auto address = read(inst.src0); - if (address.kind != Kind::Affine) { + const bool control_read = !local && IsLocalRead(inst.opcode); + if (check && ((local && local_store) || control_store || control_read)) { + const auto address = read(registers, inst.src0); + // A read may index another control point; only its record offset must be fixed. + const bool indexed_read = control_read && address.kind == Kind::Scaled && + address.coefficient % input_stride == 0u; + if (address.kind != Kind::Affine && !indexed_read) { EXIT("%s tessellation address is not affine at pc 0x%08x\n", local ? "LS" : "HS", inst.pc); } - if (address.coefficient != 0u) { + if (control_store && address.coefficient == 0u) { + const auto first = uint64_t {address.constant} + inst.offset; + EXIT_NOT_IMPLEMENTED(first + 4u * inst.data_dwords > UINT32_MAX); + fixed_stores.push_back({address.constant, static_cast<uint32_t>(first), + static_cast<uint32_t>(first + 4u * inst.data_dwords)}); + } + if (address.kind == Kind::Affine && address.coefficient != 0u) { const auto expected = control_read ? input_stride : stride; EXIT_NOT_IMPLEMENTED((address.coefficient & 3u) != 0u || (expected != 0u && expected != address.coefficient)); if (!control_read) stride = address.coefficient; } } // Store vdata is a source, despite occupying the decoder's dst field. - if (local_store || buffer_store || inst.dst.kind != OperandKind::Vgpr) continue; - const auto lhs = read(inst.src0); - const auto rhs = read(inst.src1); - const auto third = read(inst.src2); + if (local_store || buffer_store || inst.dst.kind != OperandKind::Vgpr) return; + const auto lhs = read(registers, inst.src0); + const auto rhs = read(registers, inst.src1); + const auto third = read(registers, inst.src2); Address value; switch (inst.opcode) { + case Opcode::V_MOV_B32: value = lhs; break; case Opcode::V_BFE_U32: - if (lhs.kind == Kind::PackedControlPoint && rhs.kind == Kind::Affine && - rhs.coefficient == 0u && third.kind == Kind::Affine && - third.coefficient == 0u) { + if (lhs.kind == Kind::PackedControlPoint && is_constant(rhs) && + is_constant(third)) { if (rhs.constant == 8u && third.constant == 5u) value = {Kind::Affine, 1u, 0u}; if (rhs.constant == 0u && third.constant == 8u) value = constant(0u); } break; - case Opcode::V_MUL_U32_U24: value = multiply(low24(lhs), low24(rhs)); break; - case Opcode::V_MAD_U32_U24: value = add(multiply(low24(lhs), low24(rhs)), third); break; + case Opcode::V_MUL_U32_U24: value = multiply(low24(lhs), low24(rhs), true); break; + case Opcode::V_MAD_U32_U24: + value = add(multiply(low24(lhs), low24(rhs), true), third); + break; + case Opcode::V_ADD_NC_U32: value = add(lhs, rhs); break; + case Opcode::V_ADD3_U32: value = add(add(lhs, rhs), third); break; case Opcode::V_LSHL_ADD_U32: - if (rhs.kind == Kind::Affine && rhs.coefficient == 0u && rhs.constant < 32u) - value = add(multiply(lhs, constant(1u << rhs.constant)), third); + if (is_constant(rhs) && rhs.constant < 32u) + value = add(multiply(lhs, constant(1u << rhs.constant), false), third); break; case Opcode::V_LSHLREV_B32: - if (lhs.kind == Kind::Affine && lhs.coefficient == 0u && lhs.constant < 32u) - value = multiply(rhs, constant(1u << lhs.constant)); + if (is_constant(lhs) && lhs.constant < 32u) + value = multiply(rhs, constant(1u << lhs.constant), false); break; case Opcode::V_SUB_NC_U32: if (lhs.kind == Kind::Affine && rhs.kind == Kind::Affine && lhs.coefficient >= rhs.coefficient && lhs.constant >= rhs.constant) - value = affine(lhs.coefficient - rhs.coefficient, lhs.constant - rhs.constant); + value = affine(Kind::Affine, lhs.coefficient - rhs.coefficient, + lhs.constant - rhs.constant); break; default: break; } if (inst.dst.sdwa_sel != 6u || inst.dst.op_sel || inst.dst.omod || inst.dst.clamp || inst.dst.dpp) value = {}; for (uint32_t index = 0; - index < std::max(inst.data_dwords, 1u) && inst.dst.reg + index < registers.size(); index++) { + index < std::max(inst.data_dwords, 1u) && inst.dst.reg + index < registers.size(); + index++) { registers[inst.dst.reg + index] = {}; } registers.at(inst.dst.reg) = value; + }; + + // Forward dataflow over the stage's blocks; a register whose incoming values differ is unknown. + const auto& insts = program.instructions; + const auto index_of = [&](uint32_t pc) { + const auto it = std::ranges::lower_bound(insts, pc, {}, &Instruction::pc); + EXIT_IF(it == insts.end() || it->pc != pc); + return static_cast<size_t>(it - insts.begin()); + }; + std::vector<bool> leader(insts.size(), false); + leader.at(0) = true; + for (size_t index = 0; index < insts.size(); index++) { + if (!IsDirectBranch(insts[index].opcode)) continue; + leader[index_of(insts[index].branch_target)] = true; + if (index + 1u < insts.size()) leader[index + 1u] = true; + } + // Entry states of the reached blocks, by leader index. + std::unordered_map<size_t, Registers> entry; + entry[0].at(local ? 3u : 1u) = + local ? Address {Kind::Affine, 1u, 0u} : Address {Kind::PackedControlPoint}; + std::vector<size_t> work {0}; + const auto flow = [&](size_t target, const Registers& registers) { + const auto [it, inserted] = entry.try_emplace(target, registers); + bool changed = inserted; + for (size_t reg = 0; !inserted && reg < registers.size(); reg++) { + if (it->second[reg] != registers[reg] && it->second[reg].kind != Kind::Unknown) { + it->second[reg] = {}; + changed = true; + } + } + if (changed) work.push_back(target); + }; + const auto run = [&](size_t begin, bool check) { + auto registers = entry.at(begin); + for (size_t index = begin; index < insts.size(); index++) { + if (index != begin && leader[index]) { + if (!check) flow(index, registers); + return; + } + const auto& inst = insts[index]; + step(inst, registers, check); + if (inst.opcode == Opcode::S_ENDPGM) return; + if (IsDirectBranch(inst.opcode)) { + if (!check) { + flow(index_of(inst.branch_target), registers); + if (IsConditionalBranch(inst.opcode) && index + 1u < insts.size()) + flow(index + 1u, registers); + } + return; + } + } + }; + while (!work.empty()) { + const auto begin = work.back(); + work.pop_back(); + run(begin, false); + } + for (size_t index = 0; index < insts.size(); index++) { + if (entry.contains(index)) run(index, true); } EXIT_NOT_IMPLEMENTED(stride == 0u); + if (patch != nullptr) { + // As in the lowering, a store address past every control point selects the patch outputs. + patch->patch_begin = UINT32_MAX; + patch->patch_end = 0; + for (const auto& [address, first, end]: fixed_stores) { + if (address < stride * control_points) continue; + patch->patch_begin = std::min(patch->patch_begin, first); + patch->patch_end = std::max(patch->patch_end, end); + } + if (patch->patch_end == 0u) patch->patch_begin = 0; + } ``` **🩺 Stability & Availability** | **🟠 Major** | **🏗️ Heavy lift** <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash set -o pipefail printf '%s\n' '--- relevant symbols ---' rg -n -F -- 'fixed_stores' src/graphics/shader/recompiler/Tessellation.cpp rg -n -F -e 'patch_begin' -e 'patch_end' -e 'PatchInput' -e 'DefineTessellationInterfaces' src/graphics/shader/recompiler src printf '%s\n' '--- Tessellation.cpp 100-290 ---' nl -ba src/graphics/shader/recompiler/Tessellation.cpp | sed -n '100,290p' printf '%s\n' '--- outlines ---' ast-grep outline src/graphics/shader/recompiler/Tessellation.cpp --view expanded ``` Repository: KytyPS5/KytyPS5 Length of output: 16408 --- 🏁 Script executed: ```bash set -o pipefail printf '%s\n' '--- lowering and classification ---' nl -ba src/graphics/shader/recompiler/Tessellation.cpp | sed -n '330,435p' printf '%s\n' '--- tessellation interface emission ---' nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterTessellation.cpp | sed -n '1,125p' printf '%s\n' '--- relevant IR/types and shader metadata ---' nl -ba src/graphics/shader/shader.h | sed -n '105,135p' nl -ba src/graphics/shader/shader.cpp | sed -n '620,655p' ``` Repository: KytyPS5/KytyPS5 Length of output: 16349 --- 🏁 Script executed: ```bash set -o pipefail printf '%s\n' '--- address model and remaining lowering ---' nl -ba src/graphics/shader/recompiler/Tessellation.cpp | sed -n '1,105p' nl -ba src/graphics/shader/recompiler/Tessellation.cpp | sed -n '422,475p' printf '%s\n' '--- tessellation tests and patch references ---' rg -n -F -e 'TessellationBranchedRing' -e 'TessellationPatchDraw' -e 'patch_begin' -e 'PatchOutput' -e 'PatchInput' tests src | head -200 printf '%s\n' '--- PR diff for the target file ---' git diff --no-ext-diff --unified=20 df5b9b92be7dfd463b47756b707d6d356a9f0550 412547341c1b085869ad4a2f20a3535f764aa43f -- src/graphics/shader/recompiler/Tessellation.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 35455 --- </details> **Handle affine patch stores before computing the patch range.** A non-constant affine control-store address can target the patch region, but `fixed_stores` records only constant addresses. If that store is the only patch producer, `patch_begin` and `patch_end` remain zero. A TES patch read can then reach `DefineTessellationInterfaces`, which rejects its address as outside `[0, 0)`. Classify these stores as patch outputs, or reject the unsupported form during reflection instead of treating it as a control-point store. <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:e3cf5fc1700f8d7e35d9641e --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Addressed in commit e55a14c
Author
Owner

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

Actionable comments posted: 1

🧹 Nitpick comments: 1
src/graphics/shader/recompiler/Tessellation.cpp: 1

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

Check address.kind == Kind::Affine before you record a fixed store.

The check at Line 143 tests only address.coefficient == 0u. A control store can reach this point with any non-affine kind, because the EXIT at Line 139 only fires for stores and that path is skipped for indexed_read. Stores alone are safe today, since every non-Affine store exits first. The Scaled kind can still carry coefficient == 0 from std::gcd(0, 0). Add the explicit kind check so that a future relaxation of the exit cannot record a store whose address is not constant.

♻️ Proposed change
-			if (control_store && address.coefficient == 0u) {
+			if (control_store && address.kind == Kind::Affine && address.coefficient == 0u) {

ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 3adb9910-3bd9-4225-9bb2-d35708d0c664
📥 Commits

Reviewing files that changed from the base of the PR and between df5b9b92be and 412547341c1b085869ad4a2f20a3535f764aa43f.

📒 Files selected for processing: 7
  • src/graphics/shader/recompiler/Tessellation.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterTessellation.cpp
  • src/graphics/shader/recompiler/ir/ShaderIR.h
  • src/graphics/shader/shader.cpp
  • src/graphics/shader/shader.h
  • tests/ShaderRecompilerComputeTests.cpp

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

**@⁠coderabbitai[bot]** on GitHub · 2026-10-13 19:09 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1482#pullrequestreview-5508650745) · **reviewed** **Actionable comments posted: 1** <details> <summary>🧹 Nitpick comments: 1</summary><blockquote> <details> <summary>src/graphics/shader/recompiler/Tessellation.cpp: 1</summary><blockquote> `143-148`: **📐 Maintainability & Code Quality** | **🔵 Trivial** | **💤 Low value** **Check `address.kind == Kind::Affine` before you record a fixed store.** The check at Line 143 tests only `address.coefficient == 0u`. A control store can reach this point with any non-affine kind, because the `EXIT` at Line 139 only fires for stores and that path is skipped for `indexed_read`. Stores alone are safe today, since every non-Affine store exits first. The `Scaled` kind can still carry `coefficient == 0` from `std::gcd(0, 0)`. Add the explicit kind check so that a future relaxation of the exit cannot record a store whose address is not constant. <details> <summary>♻️ Proposed change</summary> ```diff - if (control_store && address.coefficient == 0u) { + if (control_store && address.kind == Kind::Affine && address.coefficient == 0u) { ``` </details> <!-- cr-comment:v1:0230f09692b3ec9a24a297a9 --> </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**: `3adb9910-3bd9-4225-9bb2-d35708d0c664` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between df5b9b92be7dfd463b47756b707d6d356a9f0550 and 412547341c1b085869ad4a2f20a3535f764aa43f. </details> <details> <summary>📒 Files selected for processing: 7</summary> * `src/graphics/shader/recompiler/Tessellation.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterTessellation.cpp` * `src/graphics/shader/recompiler/ir/ShaderIR.h` * `src/graphics/shader/shader.cpp` * `src/graphics/shader/shader.h` * `tests/ShaderRecompilerComputeTests.cpp` </details> **Included review availability:** This review used your included allowance. Your plan provides up to 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=c825a1cf-7b7c-4ba1-8354-d3769e5dd3a7 attempt=7dd8743d-7c8b-48eb-bd86-0c096f5cd449 batch=1/1 -->
Author
Owner

@⁠NeySlim on GitHub · 2026-10-13 19:19 UTC · original
On src/graphics/shader/recompiler/Tessellation.cpp line 273 (outdated):

@@ -48,108 +72,205 @@ uint32_t ReflectTessellationStride(const Decoder::Program& program, bool local,
 		if (value.kind == Kind::PackedControlPoint && operand.sdwa_sel == 0u) return constant(0u);
 		return operand.sdwa_sel == 6u ? value : Address {};
 	};
-	const auto affine = [](uint64_t coefficient, uint64_t offset) {
+	const auto affine = [](Kind kind, uint64_t coefficient, uint64_t offset) {
 		return coefficient <= UINT32_MAX && offset <= UINT32_MAX
-		           ? Address {Kind::Affine, static_cast<uint32_t>(coefficient),
+		           ? Address {kind, static_cast<uint32_t>(coefficient),
 		                      static_cast<uint32_t>(offset)}
 		           : Address {};
 	};
 	const auto add = [&](Address lhs, Address rhs) {
-		return lhs.kind == Kind::Affine && rhs.kind == Kind::Affine
-		           ? affine(uint64_t {lhs.coefficient} + rhs.coefficient,
-		                    uint64_t {lhs.constant} + rhs.constant)
-		           : Address {};
+		if (lhs.kind == Kind::Affine && rhs.kind == Kind::Affine)
+			return affine(Kind::Affine, uint64_t {lhs.coefficient} + rhs.coefficient,
+			              uint64_t {lhs.constant} + rhs.constant);
+		// Ordinal multiples of a Scaled coefficient stay multiples of it.
+		const auto scaled = [](Address value) {
+			return value.kind == Kind::Affine || value.kind == Kind::Scaled;
+		};
+		if (!scaled(lhs) || !scaled(rhs)) return Address {};
+		const auto coefficient = std::gcd(lhs.coefficient, rhs.coefficient);
+		return affine(Kind::Scaled, coefficient, uint64_t {lhs.constant} + rhs.constant);
 	};
-	const auto multiply = [&](Address lhs, Address rhs) {
-		if ((lhs.kind == Kind::Affine && lhs.coefficient == 0u && lhs.constant == 0u) ||
-		    (rhs.kind == Kind::Affine && rhs.coefficient == 0u && rhs.constant == 0u))
-			return constant(0u);
-		if (lhs.kind != Kind::Affine || rhs.kind != Kind::Affine) return Address {};
-		if (rhs.coefficient != 0u) std::swap(lhs, rhs);
-		return rhs.coefficient == 0u ? affine(uint64_t {lhs.coefficient} * rhs.constant,
-		                                      uint64_t {lhs.constant} * rhs.constant)
-		                             : Address {};
+	const auto multiply = [&](Address lhs, Address rhs, bool u24) {
+		const auto zero = [](Address value) {
+			return value.kind == Kind::Affine && value.coefficient == 0u && value.constant == 0u;
+		};
+		if (zero(lhs) || zero(rhs)) return constant(0u);
+		if (!is_constant(rhs)) std::swap(lhs, rhs);
+		if (!is_constant(rhs)) return Address {};
+		if (lhs.kind == Kind::Affine)
+			return affine(Kind::Affine, uint64_t {lhs.coefficient} * rhs.constant,
+			              uint64_t {lhs.constant} * rhs.constant);
+		if (lhs.kind == Kind::PackedControlPoint) return Address {};
+		// A product by a power of two keeps that factor when it wraps; a 24-bit operand times at
+		// most 256 cannot wrap.
+		const bool power = std::has_single_bit(rhs.constant);
+		if (lhs.kind == Kind::Scaled && power && std::has_single_bit(lhs.coefficient))
+			return affine(Kind::Scaled, uint64_t {lhs.coefficient} * rhs.constant,
+			              uint64_t {lhs.constant} * rhs.constant);
+		return power || (u24 && rhs.constant <= 0x100u) ? Address {Kind::Scaled, rhs.constant, 0u}
+		                                                : Address {};
 	};
 	const auto low24 = [&](Address value) {
-		if (value.kind == Kind::Affine && value.coefficient == 0u)
-			return constant(value.constant & 0xffffffu);
+		if (is_constant(value)) return constant(value.constant & 0xffffffu);
 		return value.kind == Kind::Affine &&
 		               uint64_t {value.coefficient} * (control_points - 1u) + value.constant <=
 		                   0xffffffu
 		           ? value
 		           : Address {};
 	};
 	uint32_t stride = 0;
-	for (const auto& inst: program.instructions) {
-		// Stage exits preserve the active path's definitions. An internal join
-		// would require merging register definitions.
-		EXIT_NOT_IMPLEMENTED(IsDirectBranch(inst.opcode) &&
-		                     inst.branch_target != program.instructions.back().pc);
-		const bool local_store =
-		    inst.opcode == Opcode::DS_WRITE_B32 || inst.opcode == Opcode::DS_WRITE2_B32;
+	// Constant-address HS stores: {address, first byte, end byte}.
+	std::vector<std::array<uint32_t, 3>> fixed_stores;
+	// Applies one instruction; ring addresses are only checked once the states are final.
+	const auto step = [&](const Instruction& inst, Registers& registers, bool check) {
+		const bool local_store  = IsLocalWrite(inst.opcode);
 		const bool buffer_store = inst.opcode == Opcode::BUFFER_STORE_DWORD ||
 		                          inst.opcode == Opcode::BUFFER_STORE_DWORDX2 ||
 		                          inst.opcode == Opcode::BUFFER_STORE_DWORDX3 ||
 		                          inst.opcode == Opcode::BUFFER_STORE_DWORDX4;
 		const bool control_store =
 		    !local && buffer_store && inst.src2.kind == OperandKind::Sgpr && inst.src2.reg == 2u;
-		const bool control_read =
-		    !local && (inst.opcode == Opcode::DS_READ_B32 || inst.opcode == Opcode::DS_READ2_B32);
-		if ((local && local_store) || control_store || control_read) {
-			const auto address = read(inst.src0);
-			if (address.kind != Kind::Affine) {
+		const bool control_read = !local && IsLocalRead(inst.opcode);
+		if (check && ((local && local_store) || control_store || control_read)) {
+			const auto address = read(registers, inst.src0);
+			// A read may index another control point; only its record offset must be fixed.
+			const bool indexed_read = control_read && address.kind == Kind::Scaled &&
+			                          address.coefficient % input_stride == 0u;
+			if (address.kind != Kind::Affine && !indexed_read) {
 				EXIT("%s tessellation address is not affine at pc 0x%08x\n", local ? "LS" : "HS",
 				     inst.pc);
 			}
-			if (address.coefficient != 0u) {
+			if (control_store && address.coefficient == 0u) {
+				const auto first = uint64_t {address.constant} + inst.offset;
+				EXIT_NOT_IMPLEMENTED(first + 4u * inst.data_dwords > UINT32_MAX);
+				fixed_stores.push_back({address.constant, static_cast<uint32_t>(first),
+				                        static_cast<uint32_t>(first + 4u * inst.data_dwords)});
+			}
+			if (address.kind == Kind::Affine && address.coefficient != 0u) {
 				const auto expected = control_read ? input_stride : stride;
 				EXIT_NOT_IMPLEMENTED((address.coefficient & 3u) != 0u ||
 				                     (expected != 0u && expected != address.coefficient));
 				if (!control_read) stride = address.coefficient;
 			}
 		}
 		// Store vdata is a source, despite occupying the decoder's dst field.
-		if (local_store || buffer_store || inst.dst.kind != OperandKind::Vgpr) continue;
-		const auto lhs   = read(inst.src0);
-		const auto rhs   = read(inst.src1);
-		const auto third = read(inst.src2);
+		if (local_store || buffer_store || inst.dst.kind != OperandKind::Vgpr) return;
+		const auto lhs   = read(registers, inst.src0);
+		const auto rhs   = read(registers, inst.src1);
+		const auto third = read(registers, inst.src2);
 		Address    value;
 		switch (inst.opcode) {
+			case Opcode::V_MOV_B32: value = lhs; break;
 			case Opcode::V_BFE_U32:
-				if (lhs.kind == Kind::PackedControlPoint && rhs.kind == Kind::Affine &&
-				    rhs.coefficient == 0u && third.kind == Kind::Affine &&
-				    third.coefficient == 0u) {
+				if (lhs.kind == Kind::PackedControlPoint && is_constant(rhs) &&
+				    is_constant(third)) {
 					if (rhs.constant == 8u && third.constant == 5u) value = {Kind::Affine, 1u, 0u};
 					if (rhs.constant == 0u && third.constant == 8u) value = constant(0u);
 				}
 				break;
-			case Opcode::V_MUL_U32_U24: value = multiply(low24(lhs), low24(rhs)); break;
-			case Opcode::V_MAD_U32_U24: value = add(multiply(low24(lhs), low24(rhs)), third); break;
+			case Opcode::V_MUL_U32_U24: value = multiply(low24(lhs), low24(rhs), true); break;
+			case Opcode::V_MAD_U32_U24:
+				value = add(multiply(low24(lhs), low24(rhs), true), third);
+				break;
+			case Opcode::V_ADD_NC_U32: value = add(lhs, rhs); break;
+			case Opcode::V_ADD3_U32: value = add(add(lhs, rhs), third); break;
 			case Opcode::V_LSHL_ADD_U32:
-				if (rhs.kind == Kind::Affine && rhs.coefficient == 0u && rhs.constant < 32u)
-					value = add(multiply(lhs, constant(1u << rhs.constant)), third);
+				if (is_constant(rhs) && rhs.constant < 32u)
+					value = add(multiply(lhs, constant(1u << rhs.constant), false), third);
 				break;
 			case Opcode::V_LSHLREV_B32:
-				if (lhs.kind == Kind::Affine && lhs.coefficient == 0u && lhs.constant < 32u)
-					value = multiply(rhs, constant(1u << lhs.constant));
+				if (is_constant(lhs) && lhs.constant < 32u)
+					value = multiply(rhs, constant(1u << lhs.constant), false);
 				break;
 			case Opcode::V_SUB_NC_U32:
 				if (lhs.kind == Kind::Affine && rhs.kind == Kind::Affine &&
 				    lhs.coefficient >= rhs.coefficient && lhs.constant >= rhs.constant)
-					value = affine(lhs.coefficient - rhs.coefficient, lhs.constant - rhs.constant);
+					value = affine(Kind::Affine, lhs.coefficient - rhs.coefficient,
+					               lhs.constant - rhs.constant);
 				break;
 			default: break;
 		}
 		if (inst.dst.sdwa_sel != 6u || inst.dst.op_sel || inst.dst.omod || inst.dst.clamp ||
 		    inst.dst.dpp)
 			value = {};
 		for (uint32_t index = 0;
-		     index < std::max(inst.data_dwords, 1u) && inst.dst.reg + index < registers.size(); index++) {
+		     index < std::max(inst.data_dwords, 1u) && inst.dst.reg + index < registers.size();
+		     index++) {
 			registers[inst.dst.reg + index] = {};
 		}
 		registers.at(inst.dst.reg) = value;
+	};
+
+	// Forward dataflow over the stage's blocks; a register whose incoming values differ is unknown.
+	const auto& insts    = program.instructions;
+	const auto  index_of = [&](uint32_t pc) {
+		const auto it = std::ranges::lower_bound(insts, pc, {}, &Instruction::pc);
+		EXIT_IF(it == insts.end() || it->pc != pc);
+		return static_cast<size_t>(it - insts.begin());
+	};
+	std::vector<bool> leader(insts.size(), false);
+	leader.at(0) = true;
+	for (size_t index = 0; index < insts.size(); index++) {
+		if (!IsDirectBranch(insts[index].opcode)) continue;
+		leader[index_of(insts[index].branch_target)] = true;
+		if (index + 1u < insts.size()) leader[index + 1u] = true;
+	}
+	// Entry states of the reached blocks, by leader index.
+	std::unordered_map<size_t, Registers> entry;
+	entry[0].at(local ? 3u : 1u) =
+	    local ? Address {Kind::Affine, 1u, 0u} : Address {Kind::PackedControlPoint};
+	std::vector<size_t> work {0};
+	const auto          flow = [&](size_t target, const Registers& registers) {
+		const auto [it, inserted] = entry.try_emplace(target, registers);
+		bool changed              = inserted;
+		for (size_t reg = 0; !inserted && reg < registers.size(); reg++) {
+			if (it->second[reg] != registers[reg] && it->second[reg].kind != Kind::Unknown) {
+				it->second[reg] = {};
+				changed         = true;
+			}
+		}
+		if (changed) work.push_back(target);
+	};
+	const auto run = [&](size_t begin, bool check) {
+		auto registers = entry.at(begin);
+		for (size_t index = begin; index < insts.size(); index++) {
+			if (index != begin && leader[index]) {
+				if (!check) flow(index, registers);
+				return;
+			}
+			const auto& inst = insts[index];
+			step(inst, registers, check);
+			if (inst.opcode == Opcode::S_ENDPGM) return;
+			if (IsDirectBranch(inst.opcode)) {
+				if (!check) {
+					flow(index_of(inst.branch_target), registers);
+					if (IsConditionalBranch(inst.opcode) && index + 1u < insts.size())
+						flow(index + 1u, registers);
+				}
+				return;
+			}
+		}
+	};
+	while (!work.empty()) {
+		const auto begin = work.back();
+		work.pop_back();
+		run(begin, false);
+	}
+	for (size_t index = 0; index < insts.size(); index++) {
+		if (entry.contains(index)) run(index, true);
 	}
 	EXIT_NOT_IMPLEMENTED(stride == 0u);
+	if (patch != nullptr) {
+		// As in the lowering, a store address past every control point selects the patch outputs.
+		patch->patch_begin = UINT32_MAX;
+		patch->patch_end   = 0;
+		for (const auto& [address, first, end]: fixed_stores) {
+			if (address < stride * control_points) continue;
+			patch->patch_begin = std::min(patch->patch_begin, first);
+			patch->patch_end   = std::max(patch->patch_end, end);
+		}
+		if (patch->patch_end == 0u) patch->patch_begin = 0;
+	}

Yes, an affine store with a constant at or past the stride lands in the next record, and the last control point's lands in the patch region. The lowering would write it to the invocation's own output, so reflection now exits on any per-control-point store that leaves its record (e55a14c6, host test added). The 12 LS/HS/DS sets from the game all pass the check.

Also switched the fixed store check to is_constant() in the same commit. A Scaled store can't reach it since non-affine stores exit just above, but it reads clearer.

**@⁠NeySlim** on GitHub · 2026-10-13 19:19 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1482#discussion_r4262993923) On `src/graphics/shader/recompiler/Tessellation.cpp` line 273 (outdated): ```diff @@ -48,108 +72,205 @@ uint32_t ReflectTessellationStride(const Decoder::Program& program, bool local, if (value.kind == Kind::PackedControlPoint && operand.sdwa_sel == 0u) return constant(0u); return operand.sdwa_sel == 6u ? value : Address {}; }; - const auto affine = [](uint64_t coefficient, uint64_t offset) { + const auto affine = [](Kind kind, uint64_t coefficient, uint64_t offset) { return coefficient <= UINT32_MAX && offset <= UINT32_MAX - ? Address {Kind::Affine, static_cast<uint32_t>(coefficient), + ? Address {kind, static_cast<uint32_t>(coefficient), static_cast<uint32_t>(offset)} : Address {}; }; const auto add = [&](Address lhs, Address rhs) { - return lhs.kind == Kind::Affine && rhs.kind == Kind::Affine - ? affine(uint64_t {lhs.coefficient} + rhs.coefficient, - uint64_t {lhs.constant} + rhs.constant) - : Address {}; + if (lhs.kind == Kind::Affine && rhs.kind == Kind::Affine) + return affine(Kind::Affine, uint64_t {lhs.coefficient} + rhs.coefficient, + uint64_t {lhs.constant} + rhs.constant); + // Ordinal multiples of a Scaled coefficient stay multiples of it. + const auto scaled = [](Address value) { + return value.kind == Kind::Affine || value.kind == Kind::Scaled; + }; + if (!scaled(lhs) || !scaled(rhs)) return Address {}; + const auto coefficient = std::gcd(lhs.coefficient, rhs.coefficient); + return affine(Kind::Scaled, coefficient, uint64_t {lhs.constant} + rhs.constant); }; - const auto multiply = [&](Address lhs, Address rhs) { - if ((lhs.kind == Kind::Affine && lhs.coefficient == 0u && lhs.constant == 0u) || - (rhs.kind == Kind::Affine && rhs.coefficient == 0u && rhs.constant == 0u)) - return constant(0u); - if (lhs.kind != Kind::Affine || rhs.kind != Kind::Affine) return Address {}; - if (rhs.coefficient != 0u) std::swap(lhs, rhs); - return rhs.coefficient == 0u ? affine(uint64_t {lhs.coefficient} * rhs.constant, - uint64_t {lhs.constant} * rhs.constant) - : Address {}; + const auto multiply = [&](Address lhs, Address rhs, bool u24) { + const auto zero = [](Address value) { + return value.kind == Kind::Affine && value.coefficient == 0u && value.constant == 0u; + }; + if (zero(lhs) || zero(rhs)) return constant(0u); + if (!is_constant(rhs)) std::swap(lhs, rhs); + if (!is_constant(rhs)) return Address {}; + if (lhs.kind == Kind::Affine) + return affine(Kind::Affine, uint64_t {lhs.coefficient} * rhs.constant, + uint64_t {lhs.constant} * rhs.constant); + if (lhs.kind == Kind::PackedControlPoint) return Address {}; + // A product by a power of two keeps that factor when it wraps; a 24-bit operand times at + // most 256 cannot wrap. + const bool power = std::has_single_bit(rhs.constant); + if (lhs.kind == Kind::Scaled && power && std::has_single_bit(lhs.coefficient)) + return affine(Kind::Scaled, uint64_t {lhs.coefficient} * rhs.constant, + uint64_t {lhs.constant} * rhs.constant); + return power || (u24 && rhs.constant <= 0x100u) ? Address {Kind::Scaled, rhs.constant, 0u} + : Address {}; }; const auto low24 = [&](Address value) { - if (value.kind == Kind::Affine && value.coefficient == 0u) - return constant(value.constant & 0xffffffu); + if (is_constant(value)) return constant(value.constant & 0xffffffu); return value.kind == Kind::Affine && uint64_t {value.coefficient} * (control_points - 1u) + value.constant <= 0xffffffu ? value : Address {}; }; uint32_t stride = 0; - for (const auto& inst: program.instructions) { - // Stage exits preserve the active path's definitions. An internal join - // would require merging register definitions. - EXIT_NOT_IMPLEMENTED(IsDirectBranch(inst.opcode) && - inst.branch_target != program.instructions.back().pc); - const bool local_store = - inst.opcode == Opcode::DS_WRITE_B32 || inst.opcode == Opcode::DS_WRITE2_B32; + // Constant-address HS stores: {address, first byte, end byte}. + std::vector<std::array<uint32_t, 3>> fixed_stores; + // Applies one instruction; ring addresses are only checked once the states are final. + const auto step = [&](const Instruction& inst, Registers& registers, bool check) { + const bool local_store = IsLocalWrite(inst.opcode); const bool buffer_store = inst.opcode == Opcode::BUFFER_STORE_DWORD || inst.opcode == Opcode::BUFFER_STORE_DWORDX2 || inst.opcode == Opcode::BUFFER_STORE_DWORDX3 || inst.opcode == Opcode::BUFFER_STORE_DWORDX4; const bool control_store = !local && buffer_store && inst.src2.kind == OperandKind::Sgpr && inst.src2.reg == 2u; - const bool control_read = - !local && (inst.opcode == Opcode::DS_READ_B32 || inst.opcode == Opcode::DS_READ2_B32); - if ((local && local_store) || control_store || control_read) { - const auto address = read(inst.src0); - if (address.kind != Kind::Affine) { + const bool control_read = !local && IsLocalRead(inst.opcode); + if (check && ((local && local_store) || control_store || control_read)) { + const auto address = read(registers, inst.src0); + // A read may index another control point; only its record offset must be fixed. + const bool indexed_read = control_read && address.kind == Kind::Scaled && + address.coefficient % input_stride == 0u; + if (address.kind != Kind::Affine && !indexed_read) { EXIT("%s tessellation address is not affine at pc 0x%08x\n", local ? "LS" : "HS", inst.pc); } - if (address.coefficient != 0u) { + if (control_store && address.coefficient == 0u) { + const auto first = uint64_t {address.constant} + inst.offset; + EXIT_NOT_IMPLEMENTED(first + 4u * inst.data_dwords > UINT32_MAX); + fixed_stores.push_back({address.constant, static_cast<uint32_t>(first), + static_cast<uint32_t>(first + 4u * inst.data_dwords)}); + } + if (address.kind == Kind::Affine && address.coefficient != 0u) { const auto expected = control_read ? input_stride : stride; EXIT_NOT_IMPLEMENTED((address.coefficient & 3u) != 0u || (expected != 0u && expected != address.coefficient)); if (!control_read) stride = address.coefficient; } } // Store vdata is a source, despite occupying the decoder's dst field. - if (local_store || buffer_store || inst.dst.kind != OperandKind::Vgpr) continue; - const auto lhs = read(inst.src0); - const auto rhs = read(inst.src1); - const auto third = read(inst.src2); + if (local_store || buffer_store || inst.dst.kind != OperandKind::Vgpr) return; + const auto lhs = read(registers, inst.src0); + const auto rhs = read(registers, inst.src1); + const auto third = read(registers, inst.src2); Address value; switch (inst.opcode) { + case Opcode::V_MOV_B32: value = lhs; break; case Opcode::V_BFE_U32: - if (lhs.kind == Kind::PackedControlPoint && rhs.kind == Kind::Affine && - rhs.coefficient == 0u && third.kind == Kind::Affine && - third.coefficient == 0u) { + if (lhs.kind == Kind::PackedControlPoint && is_constant(rhs) && + is_constant(third)) { if (rhs.constant == 8u && third.constant == 5u) value = {Kind::Affine, 1u, 0u}; if (rhs.constant == 0u && third.constant == 8u) value = constant(0u); } break; - case Opcode::V_MUL_U32_U24: value = multiply(low24(lhs), low24(rhs)); break; - case Opcode::V_MAD_U32_U24: value = add(multiply(low24(lhs), low24(rhs)), third); break; + case Opcode::V_MUL_U32_U24: value = multiply(low24(lhs), low24(rhs), true); break; + case Opcode::V_MAD_U32_U24: + value = add(multiply(low24(lhs), low24(rhs), true), third); + break; + case Opcode::V_ADD_NC_U32: value = add(lhs, rhs); break; + case Opcode::V_ADD3_U32: value = add(add(lhs, rhs), third); break; case Opcode::V_LSHL_ADD_U32: - if (rhs.kind == Kind::Affine && rhs.coefficient == 0u && rhs.constant < 32u) - value = add(multiply(lhs, constant(1u << rhs.constant)), third); + if (is_constant(rhs) && rhs.constant < 32u) + value = add(multiply(lhs, constant(1u << rhs.constant), false), third); break; case Opcode::V_LSHLREV_B32: - if (lhs.kind == Kind::Affine && lhs.coefficient == 0u && lhs.constant < 32u) - value = multiply(rhs, constant(1u << lhs.constant)); + if (is_constant(lhs) && lhs.constant < 32u) + value = multiply(rhs, constant(1u << lhs.constant), false); break; case Opcode::V_SUB_NC_U32: if (lhs.kind == Kind::Affine && rhs.kind == Kind::Affine && lhs.coefficient >= rhs.coefficient && lhs.constant >= rhs.constant) - value = affine(lhs.coefficient - rhs.coefficient, lhs.constant - rhs.constant); + value = affine(Kind::Affine, lhs.coefficient - rhs.coefficient, + lhs.constant - rhs.constant); break; default: break; } if (inst.dst.sdwa_sel != 6u || inst.dst.op_sel || inst.dst.omod || inst.dst.clamp || inst.dst.dpp) value = {}; for (uint32_t index = 0; - index < std::max(inst.data_dwords, 1u) && inst.dst.reg + index < registers.size(); index++) { + index < std::max(inst.data_dwords, 1u) && inst.dst.reg + index < registers.size(); + index++) { registers[inst.dst.reg + index] = {}; } registers.at(inst.dst.reg) = value; + }; + + // Forward dataflow over the stage's blocks; a register whose incoming values differ is unknown. + const auto& insts = program.instructions; + const auto index_of = [&](uint32_t pc) { + const auto it = std::ranges::lower_bound(insts, pc, {}, &Instruction::pc); + EXIT_IF(it == insts.end() || it->pc != pc); + return static_cast<size_t>(it - insts.begin()); + }; + std::vector<bool> leader(insts.size(), false); + leader.at(0) = true; + for (size_t index = 0; index < insts.size(); index++) { + if (!IsDirectBranch(insts[index].opcode)) continue; + leader[index_of(insts[index].branch_target)] = true; + if (index + 1u < insts.size()) leader[index + 1u] = true; + } + // Entry states of the reached blocks, by leader index. + std::unordered_map<size_t, Registers> entry; + entry[0].at(local ? 3u : 1u) = + local ? Address {Kind::Affine, 1u, 0u} : Address {Kind::PackedControlPoint}; + std::vector<size_t> work {0}; + const auto flow = [&](size_t target, const Registers& registers) { + const auto [it, inserted] = entry.try_emplace(target, registers); + bool changed = inserted; + for (size_t reg = 0; !inserted && reg < registers.size(); reg++) { + if (it->second[reg] != registers[reg] && it->second[reg].kind != Kind::Unknown) { + it->second[reg] = {}; + changed = true; + } + } + if (changed) work.push_back(target); + }; + const auto run = [&](size_t begin, bool check) { + auto registers = entry.at(begin); + for (size_t index = begin; index < insts.size(); index++) { + if (index != begin && leader[index]) { + if (!check) flow(index, registers); + return; + } + const auto& inst = insts[index]; + step(inst, registers, check); + if (inst.opcode == Opcode::S_ENDPGM) return; + if (IsDirectBranch(inst.opcode)) { + if (!check) { + flow(index_of(inst.branch_target), registers); + if (IsConditionalBranch(inst.opcode) && index + 1u < insts.size()) + flow(index + 1u, registers); + } + return; + } + } + }; + while (!work.empty()) { + const auto begin = work.back(); + work.pop_back(); + run(begin, false); + } + for (size_t index = 0; index < insts.size(); index++) { + if (entry.contains(index)) run(index, true); } EXIT_NOT_IMPLEMENTED(stride == 0u); + if (patch != nullptr) { + // As in the lowering, a store address past every control point selects the patch outputs. + patch->patch_begin = UINT32_MAX; + patch->patch_end = 0; + for (const auto& [address, first, end]: fixed_stores) { + if (address < stride * control_points) continue; + patch->patch_begin = std::min(patch->patch_begin, first); + patch->patch_end = std::max(patch->patch_end, end); + } + if (patch->patch_end == 0u) patch->patch_begin = 0; + } ``` Yes, an affine store with a constant at or past the stride lands in the next record, and the last control point's lands in the patch region. The lowering would write it to the invocation's own output, so reflection now exits on any per-control-point store that leaves its record (e55a14c6, host test added). The 12 LS/HS/DS sets from the game all pass the check. Also switched the fixed store check to is_constant() in the same commit. A Scaled store can't reach it since non-affine stores exit just above, but it reads clearer.
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-13 19:21 UTC · original
On src/graphics/shader/recompiler/Tessellation.cpp line 273 (outdated):

@@ -48,108 +72,205 @@ uint32_t ReflectTessellationStride(const Decoder::Program& program, bool local,
 		if (value.kind == Kind::PackedControlPoint && operand.sdwa_sel == 0u) return constant(0u);
 		return operand.sdwa_sel == 6u ? value : Address {};
 	};
-	const auto affine = [](uint64_t coefficient, uint64_t offset) {
+	const auto affine = [](Kind kind, uint64_t coefficient, uint64_t offset) {
 		return coefficient <= UINT32_MAX && offset <= UINT32_MAX
-		           ? Address {Kind::Affine, static_cast<uint32_t>(coefficient),
+		           ? Address {kind, static_cast<uint32_t>(coefficient),
 		                      static_cast<uint32_t>(offset)}
 		           : Address {};
 	};
 	const auto add = [&](Address lhs, Address rhs) {
-		return lhs.kind == Kind::Affine && rhs.kind == Kind::Affine
-		           ? affine(uint64_t {lhs.coefficient} + rhs.coefficient,
-		                    uint64_t {lhs.constant} + rhs.constant)
-		           : Address {};
+		if (lhs.kind == Kind::Affine && rhs.kind == Kind::Affine)
+			return affine(Kind::Affine, uint64_t {lhs.coefficient} + rhs.coefficient,
+			              uint64_t {lhs.constant} + rhs.constant);
+		// Ordinal multiples of a Scaled coefficient stay multiples of it.
+		const auto scaled = [](Address value) {
+			return value.kind == Kind::Affine || value.kind == Kind::Scaled;
+		};
+		if (!scaled(lhs) || !scaled(rhs)) return Address {};
+		const auto coefficient = std::gcd(lhs.coefficient, rhs.coefficient);
+		return affine(Kind::Scaled, coefficient, uint64_t {lhs.constant} + rhs.constant);
 	};
-	const auto multiply = [&](Address lhs, Address rhs) {
-		if ((lhs.kind == Kind::Affine && lhs.coefficient == 0u && lhs.constant == 0u) ||
-		    (rhs.kind == Kind::Affine && rhs.coefficient == 0u && rhs.constant == 0u))
-			return constant(0u);
-		if (lhs.kind != Kind::Affine || rhs.kind != Kind::Affine) return Address {};
-		if (rhs.coefficient != 0u) std::swap(lhs, rhs);
-		return rhs.coefficient == 0u ? affine(uint64_t {lhs.coefficient} * rhs.constant,
-		                                      uint64_t {lhs.constant} * rhs.constant)
-		                             : Address {};
+	const auto multiply = [&](Address lhs, Address rhs, bool u24) {
+		const auto zero = [](Address value) {
+			return value.kind == Kind::Affine && value.coefficient == 0u && value.constant == 0u;
+		};
+		if (zero(lhs) || zero(rhs)) return constant(0u);
+		if (!is_constant(rhs)) std::swap(lhs, rhs);
+		if (!is_constant(rhs)) return Address {};
+		if (lhs.kind == Kind::Affine)
+			return affine(Kind::Affine, uint64_t {lhs.coefficient} * rhs.constant,
+			              uint64_t {lhs.constant} * rhs.constant);
+		if (lhs.kind == Kind::PackedControlPoint) return Address {};
+		// A product by a power of two keeps that factor when it wraps; a 24-bit operand times at
+		// most 256 cannot wrap.
+		const bool power = std::has_single_bit(rhs.constant);
+		if (lhs.kind == Kind::Scaled && power && std::has_single_bit(lhs.coefficient))
+			return affine(Kind::Scaled, uint64_t {lhs.coefficient} * rhs.constant,
+			              uint64_t {lhs.constant} * rhs.constant);
+		return power || (u24 && rhs.constant <= 0x100u) ? Address {Kind::Scaled, rhs.constant, 0u}
+		                                                : Address {};
 	};
 	const auto low24 = [&](Address value) {
-		if (value.kind == Kind::Affine && value.coefficient == 0u)
-			return constant(value.constant & 0xffffffu);
+		if (is_constant(value)) return constant(value.constant & 0xffffffu);
 		return value.kind == Kind::Affine &&
 		               uint64_t {value.coefficient} * (control_points - 1u) + value.constant <=
 		                   0xffffffu
 		           ? value
 		           : Address {};
 	};
 	uint32_t stride = 0;
-	for (const auto& inst: program.instructions) {
-		// Stage exits preserve the active path's definitions. An internal join
-		// would require merging register definitions.
-		EXIT_NOT_IMPLEMENTED(IsDirectBranch(inst.opcode) &&
-		                     inst.branch_target != program.instructions.back().pc);
-		const bool local_store =
-		    inst.opcode == Opcode::DS_WRITE_B32 || inst.opcode == Opcode::DS_WRITE2_B32;
+	// Constant-address HS stores: {address, first byte, end byte}.
+	std::vector<std::array<uint32_t, 3>> fixed_stores;
+	// Applies one instruction; ring addresses are only checked once the states are final.
+	const auto step = [&](const Instruction& inst, Registers& registers, bool check) {
+		const bool local_store  = IsLocalWrite(inst.opcode);
 		const bool buffer_store = inst.opcode == Opcode::BUFFER_STORE_DWORD ||
 		                          inst.opcode == Opcode::BUFFER_STORE_DWORDX2 ||
 		                          inst.opcode == Opcode::BUFFER_STORE_DWORDX3 ||
 		                          inst.opcode == Opcode::BUFFER_STORE_DWORDX4;
 		const bool control_store =
 		    !local && buffer_store && inst.src2.kind == OperandKind::Sgpr && inst.src2.reg == 2u;
-		const bool control_read =
-		    !local && (inst.opcode == Opcode::DS_READ_B32 || inst.opcode == Opcode::DS_READ2_B32);
-		if ((local && local_store) || control_store || control_read) {
-			const auto address = read(inst.src0);
-			if (address.kind != Kind::Affine) {
+		const bool control_read = !local && IsLocalRead(inst.opcode);
+		if (check && ((local && local_store) || control_store || control_read)) {
+			const auto address = read(registers, inst.src0);
+			// A read may index another control point; only its record offset must be fixed.
+			const bool indexed_read = control_read && address.kind == Kind::Scaled &&
+			                          address.coefficient % input_stride == 0u;
+			if (address.kind != Kind::Affine && !indexed_read) {
 				EXIT("%s tessellation address is not affine at pc 0x%08x\n", local ? "LS" : "HS",
 				     inst.pc);
 			}
-			if (address.coefficient != 0u) {
+			if (control_store && address.coefficient == 0u) {
+				const auto first = uint64_t {address.constant} + inst.offset;
+				EXIT_NOT_IMPLEMENTED(first + 4u * inst.data_dwords > UINT32_MAX);
+				fixed_stores.push_back({address.constant, static_cast<uint32_t>(first),
+				                        static_cast<uint32_t>(first + 4u * inst.data_dwords)});
+			}
+			if (address.kind == Kind::Affine && address.coefficient != 0u) {
 				const auto expected = control_read ? input_stride : stride;
 				EXIT_NOT_IMPLEMENTED((address.coefficient & 3u) != 0u ||
 				                     (expected != 0u && expected != address.coefficient));
 				if (!control_read) stride = address.coefficient;
 			}
 		}
 		// Store vdata is a source, despite occupying the decoder's dst field.
-		if (local_store || buffer_store || inst.dst.kind != OperandKind::Vgpr) continue;
-		const auto lhs   = read(inst.src0);
-		const auto rhs   = read(inst.src1);
-		const auto third = read(inst.src2);
+		if (local_store || buffer_store || inst.dst.kind != OperandKind::Vgpr) return;
+		const auto lhs   = read(registers, inst.src0);
+		const auto rhs   = read(registers, inst.src1);
+		const auto third = read(registers, inst.src2);
 		Address    value;
 		switch (inst.opcode) {
+			case Opcode::V_MOV_B32: value = lhs; break;
 			case Opcode::V_BFE_U32:
-				if (lhs.kind == Kind::PackedControlPoint && rhs.kind == Kind::Affine &&
-				    rhs.coefficient == 0u && third.kind == Kind::Affine &&
-				    third.coefficient == 0u) {
+				if (lhs.kind == Kind::PackedControlPoint && is_constant(rhs) &&
+				    is_constant(third)) {
 					if (rhs.constant == 8u && third.constant == 5u) value = {Kind::Affine, 1u, 0u};
 					if (rhs.constant == 0u && third.constant == 8u) value = constant(0u);
 				}
 				break;
-			case Opcode::V_MUL_U32_U24: value = multiply(low24(lhs), low24(rhs)); break;
-			case Opcode::V_MAD_U32_U24: value = add(multiply(low24(lhs), low24(rhs)), third); break;
+			case Opcode::V_MUL_U32_U24: value = multiply(low24(lhs), low24(rhs), true); break;
+			case Opcode::V_MAD_U32_U24:
+				value = add(multiply(low24(lhs), low24(rhs), true), third);
+				break;
+			case Opcode::V_ADD_NC_U32: value = add(lhs, rhs); break;
+			case Opcode::V_ADD3_U32: value = add(add(lhs, rhs), third); break;
 			case Opcode::V_LSHL_ADD_U32:
-				if (rhs.kind == Kind::Affine && rhs.coefficient == 0u && rhs.constant < 32u)
-					value = add(multiply(lhs, constant(1u << rhs.constant)), third);
+				if (is_constant(rhs) && rhs.constant < 32u)
+					value = add(multiply(lhs, constant(1u << rhs.constant), false), third);
 				break;
 			case Opcode::V_LSHLREV_B32:
-				if (lhs.kind == Kind::Affine && lhs.coefficient == 0u && lhs.constant < 32u)
-					value = multiply(rhs, constant(1u << lhs.constant));
+				if (is_constant(lhs) && lhs.constant < 32u)
+					value = multiply(rhs, constant(1u << lhs.constant), false);
 				break;
 			case Opcode::V_SUB_NC_U32:
 				if (lhs.kind == Kind::Affine && rhs.kind == Kind::Affine &&
 				    lhs.coefficient >= rhs.coefficient && lhs.constant >= rhs.constant)
-					value = affine(lhs.coefficient - rhs.coefficient, lhs.constant - rhs.constant);
+					value = affine(Kind::Affine, lhs.coefficient - rhs.coefficient,
+					               lhs.constant - rhs.constant);
 				break;
 			default: break;
 		}
 		if (inst.dst.sdwa_sel != 6u || inst.dst.op_sel || inst.dst.omod || inst.dst.clamp ||
 		    inst.dst.dpp)
 			value = {};
 		for (uint32_t index = 0;
-		     index < std::max(inst.data_dwords, 1u) && inst.dst.reg + index < registers.size(); index++) {
+		     index < std::max(inst.data_dwords, 1u) && inst.dst.reg + index < registers.size();
+		     index++) {
 			registers[inst.dst.reg + index] = {};
 		}
 		registers.at(inst.dst.reg) = value;
+	};
+
+	// Forward dataflow over the stage's blocks; a register whose incoming values differ is unknown.
+	const auto& insts    = program.instructions;
+	const auto  index_of = [&](uint32_t pc) {
+		const auto it = std::ranges::lower_bound(insts, pc, {}, &Instruction::pc);
+		EXIT_IF(it == insts.end() || it->pc != pc);
+		return static_cast<size_t>(it - insts.begin());
+	};
+	std::vector<bool> leader(insts.size(), false);
+	leader.at(0) = true;
+	for (size_t index = 0; index < insts.size(); index++) {
+		if (!IsDirectBranch(insts[index].opcode)) continue;
+		leader[index_of(insts[index].branch_target)] = true;
+		if (index + 1u < insts.size()) leader[index + 1u] = true;
+	}
+	// Entry states of the reached blocks, by leader index.
+	std::unordered_map<size_t, Registers> entry;
+	entry[0].at(local ? 3u : 1u) =
+	    local ? Address {Kind::Affine, 1u, 0u} : Address {Kind::PackedControlPoint};
+	std::vector<size_t> work {0};
+	const auto          flow = [&](size_t target, const Registers& registers) {
+		const auto [it, inserted] = entry.try_emplace(target, registers);
+		bool changed              = inserted;
+		for (size_t reg = 0; !inserted && reg < registers.size(); reg++) {
+			if (it->second[reg] != registers[reg] && it->second[reg].kind != Kind::Unknown) {
+				it->second[reg] = {};
+				changed         = true;
+			}
+		}
+		if (changed) work.push_back(target);
+	};
+	const auto run = [&](size_t begin, bool check) {
+		auto registers = entry.at(begin);
+		for (size_t index = begin; index < insts.size(); index++) {
+			if (index != begin && leader[index]) {
+				if (!check) flow(index, registers);
+				return;
+			}
+			const auto& inst = insts[index];
+			step(inst, registers, check);
+			if (inst.opcode == Opcode::S_ENDPGM) return;
+			if (IsDirectBranch(inst.opcode)) {
+				if (!check) {
+					flow(index_of(inst.branch_target), registers);
+					if (IsConditionalBranch(inst.opcode) && index + 1u < insts.size())
+						flow(index + 1u, registers);
+				}
+				return;
+			}
+		}
+	};
+	while (!work.empty()) {
+		const auto begin = work.back();
+		work.pop_back();
+		run(begin, false);
+	}
+	for (size_t index = 0; index < insts.size(); index++) {
+		if (entry.contains(index)) run(index, true);
 	}
 	EXIT_NOT_IMPLEMENTED(stride == 0u);
+	if (patch != nullptr) {
+		// As in the lowering, a store address past every control point selects the patch outputs.
+		patch->patch_begin = UINT32_MAX;
+		patch->patch_end   = 0;
+		for (const auto& [address, first, end]: fixed_stores) {
+			if (address < stride * control_points) continue;
+			patch->patch_begin = std::min(patch->patch_begin, first);
+			patch->patch_end   = std::max(patch->patch_end, end);
+		}
+		if (patch->patch_end == 0u) patch->patch_begin = 0;
+	}

@NeySlim Thanks for the fix and the clarification. The supplied code now checks the full store width, including inst.offset, and rejects per-control-point HS stores that exceed their record. This addresses the unsupported affine-store case.

The is_constant() check also makes the purpose of fixed_stores clearer.


✏️ Learnings added
Learnt from: NeySlim
Repo: KytyPS5/KytyPS5 PR: 1482
File: src/graphics/shader/recompiler/Tessellation.cpp:269-279
Timestamp: 2026-10-13T19:21:16.520Z
Learning: In src/graphics/shader/recompiler/Tessellation.cpp, C++ tessellation lowering maps per-control-point HS stores to the invocation's own control-point output. ReflectTessellationStride must reject affine per-control-point stores whose constant offset, instruction offset, and full store width exceed the HS stride. Such stores cannot be treated as writes to another control-point record or patch output.

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-13 19:21 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1482#discussion_r4263012397) On `src/graphics/shader/recompiler/Tessellation.cpp` line 273 (outdated): ```diff @@ -48,108 +72,205 @@ uint32_t ReflectTessellationStride(const Decoder::Program& program, bool local, if (value.kind == Kind::PackedControlPoint && operand.sdwa_sel == 0u) return constant(0u); return operand.sdwa_sel == 6u ? value : Address {}; }; - const auto affine = [](uint64_t coefficient, uint64_t offset) { + const auto affine = [](Kind kind, uint64_t coefficient, uint64_t offset) { return coefficient <= UINT32_MAX && offset <= UINT32_MAX - ? Address {Kind::Affine, static_cast<uint32_t>(coefficient), + ? Address {kind, static_cast<uint32_t>(coefficient), static_cast<uint32_t>(offset)} : Address {}; }; const auto add = [&](Address lhs, Address rhs) { - return lhs.kind == Kind::Affine && rhs.kind == Kind::Affine - ? affine(uint64_t {lhs.coefficient} + rhs.coefficient, - uint64_t {lhs.constant} + rhs.constant) - : Address {}; + if (lhs.kind == Kind::Affine && rhs.kind == Kind::Affine) + return affine(Kind::Affine, uint64_t {lhs.coefficient} + rhs.coefficient, + uint64_t {lhs.constant} + rhs.constant); + // Ordinal multiples of a Scaled coefficient stay multiples of it. + const auto scaled = [](Address value) { + return value.kind == Kind::Affine || value.kind == Kind::Scaled; + }; + if (!scaled(lhs) || !scaled(rhs)) return Address {}; + const auto coefficient = std::gcd(lhs.coefficient, rhs.coefficient); + return affine(Kind::Scaled, coefficient, uint64_t {lhs.constant} + rhs.constant); }; - const auto multiply = [&](Address lhs, Address rhs) { - if ((lhs.kind == Kind::Affine && lhs.coefficient == 0u && lhs.constant == 0u) || - (rhs.kind == Kind::Affine && rhs.coefficient == 0u && rhs.constant == 0u)) - return constant(0u); - if (lhs.kind != Kind::Affine || rhs.kind != Kind::Affine) return Address {}; - if (rhs.coefficient != 0u) std::swap(lhs, rhs); - return rhs.coefficient == 0u ? affine(uint64_t {lhs.coefficient} * rhs.constant, - uint64_t {lhs.constant} * rhs.constant) - : Address {}; + const auto multiply = [&](Address lhs, Address rhs, bool u24) { + const auto zero = [](Address value) { + return value.kind == Kind::Affine && value.coefficient == 0u && value.constant == 0u; + }; + if (zero(lhs) || zero(rhs)) return constant(0u); + if (!is_constant(rhs)) std::swap(lhs, rhs); + if (!is_constant(rhs)) return Address {}; + if (lhs.kind == Kind::Affine) + return affine(Kind::Affine, uint64_t {lhs.coefficient} * rhs.constant, + uint64_t {lhs.constant} * rhs.constant); + if (lhs.kind == Kind::PackedControlPoint) return Address {}; + // A product by a power of two keeps that factor when it wraps; a 24-bit operand times at + // most 256 cannot wrap. + const bool power = std::has_single_bit(rhs.constant); + if (lhs.kind == Kind::Scaled && power && std::has_single_bit(lhs.coefficient)) + return affine(Kind::Scaled, uint64_t {lhs.coefficient} * rhs.constant, + uint64_t {lhs.constant} * rhs.constant); + return power || (u24 && rhs.constant <= 0x100u) ? Address {Kind::Scaled, rhs.constant, 0u} + : Address {}; }; const auto low24 = [&](Address value) { - if (value.kind == Kind::Affine && value.coefficient == 0u) - return constant(value.constant & 0xffffffu); + if (is_constant(value)) return constant(value.constant & 0xffffffu); return value.kind == Kind::Affine && uint64_t {value.coefficient} * (control_points - 1u) + value.constant <= 0xffffffu ? value : Address {}; }; uint32_t stride = 0; - for (const auto& inst: program.instructions) { - // Stage exits preserve the active path's definitions. An internal join - // would require merging register definitions. - EXIT_NOT_IMPLEMENTED(IsDirectBranch(inst.opcode) && - inst.branch_target != program.instructions.back().pc); - const bool local_store = - inst.opcode == Opcode::DS_WRITE_B32 || inst.opcode == Opcode::DS_WRITE2_B32; + // Constant-address HS stores: {address, first byte, end byte}. + std::vector<std::array<uint32_t, 3>> fixed_stores; + // Applies one instruction; ring addresses are only checked once the states are final. + const auto step = [&](const Instruction& inst, Registers& registers, bool check) { + const bool local_store = IsLocalWrite(inst.opcode); const bool buffer_store = inst.opcode == Opcode::BUFFER_STORE_DWORD || inst.opcode == Opcode::BUFFER_STORE_DWORDX2 || inst.opcode == Opcode::BUFFER_STORE_DWORDX3 || inst.opcode == Opcode::BUFFER_STORE_DWORDX4; const bool control_store = !local && buffer_store && inst.src2.kind == OperandKind::Sgpr && inst.src2.reg == 2u; - const bool control_read = - !local && (inst.opcode == Opcode::DS_READ_B32 || inst.opcode == Opcode::DS_READ2_B32); - if ((local && local_store) || control_store || control_read) { - const auto address = read(inst.src0); - if (address.kind != Kind::Affine) { + const bool control_read = !local && IsLocalRead(inst.opcode); + if (check && ((local && local_store) || control_store || control_read)) { + const auto address = read(registers, inst.src0); + // A read may index another control point; only its record offset must be fixed. + const bool indexed_read = control_read && address.kind == Kind::Scaled && + address.coefficient % input_stride == 0u; + if (address.kind != Kind::Affine && !indexed_read) { EXIT("%s tessellation address is not affine at pc 0x%08x\n", local ? "LS" : "HS", inst.pc); } - if (address.coefficient != 0u) { + if (control_store && address.coefficient == 0u) { + const auto first = uint64_t {address.constant} + inst.offset; + EXIT_NOT_IMPLEMENTED(first + 4u * inst.data_dwords > UINT32_MAX); + fixed_stores.push_back({address.constant, static_cast<uint32_t>(first), + static_cast<uint32_t>(first + 4u * inst.data_dwords)}); + } + if (address.kind == Kind::Affine && address.coefficient != 0u) { const auto expected = control_read ? input_stride : stride; EXIT_NOT_IMPLEMENTED((address.coefficient & 3u) != 0u || (expected != 0u && expected != address.coefficient)); if (!control_read) stride = address.coefficient; } } // Store vdata is a source, despite occupying the decoder's dst field. - if (local_store || buffer_store || inst.dst.kind != OperandKind::Vgpr) continue; - const auto lhs = read(inst.src0); - const auto rhs = read(inst.src1); - const auto third = read(inst.src2); + if (local_store || buffer_store || inst.dst.kind != OperandKind::Vgpr) return; + const auto lhs = read(registers, inst.src0); + const auto rhs = read(registers, inst.src1); + const auto third = read(registers, inst.src2); Address value; switch (inst.opcode) { + case Opcode::V_MOV_B32: value = lhs; break; case Opcode::V_BFE_U32: - if (lhs.kind == Kind::PackedControlPoint && rhs.kind == Kind::Affine && - rhs.coefficient == 0u && third.kind == Kind::Affine && - third.coefficient == 0u) { + if (lhs.kind == Kind::PackedControlPoint && is_constant(rhs) && + is_constant(third)) { if (rhs.constant == 8u && third.constant == 5u) value = {Kind::Affine, 1u, 0u}; if (rhs.constant == 0u && third.constant == 8u) value = constant(0u); } break; - case Opcode::V_MUL_U32_U24: value = multiply(low24(lhs), low24(rhs)); break; - case Opcode::V_MAD_U32_U24: value = add(multiply(low24(lhs), low24(rhs)), third); break; + case Opcode::V_MUL_U32_U24: value = multiply(low24(lhs), low24(rhs), true); break; + case Opcode::V_MAD_U32_U24: + value = add(multiply(low24(lhs), low24(rhs), true), third); + break; + case Opcode::V_ADD_NC_U32: value = add(lhs, rhs); break; + case Opcode::V_ADD3_U32: value = add(add(lhs, rhs), third); break; case Opcode::V_LSHL_ADD_U32: - if (rhs.kind == Kind::Affine && rhs.coefficient == 0u && rhs.constant < 32u) - value = add(multiply(lhs, constant(1u << rhs.constant)), third); + if (is_constant(rhs) && rhs.constant < 32u) + value = add(multiply(lhs, constant(1u << rhs.constant), false), third); break; case Opcode::V_LSHLREV_B32: - if (lhs.kind == Kind::Affine && lhs.coefficient == 0u && lhs.constant < 32u) - value = multiply(rhs, constant(1u << lhs.constant)); + if (is_constant(lhs) && lhs.constant < 32u) + value = multiply(rhs, constant(1u << lhs.constant), false); break; case Opcode::V_SUB_NC_U32: if (lhs.kind == Kind::Affine && rhs.kind == Kind::Affine && lhs.coefficient >= rhs.coefficient && lhs.constant >= rhs.constant) - value = affine(lhs.coefficient - rhs.coefficient, lhs.constant - rhs.constant); + value = affine(Kind::Affine, lhs.coefficient - rhs.coefficient, + lhs.constant - rhs.constant); break; default: break; } if (inst.dst.sdwa_sel != 6u || inst.dst.op_sel || inst.dst.omod || inst.dst.clamp || inst.dst.dpp) value = {}; for (uint32_t index = 0; - index < std::max(inst.data_dwords, 1u) && inst.dst.reg + index < registers.size(); index++) { + index < std::max(inst.data_dwords, 1u) && inst.dst.reg + index < registers.size(); + index++) { registers[inst.dst.reg + index] = {}; } registers.at(inst.dst.reg) = value; + }; + + // Forward dataflow over the stage's blocks; a register whose incoming values differ is unknown. + const auto& insts = program.instructions; + const auto index_of = [&](uint32_t pc) { + const auto it = std::ranges::lower_bound(insts, pc, {}, &Instruction::pc); + EXIT_IF(it == insts.end() || it->pc != pc); + return static_cast<size_t>(it - insts.begin()); + }; + std::vector<bool> leader(insts.size(), false); + leader.at(0) = true; + for (size_t index = 0; index < insts.size(); index++) { + if (!IsDirectBranch(insts[index].opcode)) continue; + leader[index_of(insts[index].branch_target)] = true; + if (index + 1u < insts.size()) leader[index + 1u] = true; + } + // Entry states of the reached blocks, by leader index. + std::unordered_map<size_t, Registers> entry; + entry[0].at(local ? 3u : 1u) = + local ? Address {Kind::Affine, 1u, 0u} : Address {Kind::PackedControlPoint}; + std::vector<size_t> work {0}; + const auto flow = [&](size_t target, const Registers& registers) { + const auto [it, inserted] = entry.try_emplace(target, registers); + bool changed = inserted; + for (size_t reg = 0; !inserted && reg < registers.size(); reg++) { + if (it->second[reg] != registers[reg] && it->second[reg].kind != Kind::Unknown) { + it->second[reg] = {}; + changed = true; + } + } + if (changed) work.push_back(target); + }; + const auto run = [&](size_t begin, bool check) { + auto registers = entry.at(begin); + for (size_t index = begin; index < insts.size(); index++) { + if (index != begin && leader[index]) { + if (!check) flow(index, registers); + return; + } + const auto& inst = insts[index]; + step(inst, registers, check); + if (inst.opcode == Opcode::S_ENDPGM) return; + if (IsDirectBranch(inst.opcode)) { + if (!check) { + flow(index_of(inst.branch_target), registers); + if (IsConditionalBranch(inst.opcode) && index + 1u < insts.size()) + flow(index + 1u, registers); + } + return; + } + } + }; + while (!work.empty()) { + const auto begin = work.back(); + work.pop_back(); + run(begin, false); + } + for (size_t index = 0; index < insts.size(); index++) { + if (entry.contains(index)) run(index, true); } EXIT_NOT_IMPLEMENTED(stride == 0u); + if (patch != nullptr) { + // As in the lowering, a store address past every control point selects the patch outputs. + patch->patch_begin = UINT32_MAX; + patch->patch_end = 0; + for (const auto& [address, first, end]: fixed_stores) { + if (address < stride * control_points) continue; + patch->patch_begin = std::min(patch->patch_begin, first); + patch->patch_end = std::max(patch->patch_end, end); + } + if (patch->patch_end == 0u) patch->patch_begin = 0; + } ``` `@NeySlim` Thanks for the fix and the clarification. The supplied code now checks the full store width, including `inst.offset`, and rejects per-control-point HS stores that exceed their record. This addresses the unsupported affine-store case. The `is_constant()` check also makes the purpose of `fixed_stores` clearer. --- <details> <summary>✏️ Learnings added</summary> ``` Learnt from: NeySlim Repo: KytyPS5/KytyPS5 PR: 1482 File: src/graphics/shader/recompiler/Tessellation.cpp:269-279 Timestamp: 2026-10-13T19:21:16.520Z Learning: In src/graphics/shader/recompiler/Tessellation.cpp, C++ tessellation lowering maps per-control-point HS stores to the invocation's own control-point output. ReflectTessellationStride must reject affine per-control-point stores whose constant offset, instruction offset, and full store width exceed the HS stride. Such stores cannot be treated as writes to another control-point record or patch output. ``` > 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=%40coderabbitai%20caught%20a%20subtle%20tessellation%20bug%3A%20affine%20stores%20could%20escape%20a%20control-point%20record%20and%20leave%20patch%20ranges%20unset.%20Reflection%20now%20rejects%20them%2C%20with%20a%20host%20test.%20Try%20%40coderabbitai%20%F0%9F%A9%BA&url=https%3A%2F%2Fgithub.com%2FKytyPS5%2FKytyPS5%2Fpull%2F1482%23discussion_r4262893990)? 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

@⁠NeySlim on GitHub · 2026-10-14 05:59 UTC · original

Related: #1245 (GTA V tree trunks) touches the same code. It adds the patch input attribute, reflects the patch range from the HS and follows LS/HS data through branches and wide LDS accesses, which is roughly the first half of this PR. The two conflict textually in Tessellation.cpp, spirvEmitterTessellation.cpp, shader.cpp/h and the tessellation tests.

#1245 alone does not get God of War Ragnarök's terrain through. On top of it the game needs:

  • integer partitioning (#1245 only accepts partitioning == 2, GoW uses 0)
  • HS output readback, where the HS reads back what it wrote for its own control point (#1245 rejects reads of HS outputs)
  • reads of another control point of the patch (cp + 1 mod 3)
  • caching the LS/HS reflection per shader pair, otherwise it runs on every patch draw

#1245 also has V_AND_B32 for the masked patch ordinal, which this PR does not need for GoW.

If #1245 lands first I can rebase this one on it so that only the cases above remain in the diff.

**@⁠NeySlim** on GitHub · 2026-10-14 05:59 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1482#issuecomment-6161979306) Related: #1245 (GTA V tree trunks) touches the same code. It adds the patch input attribute, reflects the patch range from the HS and follows LS/HS data through branches and wide LDS accesses, which is roughly the first half of this PR. The two conflict textually in Tessellation.cpp, spirvEmitterTessellation.cpp, shader.cpp/h and the tessellation tests. #1245 alone does not get God of War Ragnarök's terrain through. On top of it the game needs: - integer partitioning (#1245 only accepts `partitioning == 2`, GoW uses 0) - HS output readback, where the HS reads back what it wrote for its own control point (#1245 rejects reads of HS outputs) - reads of another control point of the patch (`cp + 1 mod 3`) - caching the LS/HS reflection per shader pair, otherwise it runs on every patch draw #1245 also has `V_AND_B32` for the masked patch ordinal, which this PR does not need for GoW. If #1245 lands first I can rebase this one on it so that only the cases above remain in the diff.
Author
Owner

@⁠NeySlim on GitHub · 2026-10-15 16:50 UTC · original

Pushed 090aad7de on top. Once the DS gets real patch data, the snowy terrain in the Freya scene turned into a flat grey slab in front of her: the depth prepass and the gbuffer pass ended up with different tessellated positions.

The trigger is a RADV bug (Mesa 26.2.4): when a TCS writes a per-vertex output at a dynamic location/component, the TES reads 0 from its non-constant patch outputs. We addressed every ring attribute as address % stride at runtime, while the guest always uses stride * cp + const. The emitter now turns that into a constant offset when it's the same for every lane passing the access predicate, and keeps the old path otherwise. Only the control point index stays dynamic.

CheckTessellationProgram now requires no OpUMod for the stride programs, and fails without the change. I couldn't get a GPU test to hit the driver bug inside the emulator, so the GPU evidence is the game plus a standalone GLSL repro, which I'll file with Mesa.

before/after

**@⁠NeySlim** on GitHub · 2026-10-15 16:50 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1482#issuecomment-6197458573) Pushed 090aad7de on top. Once the DS gets real patch data, the snowy terrain in the Freya scene turned into a flat grey slab in front of her: the depth prepass and the gbuffer pass ended up with different tessellated positions. The trigger is a RADV bug (Mesa 26.2.4): when a TCS writes a per-vertex output at a dynamic location/component, the TES reads 0 from its non-constant patch outputs. We addressed every ring attribute as `address % stride` at runtime, while the guest always uses `stride * cp + const`. The emitter now turns that into a constant offset when it's the same for every lane passing the access predicate, and keeps the old path otherwise. Only the control point index stays dynamic. CheckTessellationProgram now requires no OpUMod for the stride programs, and fails without the change. I couldn't get a GPU test to hit the driver bug inside the emulator, so the GPU evidence is the game plus a standalone GLSL repro, which I'll file with Mesa. ![before/after](https://github.com/NeySlim/KytyPS5/raw/media/gow-tess-freya.jpg)
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-16 00:46 UTC · original · reviewed

🧹 Nitpick comments: 1
src/graphics/shader/shader.cpp: 1

649-664: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low value

The layout cache lock is held during analysis, and the cache is unbounded.

The key contains the LS hash, the HS hash, and both control-point counts. This matches the learning on context-dependent cache keys. The analysis also depends only on those inputs and on params[0].code and params[1].code, so the key looks complete.

Two minor concerns remain:

  • std::scoped_lock lock(mutex) stays held while AnalyzeTessellationPrograms runs on a cache miss. Other threads that prepare tessellation draws block during the decode.
  • layouts grows without a bound. The practical risk is small because the number of LS/HS pairs is limited.

Release the lock around the analysis. A duplicate analysis on a race is harmless because the result is deterministic. Use emplace, which keeps the first entry.

Proposed change
-	std::scoped_lock lock(mutex);
-	if (const auto found = layouts.find(key); found != layouts.end()) {
-		tess.ls_stride   = found->second.ls_stride;
-		tess.hs_stride   = found->second.hs_stride;
-		tess.patch_begin = found->second.patch_begin;
-		tess.patch_end   = found->second.patch_end;
-	} else {
-		ShaderRecompiler::AnalyzeTessellationPrograms(params[0].code, params[1].code, tess);
-		layouts.emplace(key, tess);
-	}
+	{
+		std::scoped_lock lock(mutex);
+		if (const auto found = layouts.find(key); found != layouts.end()) {
+			tess.ls_stride   = found->second.ls_stride;
+			tess.hs_stride   = found->second.hs_stride;
+			tess.patch_begin = found->second.patch_begin;
+			tess.patch_end   = found->second.patch_end;
+			goto cached;
+		}
+	}
+	ShaderRecompiler::AnalyzeTessellationPrograms(params[0].code, params[1].code, tess);
+	{
+		std::scoped_lock lock(mutex);
+		layouts.emplace(key, tess);
+	}
+cached:

A lambda that returns a bool for "cache hit" is cleaner than goto.


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 6e729fa5-767b-4736-ad2c-4b7608d24721
📥 Commits

Reviewing files that changed from the base of the PR and between 090aad7de90d9461bbd5bd45a556e892b9360207 and 01e9147f9451f96e2b6b5421c24e0cfefd33828a.

📒 Files selected for processing: 5
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h
  • src/graphics/shader/recompiler/ir/ShaderIR.h
  • src/graphics/shader/shader.cpp
  • src/graphics/shader/shader.h
  • tests/ShaderRecompilerComputeTests.cpp

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

**@⁠coderabbitai[bot]** on GitHub · 2026-10-16 00:46 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1482#pullrequestreview-5541657454) · **reviewed** <details> <summary>🧹 Nitpick comments: 1</summary><blockquote> <details> <summary>src/graphics/shader/shader.cpp: 1</summary><blockquote> `649-664`: **🚀 Performance & Scalability** | **🔵 Trivial** | **💤 Low value** **The layout cache lock is held during analysis, and the cache is unbounded.** The key contains the LS hash, the HS hash, and both control-point counts. This matches the learning on context-dependent cache keys. The analysis also depends only on those inputs and on `params[0].code` and `params[1].code`, so the key looks complete. Two minor concerns remain: - `std::scoped_lock lock(mutex)` stays held while `AnalyzeTessellationPrograms` runs on a cache miss. Other threads that prepare tessellation draws block during the decode. - `layouts` grows without a bound. The practical risk is small because the number of LS/HS pairs is limited. Release the lock around the analysis. A duplicate analysis on a race is harmless because the result is deterministic. Use `emplace`, which keeps the first entry. <details> <summary>Proposed change</summary> ```diff - std::scoped_lock lock(mutex); - if (const auto found = layouts.find(key); found != layouts.end()) { - tess.ls_stride = found->second.ls_stride; - tess.hs_stride = found->second.hs_stride; - tess.patch_begin = found->second.patch_begin; - tess.patch_end = found->second.patch_end; - } else { - ShaderRecompiler::AnalyzeTessellationPrograms(params[0].code, params[1].code, tess); - layouts.emplace(key, tess); - } + { + std::scoped_lock lock(mutex); + if (const auto found = layouts.find(key); found != layouts.end()) { + tess.ls_stride = found->second.ls_stride; + tess.hs_stride = found->second.hs_stride; + tess.patch_begin = found->second.patch_begin; + tess.patch_end = found->second.patch_end; + goto cached; + } + } + ShaderRecompiler::AnalyzeTessellationPrograms(params[0].code, params[1].code, tess); + { + std::scoped_lock lock(mutex); + layouts.emplace(key, tess); + } +cached: ``` </details> A lambda that returns a bool for "cache hit" is cleaner than `goto`. <!-- cr-comment:v1:652db69ade0d6be7b7c0b09f --> </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**: `6e729fa5-767b-4736-ad2c-4b7608d24721` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 090aad7de90d9461bbd5bd45a556e892b9360207 and 01e9147f9451f96e2b6b5421c24e0cfefd33828a. </details> <details> <summary>📒 Files selected for processing: 5</summary> * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.h` * `src/graphics/shader/recompiler/ir/ShaderIR.h` * `src/graphics/shader/shader.cpp` * `src/graphics/shader/shader.h` * `tests/ShaderRecompilerComputeTests.cpp` </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 6 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=d27246d8-8732-45ce-a96a-73714623dc5f attempt=ce59c340-2678-4ebb-952f-5faee784fa15 batch=1/1 -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-20 18:34 UTC · original · edited 2026-10-20 19:41 UTC
On src/graphics/shader/recompiler/backend/spirv/spirvEmitterTessellation.cpp line 26 (outdated):

@@ -16,6 +17,46 @@ bool IsTessellationPatch(IR::TessellationAttribute kind) {
 	return kind == Attribute::PatchOutput || kind == Attribute::PatchInput;
 }
 
+// The offset of a ring address inside its control point record when it is the same for every
+// lane that passes the access predicate: control point terms are multiples of the stride. Ring
+// addresses never wrap.
+std::optional<uint32_t> RecordOffset(const IR::Value& value, uint32_t stride,
+                                     const IR::Value& predicate) {
+	const auto resolved = value.Resolve();
+	if (resolved.IsImmediate()) return resolved.U32() % stride;

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
rg -nP -C3 '\bIAdd32\b' src/graphics/shader/recompiler --type=cpp -g '!**/backend/**' | rg -n -C3 -i 'sub|neg|-\s*\d|0xffff'
rg -nP -C2 'ValueOpcode::ISub32|\bISub32\b' src/graphics/shader/recompiler --type=cpp

Repository: KytyPS5/KytyPS5

Length of output: 26123


🏁 Script executed:

set -eu
printf '%s\n' '--- spirv emitter context ---'
nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterTessellation.cpp | sed -n '1,180p'
printf '%s\n' '--- tessellation record-offset and pointer flow ---'
nl -ba src/graphics/shader/recompiler/Tessellation.cpp | sed -n '260,470p'
printf '%s\n' '--- relevant IR value and emitter declarations ---'
rg -n -F --glob '*.h' --glob '*.cpp' -e 'class Value' -e 'Value::Value' -e 'Immediate' -e 'IAdd32' -e 'ISub32' src/graphics/shader/recompiler/ir src/graphics/shader/recompiler/frontend | head -n 240
printf '%s\n' '--- base versus head target implementation ---'
git diff 7b7f9a70c652afd6ec8ea8599884d9b4b3abc9f3 -- src/graphics/shader/recompiler/backend/spirv/spirvEmitterTessellation.cpp src/graphics/shader/recompiler/Tessellation.cpp

Repository: KytyPS5/KytyPS5

Length of output: 41898


🏁 Script executed:

set -eu
nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterTessellation.cpp | sed -n '1,140p'
nl -ba src/graphics/shader/recompiler/Tessellation.cpp | sed -n '280,380p'
git diff 7b7f9a70c652afd6ec8ea8599884d9b4b3abc9f3 -- src/graphics/shader/recompiler/backend/spirv/spirvEmitterTessellation.cpp src/graphics/shader/recompiler/Tessellation.cpp

Repository: KytyPS5/KytyPS5

Length of output: 35367


🏁 Script executed:

set -eu
printf '%s\n' '--- reviewed emitter ---'
sed -n '1,90p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterTessellation.cpp
printf '%s\n' '--- RecordOffset definition and callers ---'
rg -n -C5 -F -- 'RecordOffset' src/graphics/shader/recompiler --glob '*.cpp' --glob '*.h'
printf '%s\n' '--- immediate constructors and negative/inline constants ---'
rg -n -C4 -P 'Inline|inline|Immediate|static_cast<int32_t>|int32_t\(.*Value|Value\(-|0xfffffff' src/graphics/shader/recompiler/frontend src/graphics/shader/recompiler/ir --glob '*.cpp' --glob '*.h' || test "$?" -eq 1
printf '%s\n' '--- relevant changed diff ---'
git diff 7b7f9a70c652afd6ec8ea8599884d9b4b3abc9f3 -- src/graphics/shader/recompiler/backend/spirv/spirvEmitterTessellation.cpp src/graphics/shader/recompiler/Tessellation.cpp

Repository: KytyPS5/KytyPS5

Length of output: 8056


🏁 Script executed:

set -eu
printf '%s\n' '--- frontend integer translation ---'
rg -n -C6 --glob '*.cpp' --glob '*.h' -e 'SimpleInteger' -e 'V_ADD_NC_U32' -e 'V_SUB_NC_U32' -e 'OperandKind::' src/graphics/shader/recompiler/frontend src/graphics/shader/recompiler/ir | head -n 320
printf '%s\n' '--- immediate and literal conversion ---'
rg -n -C6 --glob '*.cpp' --glob '*.h' -i -e 'inline.?constant' -e 'literal' -e 'ImmediateU32' -e 'Value\(.*src' -e 'Value\(.*operand' -e 'Operand.*value' src/graphics/shader/recompiler | head -n 320
printf '%s\n' '--- IAdd and ISub translation definitions ---'
nl -ba src/graphics/shader/recompiler/frontend/translate/Vector.cpp | sed -n '600,645p'
nl -ba src/graphics/shader/recompiler/ir/IREmitter.cpp | sed -n '150,172p'

Repository: KytyPS5/KytyPS5

Length of output: 41902


🏁 Script executed:

set -eu
printf '%s\n' '--- SimpleInteger definition and operand conversion ---'
rg -n -C8 --glob '*.cpp' --glob '*.h' 'SimpleInteger\s*\(' src/graphics/shader/recompiler/frontend
printf '%s\n' '--- frontend operand/value helpers ---'
rg -n -C6 --glob '*.cpp' --glob '*.h' -e 'inst\.src[0-3].*Value' -e 'src[0-3].*value' -e 'Operand.*Value' -e 'Value\(.*signed_val' src/graphics/shader/recompiler/frontend src/graphics/shader/recompiler/ir | head -n 260

Repository: KytyPS5/KytyPS5

Length of output: 41646


🏁 Script executed:

set -eu
rg -n -C10 --glob '*.cpp' --glob '*.h' 'ReadOperand\s*\(|SourceAt\s*\(' src/graphics/shader/recompiler/frontend/translate | head -n 260

Repository: KytyPS5/KytyPS5

Length of output: 26944


🏁 Script executed:

set -eu
rg -n -C8 --glob '*.cpp' --glob '*.h' -F -- 'ReadOperand' src/graphics/shader/recompiler

Repository: KytyPS5/KytyPS5

Length of output: 37639


Normalize negative inline constants before computing the record offset.

The decoder represents inline -16 as 0xFFFFFFF0, and V_ADD_NC_U32 passes that source through SimpleInteger as IAdd32. RecordOffset then applies unsigned modulo to the immediate. With stride == 48, this produces 0 instead of the correct signed offset 32, which can select the wrong tessellation attribute and component.

Dynamic bases still use the existing runtime modulo fallback.

🐛 Suggested fix
--- "a/src/graphics/shader/recompiler/backend/spirv/spirvEmitterTessellation.cpp"
+++ "b/src/graphics/shader/recompiler/backend/spirv/spirvEmitterTessellation.cpp"
@@ -22,8 +22,13 @@
 // addresses never wrap.
 std::optional<uint32_t> RecordOffset(const IR::Value& value, uint32_t stride,
                                      const IR::Value& predicate) {
 	const auto resolved = value.Resolve();
-	if (resolved.IsImmediate()) return resolved.U32() % stride;
+	if (resolved.IsImmediate()) {
+		// Address immediates may encode negative displacements (e.g. inline constants -1..-16).
+		const auto imm = static_cast<int64_t>(static_cast<int32_t>(resolved.U32()));
+		const auto mod = static_cast<int64_t>(stride);
+		return static_cast<uint32_t>((imm % mod + mod) % mod);
+	}
 	const auto* inst = resolved.TryInstruction();
 	if (inst == nullptr) return std::nullopt;
 	const auto operand = [&](size_t index) {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

	if (resolved.IsImmediate()) {
		// Address immediates may encode negative displacements (e.g. inline constants -1..-16).
		const auto imm = static_cast<int64_t>(static_cast<int32_t>(resolved.U32()));
		const auto mod = static_cast<int64_t>(stride);
		return static_cast<uint32_t>((imm % mod + mod) % mod);
	}

✅ Confirmed as addressed by @⁠NeySlim

**@⁠coderabbitai[bot]** on GitHub · 2026-10-20 18:34 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1482#discussion_r4328754293) · edited 2026-10-20 19:41 UTC On `src/graphics/shader/recompiler/backend/spirv/spirvEmitterTessellation.cpp` line 26 (outdated): ```diff @@ -16,6 +17,46 @@ bool IsTessellationPatch(IR::TessellationAttribute kind) { return kind == Attribute::PatchOutput || kind == Attribute::PatchInput; } +// The offset of a ring address inside its control point record when it is the same for every +// lane that passes the access predicate: control point terms are multiples of the stride. Ring +// addresses never wrap. +std::optional<uint32_t> RecordOffset(const IR::Value& value, uint32_t stride, + const IR::Value& predicate) { + const auto resolved = value.Resolve(); + if (resolved.IsImmediate()) return resolved.U32() % stride; ``` <!-- coderabbit-ai-generated:v1 --> **🎯 Functional Correctness** | **🟠 Major** | **⚡ Quick win** <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash #!/bin/bash rg -nP -C3 '\bIAdd32\b' src/graphics/shader/recompiler --type=cpp -g '!**/backend/**' | rg -n -C3 -i 'sub|neg|-\s*\d|0xffff' rg -nP -C2 'ValueOpcode::ISub32|\bISub32\b' src/graphics/shader/recompiler --type=cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 26123 --- 🏁 Script executed: ```bash set -eu printf '%s\n' '--- spirv emitter context ---' nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterTessellation.cpp | sed -n '1,180p' printf '%s\n' '--- tessellation record-offset and pointer flow ---' nl -ba src/graphics/shader/recompiler/Tessellation.cpp | sed -n '260,470p' printf '%s\n' '--- relevant IR value and emitter declarations ---' rg -n -F --glob '*.h' --glob '*.cpp' -e 'class Value' -e 'Value::Value' -e 'Immediate' -e 'IAdd32' -e 'ISub32' src/graphics/shader/recompiler/ir src/graphics/shader/recompiler/frontend | head -n 240 printf '%s\n' '--- base versus head target implementation ---' git diff 7b7f9a70c652afd6ec8ea8599884d9b4b3abc9f3 -- src/graphics/shader/recompiler/backend/spirv/spirvEmitterTessellation.cpp src/graphics/shader/recompiler/Tessellation.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 41898 --- 🏁 Script executed: ```bash set -eu nl -ba src/graphics/shader/recompiler/backend/spirv/spirvEmitterTessellation.cpp | sed -n '1,140p' nl -ba src/graphics/shader/recompiler/Tessellation.cpp | sed -n '280,380p' git diff 7b7f9a70c652afd6ec8ea8599884d9b4b3abc9f3 -- src/graphics/shader/recompiler/backend/spirv/spirvEmitterTessellation.cpp src/graphics/shader/recompiler/Tessellation.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 35367 --- 🏁 Script executed: ```bash set -eu printf '%s\n' '--- reviewed emitter ---' sed -n '1,90p' src/graphics/shader/recompiler/backend/spirv/spirvEmitterTessellation.cpp printf '%s\n' '--- RecordOffset definition and callers ---' rg -n -C5 -F -- 'RecordOffset' src/graphics/shader/recompiler --glob '*.cpp' --glob '*.h' printf '%s\n' '--- immediate constructors and negative/inline constants ---' rg -n -C4 -P 'Inline|inline|Immediate|static_cast<int32_t>|int32_t\(.*Value|Value\(-|0xfffffff' src/graphics/shader/recompiler/frontend src/graphics/shader/recompiler/ir --glob '*.cpp' --glob '*.h' || test "$?" -eq 1 printf '%s\n' '--- relevant changed diff ---' git diff 7b7f9a70c652afd6ec8ea8599884d9b4b3abc9f3 -- src/graphics/shader/recompiler/backend/spirv/spirvEmitterTessellation.cpp src/graphics/shader/recompiler/Tessellation.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 8056 --- 🏁 Script executed: ```bash set -eu printf '%s\n' '--- frontend integer translation ---' rg -n -C6 --glob '*.cpp' --glob '*.h' -e 'SimpleInteger' -e 'V_ADD_NC_U32' -e 'V_SUB_NC_U32' -e 'OperandKind::' src/graphics/shader/recompiler/frontend src/graphics/shader/recompiler/ir | head -n 320 printf '%s\n' '--- immediate and literal conversion ---' rg -n -C6 --glob '*.cpp' --glob '*.h' -i -e 'inline.?constant' -e 'literal' -e 'ImmediateU32' -e 'Value\(.*src' -e 'Value\(.*operand' -e 'Operand.*value' src/graphics/shader/recompiler | head -n 320 printf '%s\n' '--- IAdd and ISub translation definitions ---' nl -ba src/graphics/shader/recompiler/frontend/translate/Vector.cpp | sed -n '600,645p' nl -ba src/graphics/shader/recompiler/ir/IREmitter.cpp | sed -n '150,172p' ``` Repository: KytyPS5/KytyPS5 Length of output: 41902 --- 🏁 Script executed: ```bash set -eu printf '%s\n' '--- SimpleInteger definition and operand conversion ---' rg -n -C8 --glob '*.cpp' --glob '*.h' 'SimpleInteger\s*\(' src/graphics/shader/recompiler/frontend printf '%s\n' '--- frontend operand/value helpers ---' rg -n -C6 --glob '*.cpp' --glob '*.h' -e 'inst\.src[0-3].*Value' -e 'src[0-3].*value' -e 'Operand.*Value' -e 'Value\(.*signed_val' src/graphics/shader/recompiler/frontend src/graphics/shader/recompiler/ir | head -n 260 ``` Repository: KytyPS5/KytyPS5 Length of output: 41646 --- 🏁 Script executed: ```bash set -eu rg -n -C10 --glob '*.cpp' --glob '*.h' 'ReadOperand\s*\(|SourceAt\s*\(' src/graphics/shader/recompiler/frontend/translate | head -n 260 ``` Repository: KytyPS5/KytyPS5 Length of output: 26944 --- 🏁 Script executed: ```bash set -eu rg -n -C8 --glob '*.cpp' --glob '*.h' -F -- 'ReadOperand' src/graphics/shader/recompiler ``` Repository: KytyPS5/KytyPS5 Length of output: 37639 --- </details> **Normalize negative inline constants before computing the record offset.** The decoder represents inline `-16` as `0xFFFFFFF0`, and `V_ADD_NC_U32` passes that source through `SimpleInteger` as `IAdd32`. `RecordOffset` then applies unsigned modulo to the immediate. With `stride == 48`, this produces `0` instead of the correct signed offset `32`, which can select the wrong tessellation attribute and component. Dynamic bases still use the existing runtime modulo fallback. <details> <summary>🐛 Suggested fix</summary> ```diff --- "a/src/graphics/shader/recompiler/backend/spirv/spirvEmitterTessellation.cpp" +++ "b/src/graphics/shader/recompiler/backend/spirv/spirvEmitterTessellation.cpp" @@ -22,8 +22,13 @@ // addresses never wrap. std::optional<uint32_t> RecordOffset(const IR::Value& value, uint32_t stride, const IR::Value& predicate) { const auto resolved = value.Resolve(); - if (resolved.IsImmediate()) return resolved.U32() % stride; + if (resolved.IsImmediate()) { + // Address immediates may encode negative displacements (e.g. inline constants -1..-16). + const auto imm = static_cast<int64_t>(static_cast<int32_t>(resolved.U32())); + const auto mod = static_cast<int64_t>(stride); + return static_cast<uint32_t>((imm % mod + mod) % mod); + } const auto* inst = resolved.TryInstruction(); if (inst == nullptr) return std::nullopt; const auto operand = [&](size_t index) { ``` </details> <!-- suggestion_start --> <details> <summary>📝 Committable suggestion</summary> > ‼️ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. ```suggestion if (resolved.IsImmediate()) { // Address immediates may encode negative displacements (e.g. inline constants -1..-16). const auto imm = static_cast<int64_t>(static_cast<int32_t>(resolved.U32())); const auto mod = static_cast<int64_t>(stride); return static_cast<uint32_t>((imm % mod + mod) % mod); } ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:d904f1b204f0578e7fbb2d11 --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Confirmed as addressed by @⁠NeySlim <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

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

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 41287c7d-2fb2-499d-8216-e7467bab0ed1
📥 Commits

Reviewing files that changed from the base of the PR and between 01e9147f9451f96e2b6b5421c24e0cfefd33828a and fecf7e689df03d5bcae4ae7e2371290f575bc496.

📒 Files selected for processing: 3
  • src/graphics/shader/recompiler/Tessellation.cpp
  • src/graphics/shader/recompiler/backend/spirv/spirvEmitterTessellation.cpp
  • tests/ShaderRecompilerComputeTests.cpp

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

**@⁠coderabbitai[bot]** on GitHub · 2026-10-20 18:34 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1482#pullrequestreview-5589790430) · **reviewed** **Actionable comments posted: 1** --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> - **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `41287c7d-2fb2-499d-8216-e7467bab0ed1` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 01e9147f9451f96e2b6b5421c24e0cfefd33828a and fecf7e689df03d5bcae4ae7e2371290f575bc496. </details> <details> <summary>📒 Files selected for processing: 3</summary> * `src/graphics/shader/recompiler/Tessellation.cpp` * `src/graphics/shader/recompiler/backend/spirv/spirvEmitterTessellation.cpp` * `tests/ShaderRecompilerComputeTests.cpp` </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=cca61326-b1d7-4ce3-9384-9674a889110e attempt=196765fc-0e2f-4221-a935-038a2936c950 batch=1/1 -->
Author
Owner

@⁠NeySlim on GitHub · 2026-10-20 19:40 UTC · original
On src/graphics/shader/recompiler/backend/spirv/spirvEmitterTessellation.cpp line 26 (outdated):

@@ -16,6 +17,46 @@ bool IsTessellationPatch(IR::TessellationAttribute kind) {
 	return kind == Attribute::PatchOutput || kind == Attribute::PatchInput;
 }
 
+// The offset of a ring address inside its control point record when it is the same for every
+// lane that passes the access predicate: control point terms are multiples of the stride. Ring
+// addresses never wrap.
+std::optional<uint32_t> RecordOffset(const IR::Value& value, uint32_t stride,
+                                     const IR::Value& predicate) {
+	const auto resolved = value.Resolve();
+	if (resolved.IsImmediate()) return resolved.U32() % stride;

Right, a negative inline constant next to a control point term gave the wrong residue when the stride does not divide 2^32. Immediates are now taken as signed, and CheckTessellationProgram covers it with a -16 add on the HS read (fails without the fix).

**@⁠NeySlim** on GitHub · 2026-10-20 19:40 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1482#discussion_r4329469900) On `src/graphics/shader/recompiler/backend/spirv/spirvEmitterTessellation.cpp` line 26 (outdated): ```diff @@ -16,6 +17,46 @@ bool IsTessellationPatch(IR::TessellationAttribute kind) { return kind == Attribute::PatchOutput || kind == Attribute::PatchInput; } +// The offset of a ring address inside its control point record when it is the same for every +// lane that passes the access predicate: control point terms are multiples of the stride. Ring +// addresses never wrap. +std::optional<uint32_t> RecordOffset(const IR::Value& value, uint32_t stride, + const IR::Value& predicate) { + const auto resolved = value.Resolve(); + if (resolved.IsImmediate()) return resolved.U32() % stride; ``` Right, a negative inline constant next to a control point term gave the wrong residue when the stride does not divide 2^32. Immediates are now taken as signed, and `CheckTessellationProgram` covers it with a `-16` add on the HS read (fails without the fix).
Author
Owner

@⁠NeySlim on GitHub · 2026-10-20 19:41 UTC · original

Rebased on main. 4a2961cdf and 0957f088a now cover forward branches, wide DS writes, the reflected patch range and PatchInput, and c71589124 caches the layouts with a better key, so I dropped my cache commit and moved the rest onto main's structures. What's left is what main still refuses in this game: a loop before the ring stores (main's scan only takes forward branches, GoW stops on Tessellation.cpp:133 without it), HS reads of another control point ((cp + 1) % 3), the HS reading back its own outputs, wide DS reads, integer and fractional even spacing, plus the two follow-ups (stores outside the control point record, static ring offsets). CheckTessellationLoop, TessellationBranchedRing and TessellationPatchDraw fail on main without it. Checked in game with --tessellation on top of current main: no stop, terrain and snow look right.

**@⁠NeySlim** on GitHub · 2026-10-20 19:41 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1482#issuecomment-6299773489) Rebased on main. 4a2961cdf and 0957f088a now cover forward branches, wide DS writes, the reflected patch range and `PatchInput`, and c71589124 caches the layouts with a better key, so I dropped my cache commit and moved the rest onto main's structures. What's left is what main still refuses in this game: a loop before the ring stores (main's scan only takes forward branches, GoW stops on Tessellation.cpp:133 without it), HS reads of another control point (`(cp + 1) % 3`), the HS reading back its own outputs, wide DS reads, integer and fractional even spacing, plus the two follow-ups (stores outside the control point record, static ring offsets). `CheckTessellationLoop`, `TessellationBranchedRing` and `TessellationPatchDraw` fail on main without it. Checked in game with `--tessellation` on top of current main: no stop, terrain and snow look right.
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-20 19:41 UTC · original
On src/graphics/shader/recompiler/backend/spirv/spirvEmitterTessellation.cpp line 26 (outdated):

@@ -16,6 +17,46 @@ bool IsTessellationPatch(IR::TessellationAttribute kind) {
 	return kind == Attribute::PatchOutput || kind == Attribute::PatchInput;
 }
 
+// The offset of a ring address inside its control point record when it is the same for every
+// lane that passes the access predicate: control point terms are multiples of the stride. Ring
+// addresses never wrap.
+std::optional<uint32_t> RecordOffset(const IR::Value& value, uint32_t stride,
+                                     const IR::Value& predicate) {
+	const auto resolved = value.Resolve();
+	if (resolved.IsImmediate()) return resolved.U32() % stride;

@⁠NeySlim Thanks for fixing this. The signed conversion and residue normalization address the incorrect offset. The reported -16 HS-read regression in CheckTessellationProgram covers the failing case.


🧠 Learnings used
Learnt from: NeySlim
Repo: KytyPS5/KytyPS5 PR: 1482
File: src/graphics/shader/recompiler/Tessellation.cpp:269-279
Timestamp: 2026-10-13T19:21:19.027Z
Learning: In src/graphics/shader/recompiler/Tessellation.cpp, C++ tessellation lowering maps per-control-point HS stores to the invocation's own control-point output. ReflectTessellationStride must reject affine per-control-point stores whose constant offset, instruction offset, and full store width exceed the HS stride. Such stores cannot be treated as writes to another control-point record or patch output.

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-20 19:41 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1482#discussion_r4329474441) On `src/graphics/shader/recompiler/backend/spirv/spirvEmitterTessellation.cpp` line 26 (outdated): ```diff @@ -16,6 +17,46 @@ bool IsTessellationPatch(IR::TessellationAttribute kind) { return kind == Attribute::PatchOutput || kind == Attribute::PatchInput; } +// The offset of a ring address inside its control point record when it is the same for every +// lane that passes the access predicate: control point terms are multiples of the stride. Ring +// addresses never wrap. +std::optional<uint32_t> RecordOffset(const IR::Value& value, uint32_t stride, + const IR::Value& predicate) { + const auto resolved = value.Resolve(); + if (resolved.IsImmediate()) return resolved.U32() % stride; ``` <!-- coderabbit-ai-generated:v1 --> @⁠NeySlim Thanks for fixing this. The signed conversion and residue normalization address the incorrect offset. The reported `-16` HS-read regression in `CheckTessellationProgram` covers the failing case. --- <details> <summary>🧠 Learnings used</summary> ``` Learnt from: NeySlim Repo: KytyPS5/KytyPS5 PR: 1482 File: src/graphics/shader/recompiler/Tessellation.cpp:269-279 Timestamp: 2026-10-13T19:21:19.027Z Learning: In src/graphics/shader/recompiler/Tessellation.cpp, C++ tessellation lowering maps per-control-point HS stores to the invocation's own control-point output. ReflectTessellationStride must reject affine per-control-point stores whose constant offset, instruction offset, and full store width exceed the HS stride. Such stores cannot be treated as writes to another control-point record or patch output. ``` </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=%40coderabbitai%20caught%20a%20subtle%20tessellation%20bug%3A%20signed%20inline%20constants%20were%20treated%20as%20unsigned%2C%20producing%20wrong%20record%20offsets.%20Their%20fix%20restores%20correct%20modulo%20behavior%E2%80%94try%20it%20for%20sharper%20reviews!%20%F0%9F%8E%AF%F0%9F%9A%80&url=https%3A%2F%2Fgithub.com%2FKytyPS5%2FKytyPS5%2Fpull%2F1482%23discussion_r4328754293)? 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

@⁠Nmzik on GitHub · 2026-10-21 03:47 UTC · original

Credited

**@⁠Nmzik** on GitHub · 2026-10-21 03:47 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1482#issuecomment-6307549050) Credited

Pull request closed

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