perf(agc): prepare registered shaders in the background #2583

Merged
gjonn merged 2 commits from upstream-pr/2583 into main 2026-10-10 08:00:12 +00:00
gjonn commented 2026-10-10 07:02:55 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by gjonn on 2026-10-10T07:02:55Z.


What

Driver::RegisterShader runs the full registration-time preparation (graph build, structurizer, PrepareShader: RDNA to IR translation and the SRT/resource plan) on the guest thread that registers the shader. The recompiler's source and plan cache is memory-only, so this work is repeated for every registered shader on every boot, even with a warm shader disk cache. A title that registers hundreds of shaders while loading blocks its loader thread one shader at a time.

This change splits PrepareRegistered in two:

  • PlanRegistered runs at registration as before. It reads the registers, validates the entry point and header metadata, decodes the code, decides deferral and builds the recompile request. Invalid registrations still fail synchronously in RegisterShader.
  • The heavy part (graph build, structurize, PrepareShader) runs on a small background pool: hardware_concurrency() / 2 detached pthreads (at least 2) with 64 MiB stacks, because the recompiler can recurse deeply.

The snapshot is published right away and marked pending. When the job finishes, its entries and the registered ABI key are merged into snapshot->prepared under its mutex, the pending flag is cleared, and waiters are notified. SourceHandleFor, InvocationFor and ShaderPreparationTransaction::Edit / Read wait for a pending snapshot before they look at its prepared state, so a draw, dispatch or ABI resolution that arrives early waits for the in-flight job instead of reporting a missing artifact or preparing the shader a second time. If the background job throws, the error is logged and rethrown at the first use of that shader.

Transactions now copy the state on Read, as well as on Edit. Commit skips snapshots that were only read, and before swapping it appends any entries and registered ABIs that were added to the live state after the copy. Without this, a reader could iterate entries while another thread was appending to it, and Commit could drop artifacts appended concurrently by the first-use paths or the background merge.

APS5_SYNC_SHADER_PREPARE=1 restores the old synchronous behaviour. ABI resolution and the null pixel shader are unchanged.

Tested

Windows 11, MinGW-w64 GCC, NVIDIA RTX 5090 Laptop GPU, Release build.

Title PPSA01317, two warm-cache boots on the same machine with the same settings, with and without the background preparation. These runs used a local build that carries the same change; I did not repeat the title run on this exact branch after porting it to current main.

  • First frame: +24 s before, +10 s after.
  • Title menu reached and rendering steadily (about 5 FPS): about +79 s before, about +57 s after. That is roughly 22 s less per boot.
  • Before the change, thread sampling showed the loader thread inside PrepareResourceProgram / Structurizer / SrtPlanBuilder while the other game threads waited about 15 s on GPU end-of-pipe events during menu load. With the change, that stall is gone.
  • Both runs had the same shader preparation failures (same "left unprepared" reasons, no new categories) and no skipped draws or dispatches.

Unit tests: agc_shader_bindless, agc_shader_frontend_pair, agc_shader_frontend_pair_off, agc_shader_memory, agc_shader_disk_cache, agc_driver_prepared_exports, agc_driver_prepared_graphics, agc_driver_prepared_publication and the six agc_driver_prepared_shaders* variants.

Build default APS5_SYNC_SHADER_PREPARE=1
main (092e133e) 14/14 pass 14/14 pass
this PR 14/14 pass (5 repeated runs) 14/14 pass (3 runs)

A new case in agc_driver_prepared_shaders covers the pending state. SourceHandleFor and InvocationFor called on a pending snapshot wait for the background result and reuse it. A failed background preparation is rethrown by ShaderPreparationTransaction::Read, SourceHandleFor and InvocationFor. The existing registration tests still see invalid program addresses, out-of-range entry points, truncated metadata, zero thread counts and undecodable code fail synchronously in RegisterShader.

Full ^agc_ CTest run with this PR: 295/296 pass in both modes. The one failure, agc_driver_f32_arithmetic_nan, also fails on unmodified main on this machine.

Overlap

Two open PRs change the same code. Neither does what this PR does, and they are complementary, but they will conflict textually (git merge-tree reports conflicts in ShaderRegistry.cpp against both heads).

  • #2363 moves PrepareRegistered out of the preparation writer lock so concurrent registering threads stop serialising. Preparation still runs synchronously on each registering thread. This PR stops RegisterShader from waiting for the heavy preparation at all, which is what helps a single loader thread that registers serially. Whichever lands second needs a small rebase in RegisterShader and the transaction lock code.
  • #2327 removes the redundant structurize pre-check inside PrepareRegistered. That makes each background job cheaper. Here the pre-check has moved into the background half (PrepareRegistered(RegisteredPreparation&)), so #2327 would drop those two lines there after a rebase. #2327 also needs a rebase onto current main on its own.

Checklist

  • Based on current main; no other open PR implements the same functions (related open PRs: see Overlap)
  • 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
<!-- greyfinch-sync:boykopovar/AnyPS5:issue:4809440291 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/2583). Originally posted by [gjonn](https://github.com/gjonn) on 2026-10-10T07:02:55Z. --- ### What `Driver::RegisterShader` runs the full registration-time preparation (graph build, structurizer, `PrepareShader`: RDNA to IR translation and the SRT/resource plan) on the guest thread that registers the shader. The recompiler's source and plan cache is memory-only, so this work is repeated for every registered shader on every boot, even with a warm shader disk cache. A title that registers hundreds of shaders while loading blocks its loader thread one shader at a time. This change splits `PrepareRegistered` in two: - `PlanRegistered` runs at registration as before. It reads the registers, validates the entry point and header metadata, decodes the code, decides deferral and builds the recompile request. Invalid registrations still fail synchronously in `RegisterShader`. - The heavy part (graph build, structurize, `PrepareShader`) runs on a small background pool: `hardware_concurrency() / 2` detached pthreads (at least 2) with 64 MiB stacks, because the recompiler can recurse deeply. The snapshot is published right away and marked pending. When the job finishes, its entries and the registered ABI key are merged into `snapshot->prepared` under its mutex, the pending flag is cleared, and waiters are notified. `SourceHandleFor`, `InvocationFor` and `ShaderPreparationTransaction::Edit` / `Read` wait for a pending snapshot before they look at its prepared state, so a draw, dispatch or ABI resolution that arrives early waits for the in-flight job instead of reporting a missing artifact or preparing the shader a second time. If the background job throws, the error is logged and rethrown at the first use of that shader. Transactions now copy the state on `Read`, as well as on `Edit`. `Commit` skips snapshots that were only read, and before swapping it appends any entries and registered ABIs that were added to the live state after the copy. Without this, a reader could iterate `entries` while another thread was appending to it, and `Commit` could drop artifacts appended concurrently by the first-use paths or the background merge. `APS5_SYNC_SHADER_PREPARE=1` restores the old synchronous behaviour. ABI resolution and the null pixel shader are unchanged. ### Tested Windows 11, MinGW-w64 GCC, NVIDIA RTX 5090 Laptop GPU, Release build. Title `PPSA01317`, two warm-cache boots on the same machine with the same settings, with and without the background preparation. These runs used a local build that carries the same change; I did not repeat the title run on this exact branch after porting it to current `main`. - First frame: +24 s before, +10 s after. - Title menu reached and rendering steadily (about 5 FPS): about +79 s before, about +57 s after. That is roughly 22 s less per boot. - Before the change, thread sampling showed the loader thread inside `PrepareResourceProgram` / `Structurizer` / `SrtPlanBuilder` while the other game threads waited about 15 s on GPU end-of-pipe events during menu load. With the change, that stall is gone. - Both runs had the same shader preparation failures (same "left unprepared" reasons, no new categories) and no skipped draws or dispatches. Unit tests: `agc_shader_bindless`, `agc_shader_frontend_pair`, `agc_shader_frontend_pair_off`, `agc_shader_memory`, `agc_shader_disk_cache`, `agc_driver_prepared_exports`, `agc_driver_prepared_graphics`, `agc_driver_prepared_publication` and the six `agc_driver_prepared_shaders*` variants. | Build | default | `APS5_SYNC_SHADER_PREPARE=1` | | --- | --- | --- | | `main` (092e133e) | 14/14 pass | 14/14 pass | | this PR | 14/14 pass (5 repeated runs) | 14/14 pass (3 runs) | A new case in `agc_driver_prepared_shaders` covers the pending state. `SourceHandleFor` and `InvocationFor` called on a pending snapshot wait for the background result and reuse it. A failed background preparation is rethrown by `ShaderPreparationTransaction::Read`, `SourceHandleFor` and `InvocationFor`. The existing registration tests still see invalid program addresses, out-of-range entry points, truncated metadata, zero thread counts and undecodable code fail synchronously in `RegisterShader`. Full `^agc_` CTest run with this PR: 295/296 pass in both modes. The one failure, `agc_driver_f32_arithmetic_nan`, also fails on unmodified `main` on this machine. ### Overlap Two open PRs change the same code. Neither does what this PR does, and they are complementary, but they will conflict textually (`git merge-tree` reports conflicts in `ShaderRegistry.cpp` against both heads). - #2363 moves `PrepareRegistered` out of the preparation writer lock so concurrent registering threads stop serialising. Preparation still runs synchronously on each registering thread. This PR stops `RegisterShader` from waiting for the heavy preparation at all, which is what helps a single loader thread that registers serially. Whichever lands second needs a small rebase in `RegisterShader` and the transaction lock code. - #2327 removes the redundant structurize pre-check inside `PrepareRegistered`. That makes each background job cheaper. Here the pre-check has moved into the background half (`PrepareRegistered(RegisteredPreparation&)`), so #2327 would drop those two lines there after a rebase. #2327 also needs a rebase onto current `main` on its own. ### Checklist - [x] Based on current `main`; no other open PR implements the same functions (related open PRs: see Overlap) - [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
adriadam10 commented 2026-10-10 07:55:40 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-10T07:55:40Z.


Rebased onto current main and added a short section to docs/dev/ARCHITECTURE.md as a separate commit.

  • Conflicts: main now defers on undecodable code in PlanRegistered, and #2327 dropped the structurize pre-check, so the background half no longer builds/structurizes the graph either.
  • Checked on the rebased tree: libSceAgcDriver tests green (310), prepared_shaders* / publication / exports / graphics tests 20× with --repeat until-fail all pass, the new test fails to build without the change.
  • Registration benchmark (RADV, 150 compute shaders of 3000 VALU instructions, cold cache, 5 runs each, same binary with and without APS5_SYNC_SHADER_PREPARE=1): time the registering thread is blocked 280 ms vs 732 ms (median); time until everything is prepared is not shorter (853 vs 733 ms, noisy), so the gain is freeing the loader thread, as the description says.
  • Not verified here: the title numbers (Windows / NVIDIA).

Merging once CI is green.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6095346025 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/2583#issuecomment-6095346025). Originally posted by [adriadam10](https://github.com/adriadam10) on 2026-10-10T07:55:40Z. --- Rebased onto current `main` and added a short section to `docs/dev/ARCHITECTURE.md` as a separate commit. - Conflicts: `main` now defers on undecodable code in `PlanRegistered`, and #2327 dropped the structurize pre-check, so the background half no longer builds/structurizes the graph either. - Checked on the rebased tree: libSceAgcDriver tests green (310), `prepared_shaders*` / publication / exports / graphics tests 20× with `--repeat until-fail` all pass, the new test fails to build without the change. - Registration benchmark (RADV, 150 compute shaders of 3000 VALU instructions, cold cache, 5 runs each, same binary with and without `APS5_SYNC_SHADER_PREPARE=1`): time the registering thread is blocked 280 ms vs 732 ms (median); time until everything is prepared is not shorter (853 vs 733 ms, noisy), so the gain is freeing the loader thread, as the description says. - Not verified here: the title numbers (Windows / NVIDIA). Merging once CI is green.
github-actions[bot] commented 2026-10-10 08:01:13 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by github-actions[bot] on 2026-10-10T08:01:13Z.


Other open pull requests touch the same code. Merging one will break the other, or both implement the same thing. If this one builds on them, list them in Depends on.

Pull request Conflicting files (lines on main) Same exports Same new files
#2363 core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp L139-141, L817
<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6095432690 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/2583#issuecomment-6095432690). Originally posted by [github-actions[bot]](https://github.com/apps/github-actions) on 2026-10-10T08:01:13Z. --- <!-- pr-overlap --> Other open pull requests touch the same code. Merging one will break the other, or both implement the same thing. If this one builds on them, list them in **Depends on**. | Pull request | Conflicting files (lines on `main`) | Same exports | Same new files | |---|---|---|---| | #2363 | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp` [L139-141](https://github.com/boykopovar/AnyPS5/blob/034dd75f858225cbe7b8568601d7e4886c6e1ebf/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp#L139-L141), [L817](https://github.com/boykopovar/AnyPS5/blob/034dd75f858225cbe7b8568601d7e4886c6e1ebf/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp#L817) | | |
Celegans12 commented 2026-10-10 12:32:46 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by Celegans12 on 2026-10-10T12:32:46Z.


I’m looking at this for Yōtei’s registration stall, and found a shutdown lifetime issue in 7fdcc34. The queued plan copies the device target, but its capability and extension spans point into the device-owned shader profile. The task captures only the snapshot and plan, while shutdown joins the existing driver workers and resets the devices without draining this detached pool. Registering an unused shader and shutting down before its job finishes can therefore leave the job reading released profile storage. Could the pool be included in shutdown, with the target's owner retained until every queued or active job has finished or been cancelled?

There’s also a pending-state failure path: the snapshot is published before task submission, and queue insertion can throw; the result-vector allocations at lines571–572 are outside the worker's catch. Those paths need to settle and notify the snapshot too, otherwise submission failure can leave a waiter blocked and result publication can escape the worker. A latch-based shutdown test and injected submission/publication failures would cover these without relying on sleeps. This is source review only; I haven’t run or measured this branch.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6097529248 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/2583#issuecomment-6097529248). Originally posted by [Celegans12](https://github.com/Celegans12) on 2026-10-10T12:32:46Z. --- I’m looking at this for Yōtei’s registration stall, and found a shutdown lifetime issue in `7fdcc34`. The [queued plan copies the device target](https://github.com/gjonn/AnyPS5/blob/7fdcc34eae743ccdd262795544f82b249b13290b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp#L463), but its capability and extension spans point into the device-owned shader profile. The [task captures only the snapshot and plan](https://github.com/gjonn/AnyPS5/blob/7fdcc34eae743ccdd262795544f82b249b13290b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp#L555), while [shutdown joins the existing driver workers and resets the devices](https://github.com/gjonn/AnyPS5/blob/7fdcc34eae743ccdd262795544f82b249b13290b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Lifecycle.cpp#L40) without draining this detached pool. Registering an unused shader and shutting down before its job finishes can therefore leave the job reading released profile storage. Could the pool be included in shutdown, with the target's owner retained until every queued or active job has finished or been cancelled? There’s also a pending-state failure path: the snapshot is published before task submission, and queue insertion can throw; the result-vector allocations at [lines571–572](https://github.com/gjonn/AnyPS5/blob/7fdcc34eae743ccdd262795544f82b249b13290b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp#L568) are outside the worker's catch. Those paths need to settle and notify the snapshot too, otherwise submission failure can leave a waiter blocked and result publication can escape the worker. A latch-based shutdown test and injected submission/publication failures would cover these without relying on sleeps. This is source review only; I haven’t run or measured this branch.
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!2583
No description provided.