Skip to content

Recompiler: enforce LOOP_BUDGET at loop headers in per-lane lowering - #2769

Open
Saksukella wants to merge 3 commits into
xcl-dev:mainfrom
Saksukella:fix/per-lane-loop-budget
Open

Saksukella wants to merge 3 commits into
xcl-dev:mainfrom
Saksukella:fix/per-lane-loop-budget

Conversation

@Saksukella

@Saksukella Saksukella commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Enforce LOOP_BUDGET at loop headers in the per-lane SSA lowering backend (XCL_PER_LANE=1), charging weighted loop_cost per header visit and keeping per-region budgets for kernel programs while keeping a single program-wide Var::Budget per lane for compute and graphics shaders. Exhausted lanes branch straight from the loop header to exit, matching direct-DXIL semantics and preventing runaway shaders from triggering Windows TDR (0x887a0006).

What is in it

  • crates/xcl/src/gpu/recomp/ssa.rs: add Var::Budget, Var::BudgetOwner, and Var::BudgetTotal.
  • crates/xcl/src/gpu/recomp/lower_dxil.rs: map Var::Budget, Var::BudgetOwner, and Var::BudgetTotal to i32 in DxilIr::ty() and handle them in DxilIr::escape().
  • crates/xcl/src/gpu/recomp/lower.rs: detect loop headers from reverse-postorder, split each loop header into a budget-check entry and continuation block, deduct weighted loop_cost (1 per 128 bytes of innermost loop code, clamped to 1..=256), apply per-region budgets (LOOP_BUDGET * 2 per region, LOOP_BUDGET * 4 total) for kernel programs only (keeping compute/graphics on a single program-wide budget to avoid the AMD compiler crash in amd-dev f84a949: AMD driver crashes (amdxc64.dll+0xd2a411) compiling the title's native DXIL compute shader ca7beffb8d3a8f28 (RX 6750 XT) #2874), and add regression tests (infinite_loop_exits_at_loop_budget, nested_loops_share_loop_budget_across_headers, long_loop_spends_its_code_size_per_header_visit, kernel_loop_after_a_full_spin_keeps_its_own_budget).

Tested

  • Hardware: AMD Radeon RX 9070 XT (driver 32.0.32029.2010), AMD Ryzen 9 7900X, 32 GB RAM, Windows 11 Pro (build 26200), rustc 1.100.0 (0ef1bc386 2026-11-09); debug (tests) and release (xcl.exe).
  • cargo test --lib -p xcl recomp::lower -- --test-threads=4: 64 passed, 0 failed, 0 ignored (2.49s), including infinite_loop_exits_at_loop_budget, nested_loops_share_loop_budget_across_headers, long_loop_spends_its_code_size_per_header_visit, and kernel_loop_after_a_full_spin_keeps_its_own_budget.
  • SKIPPED GPU sub-cases on this adapter: f16_programs_on_the_gpu (V_MUL_F16 / V_PK_MUL_F16 refused by per-lane form) and f32_programs_on_the_gpu (V_CVT_F16_F32 refused by per-lane form).
  • cargo check --workspace: passed.

Regression run

xcl-smoke v1
commit: 227d2cb388f103268dac7635ea720eb3e5352d4e
gpu: AMD Radeon RX 9070 XT
title: b8db18c2
seconds: 60
exit: 0x0
frames shown: 1674 (PresentX 1674)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 17279 MB
xcl-smoke v1
commit: a68bf237e5d02a72df1f1311b40897c1aa432c57
gpu: AMD Radeon RX 9070 XT
title: b8db18c2
seconds: 60
exit: 0x0
frames shown: 1687 (PresentX 1687)
presents per 2 s (last 3): 60 61 60
device removals: 0
crashes: 0
peak commit: 18139 MB

Not tested

  • NVIDIA and Intel GPU adapters (tested on AMD Radeon RX 9070 XT only).
  • Full cargo test --workspace run (targeted recomp::lower suite + cargo check --workspace + 60s TitleID 7952987A smoke run were executed).

AI use

  • Assisted with code review feedback alignment, regression test authoring, and rebase verification; all diffs, tests, and hardware smoke runs were verified locally.

@oni-swr

oni-swr commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

Independent amd-win test report (claim: #1607 (comment))

Tested: head 4dcc796b9d82220a3655494250bbdd4e00fcc560 (unchanged since claim; no other reports) vs. base b5c0275f (merge-base on amd-dev).
Hardware: RX 7800 XT, Ryzen 7 5700X3D, Windows 11 Pro 10.0.26200, debug build, stable-x86_64-pc-windows-msvc. Not release, not a retail title.

Commands (CARGO_TARGET_DIR separate, -j 4):

  • cargo test -p xcl --lib -j 4 -- --test-threads=4 --skip placed_title_textures_share_vram_and_preserve_pixels
  • each failing test again alone with --test-threads=1, on head and on base
  • cargo test -p xcl --lib -j 4 -- --test-threads=1 recomp::

Results

  • Head, full lib: 1533 passed, 11 failed, 27 ignored, 1 filtered (the skipped test).
  • New test gpu::recomp::lower::tests::infinite_loop_exits_at_loop_budget: passes.
  • Head recomp:: alone: 416 passed, 2 failed, 20 ignored (failures: f32_programs_on_the_gpu, a_bridged_mask_write_where_one_half_is_elsewhere_meets_no_barrier).
  • placed_title_textures_share_vram_and_preserve_pixels alone on head: passes.
  • Base, full lib: the parallel run aborted with STATUS_STACK_BUFFER_OVERRUN (known amd-dev behaviour, here in a different test than on head), so I have no clean full-run count for base. Instead I ran each of the 11 head failures alone on both commits.

Attribution (alone, --test-threads=1): the same 10 tests fail on base and on head: fuzz_validate_and_gpu_1 (#2115), dispatch_chain_native_wave64_builds_whole, a_bridged_mask_write_where_one_half_is_elsewhere_meets_no_barrier, f32_programs_on_the_gpu, a_dispatch_with_a_pipeline_still_building_waits_at_the_submit, a_put_off_dispatch_runs_at_the_submit_when_its_build_outlasts_the_wait_budget, bitset_runs_emit_exact_contiguous_page_ranges, giant_driver_compiles_have_their_own_lane, title_bytes_are_used_in_place_when_all_are_readable, physical_home_without_sparse_windows_uses_coherent_window. The 11th, two_pass_binds_set_the_shared_view_heap, fails only in the parallel run and passes alone on both. So no failure I found is caused by this PR. I did not investigate the root causes of the pre-existing ones.

SKIPPED: 4 lines, all f16_programs_on_the_gpu (f16 arithmetic and packed, wave32/wave64, per-lane form refused: V_MUL_F16 / V_PK_MUL_F16, #1426). These are not coverage.

Diff review: read the 3-file diff; no concrete defect found. The LOOP_BUDGET cap is exercised only by the CPU-interpreter test, so the GPU (DXIL) path of the new loop-header block is covered only by the existing per-lane GPU tests, which do not include a loop that hits the budget. I did not run a retail title or scripts/smoke.ps1.

AI use: Claude Code (Claude Sonnet 5.5), coordinated by Claude Code (Claude Opus 5.5). Results are from real runs on the hardware above.

@gut0to gut0to left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

AI-assisted review (OpenAI GPT-6). I checked the SSA budget flow against the other lowering backends; I did not run tests or the game.

}

#[test]
fn infinite_loop_exits_at_loop_budget() {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Var::Budget is initialized at entry and then consumed at every detected loop header, matching the shared xcl_budget in the other backends. This regression covers only one self-loop, so it does not pin SSA propagation through nested headers. Could you add a nested-loop case that shows the inner loop consumes the same per-lane budget and the total work remains bounded, rather than accidentally reinitializing at an inner header? AI-assisted review (OpenAI GPT-6); I checked the new lowering against the shared-budget paths in emit.rs and dxil/kernel.rs, but did not run tests or the game.

@Saksukella

Copy link
Copy Markdown
Contributor Author

Added nested_loops_share_loop_budget_across_headers in 9a6d83c1 right beside infinite_loop_exits_at_loop_budget: an infinite outer loop wrapping a K = 3 inner loop asserts that both headers decrement the same entry-initialized Var::Budget (s[0] + s[2] == LOOP_BUDGET and per-lane v[0][1] == expected_inner) without reinitializing at the inner header. Verified with gpu::recomp::lower::tests (38 passed; 0 failed) and a fresh 60s RX 9070 XT smoke (1,650 frames, 60 60 60, 0 crashes, 0 device removals, 15,548 MB peak commit).

rootw0rm pushed a commit to rootw0rm/xcl that referenced this pull request Nov 26, 2026
…xcl-dev#2818 (loop budget, wave32 mask kill, SDWA SDST, u32x2 routing)
@vibryxcx

Copy link
Copy Markdown

Tested on the current amd-dev and reviewed against it. The tests are fine, but the parity in the description no longer holds: since 00fe5ae the other backends spend the budget by loop cost and by region in compute, and this per-lane version spends 1 per header from one program-wide budget.

Tested: RX 6800 (RDNA2, driver 32.0.21045.5002), Windows 11 Pro 26200, Rust 1.100.0, debug. This head 9a6d83c1 sits on b5c0275f. It merges onto amd-dev bf7c82ee with no conflict, so I tested that merge against bf7c82ee, cargo test -p xcl --lib -- gpu::recomp:: --test-threads=1:

  • bf7c82ee: 430 passed, 2 failed, 20 ignored.
  • merge: 432 passed, 2 failed, 20 ignored. The only difference is the two new tests (infinite_loop_exits_at_loop_budget, nested_loops_share_loop_budget_across_headers), both ok. The 2 failures are the same on both (a_bridged_mask_write_where_one_half_is_elsewhere_meets_no_barrier, f32_programs_on_the_gpu).
  • SKIPPED: f16_programs_on_the_gpu only (4 lines, gpu: direct RDNA2 -> DXIL backend (no HLSL / DXC), behind XCL_DIRECT_DXIL #1426), on both.

Review

  1. Parity with the other backends on amd-dev. 00fe5ae ("bound long shader loops and keep mesh budgets simple") changed the HLSL path (recomp/mod.rs) and direct DXIL (dxil/kernel.rs, dxil/compact.rs) in two ways:

    This PR's per-lane lowering spends 1 per loop-header visit from a single Var::Budget for the whole program. Under XCL_PER_LANE=1, then:

    This may be deliberate. On RDNA2, per-region budgets in compute are what crash the AMD shader compiler on a retail title (amd-dev f84a949: AMD driver crashes (amdxc64.dll+0xd2a411) compiling the title's native DXIL compute shader ca7beffb8d3a8f28 (RX 6750 XT) #2874), so one budget is the safer shape for the driver. If so, saying it in the description (or porting only loop_cost) would make the difference intended rather than accidental.

  2. Exit from a loop header. An exhausted lane branches from the header straight to exit and skips the rest of the program, stores included. That matches what the HLSL and DXIL paths do. exit_stale now checks staleness only on the ends tails, not on the header-to-exit edges. So a register that is defined only after a loop header and read at exit will not be reported stale on the budget path. That seems acceptable for a runaway lane, but nothing tests it.

  3. Scope at runtime. All of this is under XCL_PER_LANE=1, which is off by default (pso.rs keys those entries as xcl-per-lane-…). A default title run does not reach it, so I did not run the title for this PR.

Not tested: XCL_PER_LANE=1 on a retail title (this card loses the device on bf7c82ee within minutes anyway, #2874); this head on its own base; NVIDIA.

AI use: Claude Code (Claude Opus 5.5) read the diff and 00fe5ae, ran the tests on base and merge, and wrote this comment.

@thehollowedone

Copy link
Copy Markdown
Contributor

Following the budget-parity review, I tested a small correction on #2769 head 9a6d83c1 merged into current amd-dev 7c795f5e.

The current base matters here: compute and graphics deliberately keep one budget because the per-region shape hit the AMD compiler (#2874); kernel programs still use per-region budgets. The candidate retains that distinction. It charges each loop header using the existing loop_cost rule, and gives kernel programs only the existing per-region owner and total counters.

Two targeted regressions exercise behavior the PR's current tests do not cover:

  • A synthetic 256-byte endless loop completes the CPU interpreter on unchanged production code but fails the new assertion: 65,536 visits versus 32,768 expected when each visit costs two units. It passes with the candidate.
  • A kernel spin that takes 65,536 visits followed by a separate three-visit loop leaves the second loop at 0/3 with the single-budget implementation, even after the code-size correction. With per-region kernel accounting it reaches 3/3 on the CPU interpreter and the RTX 3080 Ti DXIL path.

cargo test --offline --locked -j 4 -p xcl --lib gpu::recomp::lower::tests -- --test-threads=1 with the candidate: 41 passed, 0 failed, 0 ignored, including the new GPU check; four wave64 skip notices on this RTX 3080 Ti. Windows 11 build 26300, driver 621.35, Rust 1.99.1, DXC 1.8.2502.11. The full workspace suite, AMD hardware and a title run were not tested on this uncommitted candidate. This is a fix suggestion for the existing PR, not a merge-readiness claim.

Candidate diff, including the focused regressions
diff --git a/crates/xcl/src/gpu/recomp/lower.rs b/crates/xcl/src/gpu/recomp/lower.rs
index c462be09..d893da9b 100644
--- a/crates/xcl/src/gpu/recomp/lower.rs
+++ b/crates/xcl/src/gpu/recomp/lower.rs
@@ -1257,6 +1257,8 @@ fn lower_with<I: Ir>(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I, s
     if n == 0 {
         return Err("empty program".into());
     }
+    let loops = super::loop_ranges(insts);
+    let regions = if kernel { super::budget_regions(&loops) } else { Vec::new() };
     // IR blocks: 0 prologue, 1..=n the program's, n + 1 exit, n + 2 lane 0's scalar stores,
     // n + 3 every lane's vector stores, n + 4 the way to the exit of lanes outside EXEC at launch,
     // then for every coalesced guarded run (only the lanes with their EXEC bit enter): the run's
@@ -1401,6 +1403,12 @@ fn lower_with<I: Ir>(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I, s
     l.ssa.seal(&mut l.ir, 0);
     let budget = l.ir.int(LOOP_BUDGET);
     l.ssa.write(0, Var::Budget, budget);
+    if !regions.is_empty() {
+        let owner = l.ir.int(0);
+        let total = l.ir.int(LOOP_BUDGET * super::LOOP_BUDGETS_IN_ALL);
+        l.ssa.write(0, Var::BudgetOwner, owner);
+        l.ssa.write(0, Var::BudgetTotal, total);
+    }
     let lane = l.lane();
     for &r in &sregs {
         let a = l.ir.int(r as u32);
@@ -1550,18 +1558,38 @@ fn lower_with<I: Ir>(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I, s
         let body_end = block_body_end(insts, &block.insts);
         let mut cur = ib;
         if let Some(bc) = budget_cont[b] {
-            // cap a lane's loop iterations (matching emit.rs and dxil/kernel.rs LOOP_BUDGET)
-            let left = l.read(cur, Var::Budget);
-            let z = l.ir.int(0);
-            let exhausted = l.ir.icmp(Cmp::Eq, left, z);
+            // Charge long loops for their code size, as the other backends do.
+            let pc = insts[block.insts.start].pc;
+            let cost = l.ir.int(super::loop_cost(&loops, pc));
+            let mut left = l.read(cur, Var::Budget);
+            let mut total = None;
+            let region = super::budget_region(&regions, pc);
+            if let Some(r) = region {
+                let owner = l.read(cur, Var::BudgetOwner);
+                let r_value = l.ir.int(r);
+                let changed = l.ir.icmp(Cmp::Ne, owner, r_value);
+                let fresh = l.ir.int(LOOP_BUDGET * super::LOOP_BUDGETS_PER_REGION);
+                left = l.ir.select(changed, fresh, left);
+                total = Some(l.read(cur, Var::BudgetTotal));
+            }
+            let mut exhausted = l.ir.icmp(Cmp::Ult, left, cost);
+            if let Some(t) = total {
+                let depleted = l.ir.icmp(Cmp::Ult, t, cost);
+                exhausted = l.ir.bin(Bin::Or, exhausted, depleted);
+            }
             l.ir.br_if(exhausted, exit, bc);
             done[cur] = true;
             l.ir.at(bc);
             l.ssa.seal(&mut l.ir, bc);
             sealed[bc] = true;
-            let one = l.ir.int(1);
-            let next = l.ir.bin(Bin::Sub, left, one);
+            let next = l.ir.bin(Bin::Sub, left, cost);
             l.ssa.write(bc, Var::Budget, next);
+            if let (Some(r), Some(t)) = (region, total) {
+                let owner = l.ir.int(r);
+                l.ssa.write(bc, Var::BudgetOwner, owner);
+                let remaining = l.ir.bin(Bin::Sub, t, cost);
+                l.ssa.write(bc, Var::BudgetTotal, remaining);
+            }
             cur = bc;
         }
         let mut split = splits[b].iter().peekable();
@@ -1867,7 +1895,7 @@ impl<I: Ir> Lower<'_, I> {
                     let s = self.ir.icmp(Cmp::Ne, v, z);
                     self.write_scc(b, s);
                 }
-                Var::S(_) | Var::M(_) | Var::Budget => {}
+                Var::S(_) | Var::M(_) | Var::Budget | Var::BudgetOwner | Var::BudgetTotal => {}
             }
         }
         if name.starts_with("V_") && !sw.is_empty() {
@@ -4657,6 +4685,64 @@ pub(crate) mod tests {
         assert_eq!(v[0][1], LOOP_BUDGET);
     }
 
+    #[test]
+    fn long_loop_spends_its_code_size_per_header_visit() {
+        let mut lines: Vec<I> = vec![
+            ("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 128)]),
+            ("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 255), ("LITERAL", 1)]),
+        ];
+        for _ in 0..30 {
+            lines.push(("S_ADD_U32", "ENC_SOP2", &[("SDST", 4), ("SSRC0", 4), ("SSRC1", 255), ("LITERAL", 1)]));
+        }
+        lines.push(("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 0), ("SSRC1", 128)]));
+        lines.push(("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFC0)]));
+        lines.push(ENDPGM);
+        let (mut s, mut v) = state(32);
+        s[126] = 1;
+        v[0][1] = 0;
+        let (s, _) = run(&lines, false, &s, &v);
+        assert_eq!(s[0], LOOP_BUDGET / 2, "a 256-byte loop spends two units per visit");
+    }
+
+    const SPIN_THEN_LOOP: &[I] = &[
+        ("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 128)]),
+        ("S_MOV_B32", "ENC_SOP1", &[("SDST", 1), ("SSRC0", 128)]),
+        ("S_MOV_B32", "ENC_SOP1", &[("SDST", 3), ("SSRC0", 255), ("LITERAL", LOOP_BUDGET as u64)]),
+        ("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 129)]),
+        ("S_CMP_LT_U32", "ENC_SOPC", &[("SSRC0", 0), ("SSRC1", 3)]),
+        ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFD)]),
+        ("S_ADD_U32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 1), ("SSRC1", 129)]),
+        ("S_CMP_LT_U32", "ENC_SOPC", &[("SSRC0", 1), ("SSRC1", 131)]),
+        ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFD)]),
+        ENDPGM,
+    ];
+
+    #[test]
+    fn kernel_loop_after_a_full_spin_keeps_its_own_budget() {
+        let (mut s, v) = state(32);
+        s[126] = 1;
+        let (s, _) = run(SPIN_THEN_LOOP, false, &s, &v);
+        assert_eq!(s[0], LOOP_BUDGET);
+        assert_eq!(s[1], 3, "the second loop must run after the first spends one budget");
+    }
+
+    #[test]
+    fn kernel_loop_after_a_full_spin_runs_on_the_gpu() {
+        use super::super::{lower_dxil, runner};
+        if !gpu_waves() {
+            runner::skip_test("no GPU with 32-lane waves");
+            return;
+        }
+        let (dxil, _) = lower_dxil::kernel(&decode(SPIN_THEN_LOOP), false).unwrap();
+        let (mut s, _) = state(32);
+        s[126] = 1;
+        let mut input = runner::KernelState::default();
+        input.sgpr.copy_from_slice(&s);
+        let gpu = runner::run(&dxil, &input, &[]).unwrap();
+        assert_eq!(gpu.sgpr[0], LOOP_BUDGET);
+        assert_eq!(gpu.sgpr[1], 3);
+    }
+
     #[test]
     fn nested_loops_share_loop_budget_across_headers() {
         // Outer infinite loop (header at inst 2, counted in s0) wrapping an inner loop that
diff --git a/crates/xcl/src/gpu/recomp/lower_dxil.rs b/crates/xcl/src/gpu/recomp/lower_dxil.rs
index 5865c59e..1af0ddb6 100644
--- a/crates/xcl/src/gpu/recomp/lower_dxil.rs
+++ b/crates/xcl/src/gpu/recomp/lower_dxil.rs
@@ -100,7 +100,7 @@ impl DxilIr {
     fn ty(&mut self, var: Var) -> crate::gpu::dxil::module::Ty {
         match var {
             Var::M(_) | Var::Scc => self.lw.s.m.i1(),
-            Var::S(_) | Var::V(_) | Var::Budget => self.lw.s.m.i32(),
+            Var::S(_) | Var::V(_) | Var::Budget | Var::BudgetOwner | Var::BudgetTotal => self.lw.s.m.i32(),
         }
     }
 
@@ -267,7 +267,7 @@ impl Ir for DxilIr {
             Var::V(n) => VAR_VGPR + n as u32,
             Var::Scc => VAR_SCC,
             Var::M(_) => unreachable!("a lane-bit view is not a register"),
-            Var::Budget => unreachable!("loop budget is not a register"),
+            Var::Budget | Var::BudgetOwner | Var::BudgetTotal => unreachable!("loop budget is not a register"),
         };
         for &(v, x) in inputs {
             self.lw.wr(var(v), x);
diff --git a/crates/xcl/src/gpu/recomp/ssa.rs b/crates/xcl/src/gpu/recomp/ssa.rs
index 940b1553..be4c94d7 100644
--- a/crates/xcl/src/gpu/recomp/ssa.rs
+++ b/crates/xcl/src/gpu/recomp/ssa.rs
@@ -26,6 +26,8 @@ pub enum Var {
     Scc,
     /// remaining loop-header iterations for this lane (`i32`)
     Budget,
+    BudgetOwner,
+    BudgetTotal,
 }
 
 /// What the construction needs from the module builder.

AI use: Codex (GPT-6.2 Sol) traced the current lowering paths, wrote and ran the local regressions and candidate, and drafted this reply.

@throny

throny commented Nov 28, 2026

Copy link
Copy Markdown
Collaborator

merge-check claim
head: 9a6d83c

@throny

throny commented Nov 28, 2026

Copy link
Copy Markdown
Collaborator

merge-check
base: 7c795f5 (amd-dev)
head: 9a6d83c
merge: clean
build: cargo build --workspace -> ok
tests: cargo test --workspace --no-fail-fast -- --test-threads=4 on amd-dev 7c795f5 + this PR -> 1806 passed, 16 failed, 48 ignored (21 SKIPPED lines) on an RTX 4080. The base (see #2605, which changes nothing) has 1802 passed, 17 failed in the run beside it; all 16 failures here are among the base's 17, so nothing new fails on this card (the one that differs, the_mirror_sync_copies_only_the_pages_the_title_wrote, is not in this PR's area).
review: the mechanism is sound and better than before (the per-lane form had no cap at all, so a runaway loop hung the GPU), but the parity points from the thread are unanswered and the description claims a parity that current amd-dev does not have. (1) Every loop-header visit costs 1; the direct-DXIL path weighs a visit by the loop's cost, so a long loop can run up to 256 times more iterations here before the cap, and that cap exists because of driver timeouts. (2) There is one counter per lane for the whole program, set once at entry; a lane that passes 65,536 header visits in total leaves through the exit, and in compute everything after the loop, stores included, is skipped without a log line (the direct path does the same; the HLSL path breaks out of the loop and runs on). Not tested by anyone: a lane leaving early before a barrier in divergent control flow, and ballots once a lane has left.
performance: one compare and one subtraction per loop-header visit. It changes per-lane sources only: only per-lane cache entries are re-translated.
verdict: not yet: answer the two parity reviews (loop cost; what the description says), then I re-check.
hardware / tool and model: RTX 4080 16 GB (621.40), i9-12900K, Windows 11 26300, Rust 1.100.0, debug. Claude Code; merge, build and suite run by Claude Fable 5.2, diff review by Claude Opus 5.5 (every hunk read; nothing run on the GPU beyond the suite).

@Saksukella
Saksukella force-pushed the fix/per-lane-loop-budget branch from 9a6d83c to a68bf23 Compare November 28, 2026 23:54
@Saksukella
Saksukella changed the base branch from amd-dev to main November 28, 2026 23:54
@Saksukella

Copy link
Copy Markdown
Contributor Author

Rebased cleanly onto main (227d2cb388) and retargeted this PR's base branch to main.

Summary of updates addressing review feedback:

  • Weighted loop_cost deduction: Each loop-header visit now deducts loop_cost (1 per 128 bytes of innermost loop code, clamped to 1..=256) and checks Cmp::Ult against cost, so long loops cannot run up to 256x more iterations before hitting LOOP_BUDGET.
  • Kernel-only per-region budgets (BudgetOwner / BudgetTotal): Kernel programs track per-region budgets (LOOP_BUDGET * 2 per region, LOOP_BUDGET * 4 total). Compute and graphics shaders intentionally stay on a single program-wide Var::Budget per lane (avoiding the AMD compiler crash in amd-dev f84a949: AMD driver crashes (amdxc64.dll+0xd2a411) compiling the title's native DXIL compute shader ca7beffb8d3a8f28 (RX 6750 XT) #2874).
  • Exit semantics: Exhausted lanes branch directly from the loop header to exit, matching direct-DXIL semantics.
  • Regression tests & verification (RX 9070 XT):
    • cargo test --lib -p xcl recomp::lower -- --test-threads=4: 64 passed, 0 failed (including long_loop_spends_its_code_size_per_header_visit and kernel_loop_after_a_full_spin_keeps_its_own_budget).
    • cargo check --workspace: passed.
    • 60s smoke.ps1 (TitleID 7952987A, head a68bf237e5d0): 1687 frames shown (main 227d2cb388: 1674), 0 device removals, 0 crashes, 18139 MB peak commit.

@github-actions github-actions Bot added area:recompiler RDNA2 decoder, HLSL/direct-DXIL recompiler, wave64/wave32 gpu:amd Code is specific to AMD / RDNA / wave64 GPUs (scope tag; see needs:amd-test) labels Nov 28, 2026
@throny

throny commented Nov 29, 2026

Copy link
Copy Markdown
Collaborator

merge-check claim
head: a68bf23

Re-check of the head rebased onto main.

@github-actions github-actions Bot added the needs-pr-check Failing the PR description check (CONTRIBUTING.md) label Nov 29, 2026
@throny

throny commented Nov 29, 2026

Copy link
Copy Markdown
Collaborator

merge-check
base: fa20459
head: a68bf23
merge: clean
build: cargo build --workspace -> ok
tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 2612 passed, 0 failed, 49 ignored (27 SKIPPED lines). Base alone at fa20459: 2608 passed, 0 failed, 49 ignored.
review: re-check of the head rewritten onto main, and first a correction on my side. My check of 2026-11-28 asked for parity with the direct-DXIL path's loop-cost weighting. That was true of amd-dev at 7c795f5, the PR's target that day (the weighting came with 00fe5ae). The PR now targets main, and neither main (fa20459) nor today's amd-dev (8942a5b, rewritten since) has any loop-cost weighting: the direct-DXIL, compact and HLSL paths all charge 1 per loop-header visit. So the weighting and the per-region budgets this head adds to answer that point make the per-lane form stricter than every other path on main: a loop of 32 KiB or more would end after 256 header visits where the others allow 65,536, which can cut a legitimate long loop short. The comment "matching the other lowering backends" is therefore not true on main. Sorry for the detour; the earlier 1-per-visit form is the one that matches main. Still open from the thread: exit_stale ignores the header-to-exit edges; a lane leaving before a barrier in divergent flow and ballots after a lane has left are untested; a lane over budget still skips the rest silently (as the direct path does), without a log line. Process: the smoke run does not reach this code without XCL_PER_LANE=1, and AI use names no tool or model.
performance: one compare and one subtraction per loop-header visit. Per-lane sources only: only per-lane cache entries are re-translated.
verdict: not yet: on main, go back to 1 per header visit (or show why per-lane needs the weighting when no other path has it), and name the model under AI use.
hardware / tool and model: RTX 4080 16 GB (621.40), i9-12900K, Windows 11 26300, Rust 1.100.0, debug. Claude Code; merge, build and suite run by Claude Fable 5.2, diff review by Claude Opus 5.5 (every hunk read; nothing run on the GPU beyond the suite).

@futurepro62

Copy link
Copy Markdown

NVIDIA and AMD full-suite run of head a68bf237, on its own base 227d2cb and merged with current main 53e85fb1, to go with the reports above by throny, since none of them covers AMD. Nothing here fails because of this PR. On the Radeon the lib test binary stops partway on this base and on main alike (#3488), so the AMD runs are partial. The bare-head runs come first.

Tested

Not tested

AI use

  • Claude Code (Claude Opus 5.5) ran the tests and wrote this report. I checked it before posting.

@Foniass

Foniass commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

Triage (#1607) – head a68bf23

No other PR adds a loop budget to the per-lane SSA lowering (recomp/lower.rs). #2793 adds per-region budgets to the plain, compact and kernel DXIL backends but does not touch this file. This PR defines its own private copies of LOOP_BUDGETS_PER_REGION, LOOP_BUDGETS_IN_ALL, budget_regions and budget_region, which #2793 puts in recomp/mod.rs; if both land, one copy should go. The comment says loop_cost (1 unit per 128 bytes of the innermost loop) matches the other backends, but on main the plain and compact backends spend 1 per header visit and nothing on main defines loop_cost. So a long loop gets fewer iterations under XCL_PER_LANE=1 than under the default backend. Either drop the cost or change the comment. The branch conflicts with main.
Recommendation: keep open.

AI review: Claude Code (Claude Opus 5.5), diffs read only, not built or run; not checked by a human.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:recompiler RDNA2 decoder, HLSL/direct-DXIL recompiler, wave64/wave32 gpu:amd Code is specific to AMD / RDNA / wave64 GPUs (scope tag; see needs:amd-test) needs-pr-check Failing the PR description check (CONTRIBUTING.md)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants