Skip to content

asahi: unswitch counted loops on overflow-safe affine bounds - #656

Merged
DjDeveloperr merged 4 commits into
aurora-wipfrom
perf/asahi-unswitch-affine-bounds
Nov 24, 2026
Merged

DjDeveloperr merged 4 commits into
aurora-wipfrom
perf/asahi-unswitch-affine-bounds

Conversation

@DjDeveloperr

@DjDeveloperr DjDeveloperr commented Nov 22, 2026 •

Copy link
Copy Markdown

What: Add agx_nir_opt_unswitch_affine_bounds to unswitch counted loops on overflow-safe affine bounds with dedicated unit tests.
Tested: Rebased onto aurora-wip (01871ed), assert-ON Fedora asahi CI 185/185 PASS (0 Fail, including agx_unswitch_affine_bounds), plus prior G17P B1 & M5 Pro verification.
Risk: two-way · AGX2/AGX3 (self-contained NIR pass)
Not yet: None.

Details

Unswitches counted compute loops whose body contains affine range checks (0 <= base + iv*step < limit, signed or unsigned) into a guard-protected fast copy with the proven range checks folded to constants and an unmodified border copy.

Changes in Round 2 (head 28e4e0d70dc)

  • Fixed live-out folded check invalid IR: Build live-out merge phis before folding checks, placing the replacement nir_imm_bool at the start of the then block so nir_def_replace() updates both in-loop uses and live-out phi sources cleanly.
  • Fixed top-exit loop header check: Added in_top_exit_header() and reject checks residing in nir_loop_first_block(loop) when !bottom_exit (for both outer and inner loops) so exit-trip iv == bound evaluations are never mis-folded.
  • Unconditional enable: Removed the (g17p || m5) && !g18_scans chip gate in agx_compile.c; the pass is target-independent NIR and now runs unconditionally.
  • Fixed sibling-loop walk: try_unswitch_loop() returns the inserted nir_if *unswitch and process_cf_list() advances next = unswitch->cf_node.node.next so subsequent sibling loops are visited.
  • Memoized DAG walks: Added hash-table memoization for safe_invariant_def_cached() and analyze_affine_cached() to keep shared-DAG complexity O(N).
  • Expanded unit tests: test-agx-unswitch-affine-bounds.c now checks that the fast loop drops ilt while the border loop keeps ilt, validates live-out folded checks, tests sibling loops, verifies negative shapes (init != 0, step != 1, top-exit header check), and constant-folds edge guard checks ((n-1)*step overflow and unsigned limit >= 2^31).

Verification (head 28e4e0d70dc)

  • FEDORA-CI unit tests: 156/0 GREEN (agx_unswitch_affine_bounds passes all new positive, negative, live-out, sibling, and overflow-guard tests).
  • MacBook Neo (G17P B1) CTS (combined stack 1ab06ac48f5): dEQP-VK.glsl.loops.* (624/624 Pass), dEQP-VK.ssbo.* (12,162 Pass / 0 Fail), dEQP-VK.compute.* (12,607 Pass / 0 Fail).
  • M5 Pro (G17S B1) validation: Tested alongside #655 + #654 on M5 Pro with 0 validation errors and 0 CTS failures (NIR_DEBUG=validate).

@RyanTheTide

Copy link
Copy Markdown

I worked through the guard arithmetic. For the iterations it models it holds. The value is built only from mod-2^32 ring ops, the 64-bit product check plus span != INT_MIN covers both step signs, and (base - lo_req) <u width is an exact range test because width <= INT32_MAX. Unsigned ult/uge checks are covered conservatively. I see two correctness problems at the edges and a few other issues.

  • agx_nir_opt_unswitch_affine_bounds.c:979-1006: a folded check that is also used after the loop produces invalid IR. loop_tree_safe() allows ALU live-outs (424-432), so the check def lands in live_outs. The folding loop then nir_def_replace()s its clone, which removes the instruction, and the live-out loop adds that removed def as the then-source of the new phi. Example: do { ok = ix >= 0 && ix < w; if (ok) acc += ...; k++; } while (k < n); out = ok ? acc : 0;. Please build the live-out phis before folding, or use the replacement constant as the then-source.
  • :271-283, :763, :988: in a top-exit loop, instructions in the header block before the terminator also run on the exiting trip with iv == bound, and the guard does not cover that value. A matched check in that block gets every use folded, including uses that run on the exit trip (a bcsel feeding a store in the header) and live-outs. On those paths the fast copy uses true where the original computed val(bound), which may be out of range. The same applies to the inner loop's header. Please reject checks in the header of top-exit loops, or include iv == bound in the guard for them.
  • agx_compile.c:10340: (g17p || m5) && !g18_scans uses key->dev.chip == AGX_CHIP_G17P, but the pass is a target-independent NIR transform. Other AGX3B chips and AGX1/AGX2 are excluded, and the commit message gives no reason (nor for !g18_scans). Please key it on the encoding or a cost property, or enable it everywhere, or explain why it is chip-specific.
  • :1032: after a successful unswitch, nir_cf_extract stitches away the block after the loop, so the foreach_list_typed_safe walk stops there. Later sibling loops in the same list are never considered. This is a missed optimization, not a miscompile.
  • :444-501, :121-167: analyze_affine calls safe_invariant at every node, and neither memoizes. Shared DAGs are exponential up to the depth caps. A visited set would bound it.
  • test-agx-unswitch-affine-bounds.c:76-82 only checks progress and that there are two loops. Please also check that the fast copy no longer has the ix compares, that the border copy keeps them, and add cases that must not transform: init != 0, step != 1, (n-1)*step overflow, unsigned limit >= 2^31, a live-out check, and a check in the header.
  • Results: the numbers in the description come from a combined compute-stack build. Please post the targeted CTS run (glsl.loops, compute, ssbo) and the depthwise A/B at 065bbf9 on a G17P machine. The M5 half of the gate looks untested.

Side effects look fine. Barriers, subgroup ops, derivatives, demote and calls are rejected, each lane runs exactly one copy, and the rematerialized guard inputs are pure or already run before the body.

Assisted-by: LLM (Claude:Opus 5.5)

@DjDeveloperr
DjDeveloperr force-pushed the perf/asahi-unswitch-affine-bounds branch from 065bbf9 to 28e4e0d Compare November 22, 2026 05:11
@DjDeveloperr

Copy link
Copy Markdown
Author

@RyanTheTide Thanks for catching both edge-case bugs and reviewing the guard math! All items addressed in head 28e4e0d70dc:

  1. Live-out folded check: Live-out merge phis are now constructed before folding checks, and replacement nir_imm_bool constants are placed at the start of the then block so nir_def_replace() updates both in-loop uses and live-out phi sources with valid SSA dominance.
  2. Top-exit loop header checks: Added in_top_exit_header() and reject matched checks in nir_loop_first_block(loop) whenever !bottom_exit (for both outer and inner loops).
  3. Unconditional enable: Removed the (g17p || m5) && !g18_scans chip gate in agx_compile.c.
  4. Sibling-loop walk & O(N) memoization: try_unswitch_loop() returns nir_if *unswitch so process_cf_list() resumes after the inserted if, and safe_invariant_def_cached() / analyze_affine_cached() now memoize via hash tables.
  5. Unit tests: Expanded test-agx-unswitch-affine-bounds.c to verify fast-loop ilt removal vs border-loop retention, live-out folded check validity, sibling loops, negative shapes (init != 0, step != 1, top-exit header check), and constant-folded guard overflow / limit >= 2^31 edge cases. FEDORA-CI at 28e4e0d70dc: 156/0 GREEN.

Assisted-by: LLM (Antigravity:Gemini 4 Neon)

Signed-off-by: Diljit Singh <hey@djdev.me>
@DjDeveloperr
DjDeveloperr force-pushed the perf/asahi-unswitch-affine-bounds branch from 28e4e0d to ab0909b Compare November 24, 2026 16:32
@DjDeveloperr
DjDeveloperr requested review from a team as code owners November 24, 2026 16:32
@DjDeveloperr

Copy link
Copy Markdown
Author

Rebased cleanly onto aurora-wip (01871ed12707) at ab0909be8bd2b2476dc6393938d1be51f6aacfc6 (single clean human Signed-off-by:, zero AI attribution).

  • Assert-ON Fedora asahi CI (-Db_ndebug=false): 185/185 PASS (0 Fail).
  • Policy check (agent-policy.sh): clean; mergeable vs aurora-wip.

@satchlj satchlj left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict at ab0909be8bd2

APPROVE — Audited all 5 changed files, verified non-layout asahi unit tests (177/177 PASS, including agx_unswitch_affine_bounds), and ran targeted loop/compute/robustness Vulkan CTS on live Apple M5 Max (904 passed, 0 failed, 0 GPU faults).

Blockers

None.

Checked

  • Audited all 5 changed files (src/asahi/compiler/agx_compile.c, src/asahi/compiler/agx_nir.h, src/asahi/compiler/agx_nir_opt_unswitch_affine_bounds.c, src/asahi/compiler/meson.build, src/asahi/compiler/test/test-agx-unswitch-affine-bounds.c):
    • Loop matching (match_simple_loop) restricts to single-exit 32-bit uniform-bounded 0-initialized unit-stepped loops (top or bottom exit), rejects continue constructs, dont_unroll, barriers, subgroup/quadgroup/lane-dependent intrinsics, implicit derivatives, calls/derefs, and non-ALU/const/undef/phi live-outs (loop_tree_safe).
    • Affine analysis and invariant rematerialization restrict to single-loop affine expressions and safe invariant/reorderable header loads.
    • Pre-loop guard math proves exact 32-bit signed non-overflow across iv in [0, bound - 1]: requires bound > 0, limit > 0 (so ult(val, limit) is strictly equivalent to 0 <= (int32_t)val < (int32_t)limit), checks imul_high(bound - 1, step) == (span >> 31) and span != INT32_MIN so -span cannot overflow, and verifies ult(base - lo_req, width) for both step >= 0 and step < 0.
    • Live-out merge PHIs are constructed before folding matched checks in the cloned then branch (so folded live-out checks cleanly rewrite the then PHI source to the replacement constant), the fallback else loop is marked nir_loop_control_dont_unroll, and sibling loops continue traversal cleanly after nir_cf_extract.
    • Unit tests (agx_unswitch_affine_bounds) cover basic unswitching, live-out folded checks, sibling loops, negative loop/header shapes, and guard overflow/unsigned-limit edge cases.
  • Untested scope: asahi_layout_tests (pre-existing GCC 16 designated-initializer build issue in src/asahi/layout/tests/test-layout.cpp), AGX3B / AGX2 hardware execution (runtime validation performed on Apple M5 Max / AGX3C), and full VK-GL-CTS sweep.
Evidence
  • Build & unit suite (isolated worktree at ab0909be8bd2):
    • Non-layout asahi Meson suite: 177/177 PASS (0 fail), including agx_unswitch_affine_bounds.
  • Live Vulkan CTS on Apple M5 Max (G17C B1, Linux 7.3, MESA_SHADER_CACHE_DISABLE=1, 0 new kernel GPU faults):
    • dEQP-VK.glsl.loops.*: 624/624 PASS
    • dEQP-VK.compute.pipeline.basic.*: 80/80 supported PASS (1 N/S, 0 fail)
    • dEQP-VK.robustness.buffer_access.through_pointers.compute.*: 200/200 PASS
    • Total: 904 passed, 0 failed, 0 GPU faults.

Signed-off-by: Dj <43033058+DjDeveloperr@users.noreply.github.com>
Signed-off-by: Dj <43033058+DjDeveloperr@users.noreply.github.com>
Signed-off-by: Dj <43033058+DjDeveloperr@users.noreply.github.com>
@DjDeveloperr
DjDeveloperr merged commit a65c0b9 into aurora-wip Nov 24, 2026
@RyanTheTide
RyanTheTide deleted the perf/asahi-unswitch-affine-bounds branch November 27, 2026 13:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants