refactor(shader): drop unused folded constants and unreachable blocks after specialization #4431

Merged
AlxcBTW merged 3 commits from upstream-pr/4431 into main 2026-10-12 19:30:40 +00:00
AlxcBTW commented 2026-10-12 10:56:42 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by AlxcBTW on 2026-10-12T10:56:42Z.


What

SpecializeSpirv folds the specialization constants of a prepared module, but leaves two kinds of debris in the module it returns:

  • fold() hoists every instruction it folds into a module-level OpConstant/OpConstantTrue/OpConstantFalse and keeps it after the instructions that read it have folded away too. In one compute module 58,834 such constants remain, 1,286 of them referenced.
  • prune() turns every block a folded branch cuts off into OpLabel; OpUnreachable and never removes it, even when no instruction names the label. A formatted buffer access with a known descriptor leaves about 1,800 of them from its 77-case format switch.

This change emits only the folded constants that a remaining instruction refers to, and removes OpLabel; OpUnreachable blocks that no instruction names. Merge and continue targets of live constructs are named by their header, so they stay. Behaviour is unchanged; the specialized modules get smaller.

agc_formatted_buffer_once compared the words two more formatted loads add with a tenth of the module. That module was mostly debris; without it, the module has 1,219 words and the two call sites add 225. The check now requires the two extra loads to add fewer words than the first one, which also brings the shared function. A second copy of the function per load still fails both this check and the existing function-count checks.

No compile-time or speed claim. The NVIDIA driver removes the same dead code itself: pipeline creation of the same modules before and after this change took the same time within noise, with the same binary size and register count (RTX 5070 Laptop, driver 616.92: 49/46 ms, 686/744 ms, 330/361 ms, 3368/3019 ms). The gain is smaller modules in memory, in the hashing of prepared modules and in pipeline caches.

Tested

Windows 11, offline on the shader disk cache of one title (Sword of the Sea, 2,865 prepared modules). For every module the harness applies the same spec-constant replacement as buildSpecializedModule, then SpecializeSpirv from main and from this branch. The harness synthesizes the buffer descriptor values; the vertex-input and fragment-output specializations are not applied.

stage modules words after specialization, main this branch change
compute 1,624 192.6 M 128.6 M -33 % (median module 1.39x smaller, at most 25.4x)
vertex 337 50.0 M 17.4 M -65 %
fragment 872 54.9 M 46.4 M -15 %
mesh 32 1.9 M 1.5 M -19 %
  • spirv-val --target-env vulkan1.3: 80 randomly chosen modules under 200k words and 4 modules of 300k to 640k words are valid with main and with this branch.
  • The new case in tests/SpirvModule.cpp (a constant switch whose dead cases fold) fails three checks on main and passes on this branch, built with GCC 15.2.
  • Full Linux and Windows builds and tests on the fork: all pass (Linux 950 tests, Vulkan ones on lavapipe; Windows 944 tests, Vulkan ones skipped without a GPU; plus the relinker, register-context and write-watch matrices), fork run 38238424661 on main e7c70a2d.
  • Not tested: a game run with this change, AMD and Intel.

Checklist

  • Based on current main; no other open PR implements the same functions
  • One topic per PR; follow-ups go in a new PR
  • No comments in code except technical debt
  • Unimplemented paths throw (NotImplemented_nid_no_patch); silent stubs are listed in TechnicalDebt
  • No notes, investigation .md files or images added to the repository (attach them to this PR)
  • New third-party code is a submodule built from source
  • Generic behaviour, not specific to one title
  • Depends on: none
  • AI-assisted: yes (Claude Code)

🤖 Generated with Claude Code

<!-- greyfinch-sync:boykopovar/AnyPS5:issue:4828397433 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/4431). Originally posted by [AlxcBTW](https://github.com/AlxcBTW) on 2026-10-12T10:56:42Z. --- ### What `SpecializeSpirv` folds the specialization constants of a prepared module, but leaves two kinds of debris in the module it returns: - `fold()` hoists every instruction it folds into a module-level `OpConstant`/`OpConstantTrue`/`OpConstantFalse` and keeps it after the instructions that read it have folded away too. In one compute module 58,834 such constants remain, 1,286 of them referenced. - `prune()` turns every block a folded branch cuts off into `OpLabel; OpUnreachable` and never removes it, even when no instruction names the label. A formatted buffer access with a known descriptor leaves about 1,800 of them from its 77-case format switch. This change emits only the folded constants that a remaining instruction refers to, and removes `OpLabel; OpUnreachable` blocks that no instruction names. Merge and continue targets of live constructs are named by their header, so they stay. Behaviour is unchanged; the specialized modules get smaller. `agc_formatted_buffer_once` compared the words two more formatted loads add with a tenth of the module. That module was mostly debris; without it, the module has 1,219 words and the two call sites add 225. The check now requires the two extra loads to add fewer words than the first one, which also brings the shared function. A second copy of the function per load still fails both this check and the existing function-count checks. No compile-time or speed claim. The NVIDIA driver removes the same dead code itself: pipeline creation of the same modules before and after this change took the same time within noise, with the same binary size and register count (RTX 5070 Laptop, driver 616.92: 49/46 ms, 686/744 ms, 330/361 ms, 3368/3019 ms). The gain is smaller modules in memory, in the hashing of prepared modules and in pipeline caches. ### Tested Windows 11, offline on the shader disk cache of one title (Sword of the Sea, 2,865 prepared modules). For every module the harness applies the same spec-constant replacement as `buildSpecializedModule`, then `SpecializeSpirv` from `main` and from this branch. The harness synthesizes the buffer descriptor values; the vertex-input and fragment-output specializations are not applied. | stage | modules | words after specialization, `main` | this branch | change | |---|---|---|---|---| | compute | 1,624 | 192.6 M | 128.6 M | -33 % (median module 1.39x smaller, at most 25.4x) | | vertex | 337 | 50.0 M | 17.4 M | -65 % | | fragment | 872 | 54.9 M | 46.4 M | -15 % | | mesh | 32 | 1.9 M | 1.5 M | -19 % | - `spirv-val --target-env vulkan1.3`: 80 randomly chosen modules under 200k words and 4 modules of 300k to 640k words are valid with `main` and with this branch. - The new case in `tests/SpirvModule.cpp` (a constant switch whose dead cases fold) fails three checks on `main` and passes on this branch, built with GCC 15.2. - Full Linux and Windows builds and tests on the fork: all pass (Linux 950 tests, Vulkan ones on lavapipe; Windows 944 tests, Vulkan ones skipped without a GPU; plus the relinker, register-context and write-watch matrices), fork run 38238424661 on `main` e7c70a2d. - Not tested: a game run with this change, AMD and Intel. ### Checklist - [x] Based on current `main`; no other open PR implements the same functions - [x] One topic per PR; follow-ups go in a new PR - [x] No comments in code except [technical debt](https://github.com/boykopovar/AnyPS5/blob/main/docs/dev/CONVENTIONS.md) - [x] Unimplemented paths throw (`NotImplemented_nid_no_patch`); silent stubs are listed in [TechnicalDebt](https://github.com/boykopovar/AnyPS5/blob/main/docs/dev/TechnicalDebt.md#silent-stubs) - [x] No notes, investigation `.md` files or images added to the repository (attach them to this PR) - [x] New third-party code is a submodule built from source - [x] Generic behaviour, not specific to one title - [x] Depends on: none - [x] AI-assisted: yes (Claude Code) 🤖 Generated with [Claude Code](https://claude.com/claude-code)
MarcZX10 commented 2026-10-12 11:01:03 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-12T11:01:03Z.

Code review location: core/shader/recompiler/SpirvBackend/src/SpirvSpecialization.cpp; line 514

@@ -505,6 +507,50 @@ class Specialization {
         return changed;
     }
 
+    std::set<std::uint32_t> referencedIds() const {
+        std::set<std::uint32_t> referenced;
+        for (const auto& instruction : instructions) {
+            if (instruction.empty()) continue;
+            const auto op = Opcode(instruction);

referencedIds() currently treats every operand word as an ID. Literal operands can collide with result IDs and keep dead constants alive—for example, an OpTypeInt width literal of 32 will mark an otherwise-unused constant with result ID 32 as referenced. Could this use SPIR-V operand-kind/def-use information, with a regression case for a literal/result-ID collision? That would verify the pass removes ordinary dead constants even when their numeric ID appears as a literal elsewhere.

<!-- greyfinch-sync:boykopovar/AnyPS5:review-comment:4247262809 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/4431#discussion_r4247262809). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-12T11:01:03Z. **Code review location:** `core/shader/recompiler/SpirvBackend/src/SpirvSpecialization.cpp`; line 514 ~~~~diff @@ -505,6 +507,50 @@ class Specialization { return changed; } + std::set<std::uint32_t> referencedIds() const { + std::set<std::uint32_t> referenced; + for (const auto& instruction : instructions) { + if (instruction.empty()) continue; + const auto op = Opcode(instruction); ~~~~ --- `referencedIds()` currently treats every operand word as an ID. Literal operands can collide with result IDs and keep dead constants alive—for example, an `OpTypeInt` width literal of `32` will mark an otherwise-unused constant with result ID `32` as referenced. Could this use SPIR-V operand-kind/def-use information, with a regression case for a literal/result-ID collision? That would verify the pass removes ordinary dead constants even when their numeric ID appears as a literal elsewhere.
AlxcBTW commented 2026-10-12 15:17:51 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by AlxcBTW on 2026-10-12T15:17:51Z.

Code review location: core/shader/recompiler/SpirvBackend/src/SpirvSpecialization.cpp; line 514

@@ -505,6 +507,50 @@ class Specialization {
         return changed;
     }
 
+    std::set<std::uint32_t> referencedIds() const {
+        std::set<std::uint32_t> referenced;
+        for (const auto& instruction : instructions) {
+            if (instruction.empty()) continue;
+            const auto op = Opcode(instruction);

Thanks, that was a real leak. Fixed in 676622fd7.

referencedIds() now visits only <id> operands. For instructions that carry literals, the literal words are skipped:

  • type widths, counts and image parameters, constant values, storage classes;
  • memory access and image operand masks (the ids that follow them still count);
  • composite and shuffle indices, the OpArrayLength member;
  • the extended instruction number, entry point names, execution modes;
  • merge and function controls, branch weights;
  • OpSwitch case values (two words for a 64-bit selector);
  • group operations.

An opcode without a listed layout still counts every word. An instruction the table doesn't know can therefore only keep debris alive, never drop something that is used.

Regression case in tests/SpirvModule.cpp: the folded switch now also runs with its dead constant at id 32, the OpTypeInt width from your example, and with the dead blocks' labels as LocalSize literals. On the previous head this case fails three checks: the unreachable blocks are kept, there are 5 labels instead of 3, and %32 is kept. With the fix it passes.

On the census of prepared modules from the PR description (2,890 modules now; the cache has grown), the change removes another 88,726 words in total (at most 223 per module) and no module grows. spirv-val passes on 80 random modules.

The full Linux and Windows suite passes on the fork (Linux 965 of 965, Windows 971 of 971), merged into current main.

AI-assisted: yes (Claude Code)

<!-- greyfinch-sync:boykopovar/AnyPS5:review-comment:4249626675 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/4431#discussion_r4249626675). Originally posted by [AlxcBTW](https://github.com/AlxcBTW) on 2026-10-12T15:17:51Z. **Code review location:** `core/shader/recompiler/SpirvBackend/src/SpirvSpecialization.cpp`; line 514 ~~~~diff @@ -505,6 +507,50 @@ class Specialization { return changed; } + std::set<std::uint32_t> referencedIds() const { + std::set<std::uint32_t> referenced; + for (const auto& instruction : instructions) { + if (instruction.empty()) continue; + const auto op = Opcode(instruction); ~~~~ --- Thanks, that was a real leak. Fixed in 676622fd7. `referencedIds()` now visits only `<id>` operands. For instructions that carry literals, the literal words are skipped: - type widths, counts and image parameters, constant values, storage classes; - memory access and image operand masks (the ids that follow them still count); - composite and shuffle indices, the `OpArrayLength` member; - the extended instruction number, entry point names, execution modes; - merge and function controls, branch weights; - `OpSwitch` case values (two words for a 64-bit selector); - group operations. An opcode without a listed layout still counts every word. An instruction the table doesn't know can therefore only keep debris alive, never drop something that is used. Regression case in `tests/SpirvModule.cpp`: the folded switch now also runs with its dead constant at id 32, the `OpTypeInt` width from your example, and with the dead blocks' labels as `LocalSize` literals. On the previous head this case fails three checks: the unreachable blocks are kept, there are 5 labels instead of 3, and `%32` is kept. With the fix it passes. On the census of prepared modules from the PR description (2,890 modules now; the cache has grown), the change removes another 88,726 words in total (at most 223 per module) and no module grows. `spirv-val` passes on 80 random modules. The full Linux and Windows suite passes on the fork (Linux 965 of 965, Windows 971 of 971), merged into current `main`. AI-assisted: yes (Claude Code)
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
boykopovar/AnyPS5!4431
No description provided.