Skip to content

Recompiler: direct DXIL lowers a repeating compute program's blocks once - #2034

Merged
raylitebull merged 1 commit into
xcl-dev:mainfrom
Royalflamejlh:shader/direct-compact
Nov 25, 2026
Merged

raylitebull merged 1 commit into
xcl-dev:mainfrom
Royalflamejlh:shader/direct-compact

Conversation

@Royalflamejlh

@Royalflamejlh Royalflamejlh commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

The two largest compute programs of a retail pack go from 4.3 MB of direct DXIL each to 0.48 and 0.44 MB, and vkd3d-proton's dxil-spirv converts each in 0.1 s where it took 5 to 6 s. They are one code many times (14,377 and 14,346 blocks of 617 and 590 kinds), and the direct translator lowered every copy. A program like that now takes a compact form: each distinct block is lowered once, inside one loop that reads the block's class and its two successors from constant tables and switches to the class. It is the direct counterpart of the HLSL compact form (#1315, #1316, #1448), with its thresholds and no DXC run. Part of #1269.

Head e591a8c. Every number below was taken on it unless it says otherwise. The GPU tests agree on one card, and both regression blocks are below.

What is in it

  • crates/xcl/src/gpu/dxil/compact.rs (new): plan sorts the reachable blocks into classes, wanted is the rule, emit builds the loop. Two blocks are of one class when the lowering would emit the same for both: the same instruction words, the same kind of end, both loop heads or neither, and the same of what it looks up by address (static samplers, whether a mask written there is read whole in the split form, s_getpc_b64). A loop head's class begins with the plain form's loop-budget check. A table entry is a class and an index into a second table of successor offsets, packed end to end.
  • The rule: at least 20,000 instructions (branches not counted), under 30 % of them in the distinct blocks, and tables of at most 8,192 words together. These are Recompiler: route compute programs through a compact backend (XCL_COMPACT_CS) #1316's thresholds and its table limit, which it took from an RTX 5070 Ti accepting a table of 12,288 words and refusing one of 15,360.
  • crates/xcl/src/gpu/dxil/lower.rs, Init: in the compact form a register is a local variable across the loop; a class loads what it reads where it begins and stores what it wrote where it ends. As SSA values every register was a phi with an edge from every class, and three of the six programs below came out larger than their plain form.
  • crates/xcl/src/gpu/dxil/kernel.rs: the block walk is skipped for a planned program, with one [SHADER] log line; the plan is made only for a program of 20,000 instructions or more, or when forced; XCL_DIRECT_COMPACT=1 forces the form on every compute program (and the kernel tests), 0 turns it off; no TRANSLATOR_VERSION bump: since Recompiler: direct DXIL cache entries change when its sources do #1947 the cache identity follows the gpu/dxil sources.
  • crates/xcl/src/gpu/recomp/pso.rs: the forced modes get their own translation-cache identity.
  • crates/xcl/src/gpu/dxil/compact_tests.rs (new), five tests: 64 more copies of a block cost under a twentieth of what they cost in the plain form (it fails if blocks are not shared); the rule picks a program of 2,500 copies and leaves one of 2,000; two copies of a compare are two classes when the mask is read whole after one of them only (it fails with the key I had first); gpu_compact_form_runs_as_the_plain_form runs 40 copies of four blocks (scalar and vector adds, a compare into VCC, a saved EXEC mask, a region skipped on s_cbranch_execz) and a loop in both forms, and compares the registers with each other and with the values worked out by hand. gpu_compact_form_spends_the_loop_budget_as_the_plain_form runs a loop that would leave on its 65,537th entry: both forms must stop at 65,536.

Tested

  • Linux through Wine, CPU only: Ryzen 9 9950X3D, 62 GB RAM, Fedora 44, Wine 11.21 Staging, DXC 1.9.2609.5 (its validator only), rustc 1.98.0, release, x86_64-pc-windows-gnu. main is aa9ab8a. The change is e591a8c.
  • The six largest compute programs of a retail pack, XCL_DIRECT_DXIL=1 xcl shaders <folder> --precompile --only cs --split 1 from an empty cache, 1 translation each:
console instructions blocks kinds DXIL on main with the change forced (XCL_DIRECT_COMPACT=1)
88,863 14,377 617 4,323,600 B 478,888 B (−88.9 %) the same
88,445 14,346 590 4,294,852 B 442,720 B (−89.7 %) the same
76,699 13,890 2,643 3,888,520 B not taken: its tables 1,266,172 B (−67.4 %)
46,741 3,748 2,699 2,510,068 B not taken 2,430,776 B (−3.2 %)
45,398 3,696 2,471 2,435,024 B not taken 2,123,728 B (−12.8 %)
44,430 3,683 2,465 2,375,716 B not taken 2,066,704 B (−13.0 %)
sum 19,827,780 B 12,130,936 B (−38.8 %) 8,808,988 B (−55.6 %)

A program not taken is byte for byte main's (SHA-256), and so are all six with XCL_DIRECT_COMPACT=0.

  • The whole pack, xcl shaders <pack> --direct --validate --only cs --split 1 --max-bytes 0 --sample 100000 (26,698 programs, 2,689 of them compute): with the form forced on every compute program all 26,698 translated and DXC's validator accepted every one (148 s, 8 threads); with the rule deciding, 2 of the 2,689 took the form and all were accepted (155 s). While this branch was written the forced sweep ran six times on five commits: five passed, and one, on an earlier commit, stopped part-way with a page fault that Wine reported without a backtrace. I have not found the cause.
  • A 23,000-record slice of the pack (843 compute programs compiled, 836 cached translations): 233,704,716 B on main and 226,007,872 B with the change; 2 translations differ in size, by the 7,696,844 B of the table.
  • dxil-spirv as vkd3d-proton ships it (its command-line tool, unpatched, 8 GB limit, 1 conversion each); spirv-val --target-env vulkan1.3 accepts the two new ones:
console instructions main: time, SPIR-V with the change: time, SPIR-V
88,863 5.6 s, 16,133,792 B 0.1 s, 1,578,900 B
88,445 5.4 s, 16,037,840 B 0.1 s, 1,462,404 B
76,699 496.3 s, 20,705,832 B not taken; forced: 0.6 s, 4,470,064 B
  • Native Windows, RTX 5070 Ti 16 GB (driver 621.24), Ryzen 7 9800X3D, 32 GB RAM, Windows 11 Pro 26300, rustc 1.99.1, debug, 1 run each:
    • cargo test --workspace -- compact_tests: 5 passed, the two card tests among them.
    • cargo test --workspace -- gpu_ --test-threads=4 with XCL_DIRECT_DXIL=1: 113 passed, 6 failed, 1 ignored. With XCL_DIRECT_COMPACT=1 added, 99 kernels took the compact form, 88 of them a single block and 10 of 2 to 5 blocks: 113 passed, 6 failed, 1 ignored, the same six with the same messages (four fuzz_validate_and_gpu_* at CreateComputePipelineState with 0x8007000E on the same seeds, gpu_fmt_encode_int_sat_and_f16_rtz, gpu_image_get_resinfo_1d_array). 2 SKIPPED lines in both runs (no native wave64). So that run shows the loop and the local variables on a card, and little of the sharing; the card test above is what shows that.
  • cargo test --workspace --release --target x86_64-pc-windows-gnu --no-fail-fast -- --test-threads=8 under Wine, no card: 1,082 passed, 5 failed, 46 ignored; main: 1,077 passed, 5 failed, 46 ignored. The same five fail on both: disk_free_space_ex_reports_pls_quota, directed_reference_basics, gpu_depth_buffer_created_for_unordered_access_is_placed, stale_blob_cannot_bypass_the_offline_pipeline_cap, test_title_runs_and_game_folder_is_untouched. SKIPPED lines: 279 (277 on main), no GPU or a missing wave size.
  • The direct translator's own tests under Wine with XCL_DIRECT_DXIL=1 XCL_DIRECT_COMPACT=1, so every kernel they translate takes the compact form and DXC's validator: 113 passed, 1 failed (directed_reference_basics, which translates nothing and fails on main too), 3 ignored.
  • Beside the open pull requests on the same path, measured before the rebase (this change at 7edb1ac on main 80f4819, where the two programs were 471,764 and 436,512 B), each merged locally:

Regression run

scripts/smoke.ps1, unchanged, 60 s on the RTX 5070 Ti PC above, 1 run each. smoke.ps1 sets no XCL_DIRECT_DXIL, so neither run reaches this code.

main:

xcl-smoke v1
commit: aa9ab8a3e7b738ec48899e37805f6a7d2d22da53
gpu: NVIDIA GeForce RTX 5070 Ti
title: 5330474d
seconds: 60
exit: 0x0
frames shown: 1599 (PresentX 1599)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 16057 MB

PR:

xcl-smoke v1
commit: e591a8c8971206c854b0d6c5f8f21362182ed12d
gpu: NVIDIA GeForce RTX 5070 Ti
title: 5330474d
seconds: 60
exit: 0x0
frames shown: 1649 (PresentX 1649)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 15445 MB

Not tested

  • The two programs themselves on a card: driver compile time, and what the loop costs at run time. The form trades run time for size: four table reads and a switch per block, and registers through local variables. One 300 s title run of an earlier head (0e4e10e) with XCL_DIRECT_DXIL=1 on the same PC (release, A from 32 s) did not get to them: it reached the world start as main does (first #101 at 84.9 s, last present 88.0 s, 1,820 frames, exit 0, no device removal), and then one thread built 300 to 400 KB programs in the driver at 4.7 to 7.7 s each; neither of the two was asked for by 300 s. In DXIL instructions the first went from 605,253 to 65,038 and from 31,464 blocks to 2,089 on that head (dxc -dumpbin).
  • Why six card tests fail through the direct translator on that PC with and without this change; main was not run there.
  • Whether a driver takes the tables in this form. They are 7,639 + 158 words and 7,623 + 154 words for the two programs taken (counted on an earlier head). The 76,699-instruction program's branches go to 6,530 different pairs of offsets (counted before the rebase), so its tables are about 24,000 words and the rule leaves it out; by my estimate about 11,300 with the taken target in the entry itself, which is the next slice once a card says what it takes.
  • AMD, Intel, a native wave64 run, XCL_HEAP_WINDOWS=1, XCL_PER_LANE=1 (the per-lane form is tried first and is not changed).
  • With Recompiler: route compute programs through a compact backend (XCL_COMPACT_CS) #1316 in: its routing sends these programs to the HLSL compact form before the direct translator sees them. Which form should win is not decided here.

AI use

  • Claude Code (Claude Fable 5.2) found the repetition, wrote the change and the tests, ran the translations, the conversions and the suite, and wrote this description. A second Claude session read the diff and found the gap the third test covers. The loop-budget rule and the plan that was made and thrown away were found by the two reviewers below.

@WebIdentity1

WebIdentity1 commented Nov 25, 2026 •

Copy link
Copy Markdown

Revised author head verified: e591a8c

Tested exact e591a8c8971206c854b0d6c5f8f21362182ed12d on RTX 3090 split wave64 and AMD iGPU native wave64. Each run: 6 passed / 0 failed / 0 ignored / 0 skipped.

This head addresses both findings: compact::large prevents unused planning, and loop headers are separate classes with the budget charged before their bodies. That is the author's implementation, distinct from the PortBridge header-bit candidate and my SSA follow-up below; those historical patch results should not be treated as results for this head.

Tested — Windows 10 Home 19045, Ryzen 7800X3D, RTX 3090 driver591.74 (32.0.15.9174) and AMD Radeon(TM) Graphics iGPU 32.0.21030.2001; Rust/Cargo 1.98.1 MSVC, DXC/DXIL 1.8.2502.11, debug. XCL_ADAPTER=3090 / AMD in separate processes; XCL_DIRECT_COMPACT unset. Command each:

cargo test --locked -p xcl --lib -- gpu::dxil::compact_tests --test-threads=1 --show-output

The five committed tests passed unchanged, including the strengthened masked-execution GPU comparison, the new scalar loop-budget test, generated-DXIL size controls in all three wave modes, mask class separation, and automatic selection of 2,500 copies versus rejection of 2,000. The sixth is the same local boundary probe included below, added alone to this head: limits65,535/65,536 exit normally with marker42; limit65,537 stops at65,536 with marker0. Plain/compact match the CPU counts and all64 vector increments at every boundary on both GPUs. This is ten GPU dispatches per adapter across the three GPU tests, six from the boundary probe.

Only that 30-line test-only boundary probe was added; runtime and the author's tests are unchanged. All316 source hashes matched before/after and the local snapshot; XCL recompiled. Earlier worktrees and reports are preserved.

Not tested — full workspace, real shader table sizes/selection, production compute-entry ABI, retail smoke/gameplay, or refreshed translation time/memory/GPU throughput. The earlier cost measurements below are for 0e4e10e and its separate overlays, not e591a8c. The GPU diagnostic requires hardware and is not proposed unchanged for GPU-less CI. Required full-suite/retail gates remain separate.

AI use — Codex (GPT-6) checked the author's adoption, reused the independent boundary probe, ran and verified this revised head on both GPUs, and prepared the update.


Loop-budget follow-up: GPU reproduction and a small repair to the proposed candidate

@akimfomin, confirmed your loop-budget finding and candidate on native Windows / RTX 3090. Credit for the diagnosis and header-bit solution is yours; this is validation plus a small SSA-exit correction to that patch, not a competing implementation.

Tested — exact PR head 0e4e10e53b2f0f7d9a8bf2b09f1f0d137bde2d62, then your unchanged guarded-compact-offsets.patch from PortBridge 533510ca622bbe3950129070061cebd518ed3120, then that candidate plus the six-addition/three-deletion follow-up below. Same local GPU/selection probe in all three snapshots; no earlier eager-plan-gate overlay included. Windows 10 Home 19045, Ryzen 7800X3D, RTX 3090 driver 591.74 (32.0.15.9174), Rust/Cargo 1.98.1 MSVC, DXC/DXIL 1.8.2502.11, debug, split wave64. All 316 source hashes matched before/after each run and each local snapshot; XCL recompiled each time.

XCL_ADAPTER=3090, XCL_DIRECT_COMPACT unset:
cargo test --locked -p xcl --lib -- gpu::dxil::compact --test-threads=1 --show-output

Snapshot Passed / failed / ignored Explicit skips
PR head + probe 5 / 1 / 0 0
PortBridge candidate + probe 4 / 4 / 0 0
Candidate + SSA follow-up + probe 8 / 0 / 0 0

The finite GPU loop increments a scalar counter and every lane's v1, then writes marker42 on natural exit. Plain and compact agree at limits65,535 and65,536. At65,537, the head's plain form gives counter65,536/marker0, while compact gives65,537/marker42 and all64 lanes have one extra increment. The final candidate gives65,536/marker0 and correct v1 on all64 lanes. Six boundary dispatches ran per complete probe, with CPU checks for both forms.

The initial candidate builds but fails DXIL validation, before compact GPU dispatch: Instruction does not dominate all uses!. Four emitting tests fail, including existing tests. done is registered with two SSA predecessors, so epilogue register reads traverse the dispatch loop even though compact registers live in memory slots. The fix makes done an independent SSA root like the class/latch blocks, emitting its two incoming branches without SSA edges while retaining the dispatch/continuation edges. The epilogue then loads current slots in done. This preserves the original candidate's header-bit budgeting and table encoding.

The final eight tests include your signed-offset and shared-class-header controls, existing generated-DXIL size/validation controls in wave32/native64/split64, existing GPU plain/compact comparison, and the new boundary/selection probes. For our synthetic repeated(3000) and repeated(5000), table sizes remain947/1572words, four step keys and five classes in all snapshots; automatic selection remainsfalse/true respectively.

Not tested — your two real shader workloads/table counts, full workspace, retail smoke/gameplay, AMD GPU execution, acyclic backwards-layout GPU exhaustion, production compute-entry ABI, or performance/memory cost of the new guard. The GPU loop deliberately forces compact on a small fixture to isolate the budget. The selection check uses public synthetic programs, not the unavailable real shaders. Local GPU diagnostic fails without GPU prerequisites and is not proposed unchanged for GPU-less CI. The existing retail/full-suite gates remain separate.

AI use — Codex (GPT-6) wrote the independent GPU/selection probes, diagnosed and corrected the candidate's SSA exit, ran/verified the comparisons, and drafted this report. Original loop-budget diagnosis and candidate remain credited to akimfomin / PortBridge; its local GPLv2 license and exact patch are preserved with the evidence.

SSA follow-up applied after the PortBridge candidate
--- a/crates/xcl/src/gpu/dxil/compact.rs
+++ b/crates/xcl/src/gpu/dxil/compact.rs
@@ -182,9 +182,11 @@
     let left = lw.s.m.load(budget, 4);
     let none = lw.cmpc(Pred::Eq, left, 0);
     let spent = lw.and(header, none);
-    let done = lw.block(Some(2));
+    // Registers live in slots: the common exit is an independent SSA root, like each class.
+    let done = lw.block(Some(0));
     let dispatch = lw.block(Some(1));
-    lw.cond_br(spent, done, dispatch);
+    lw.s.m.cond_br(spent, done, dispatch);
+    lw.edge(head, dispatch);
     lw.s.m.set_block(dispatch);
     let one = lw.c(1);
     let less = lw.sub(left, one);
@@ -221,7 +223,8 @@
     let next = lw.s.m.load(to, 4);
     let past = lw.cmpc(Pred::UGe, next, n as u32);
     let cont = lw.block(Some(1));
-    lw.cond_br(past, done, cont);
+    lw.s.m.cond_br(past, done, cont);
+    lw.edge(latch, cont);
     lw.s.m.set_block(cont);
     lw.s.m.store(at, next, 4);
     lw.br(head);
Independent local GPU and selection probe against the original PR head
diff --git a/crates/xcl/src/gpu/dxil/compact_tests.rs b/crates/xcl/src/gpu/dxil/compact_tests.rs
index 2fd26c9..8ec19cf 100644
--- a/crates/xcl/src/gpu/dxil/compact_tests.rs
+++ b/crates/xcl/src/gpu/dxil/compact_tests.rs
@@ -95,3 +95,48 @@ fn a_mask_read_whole_after_one_copy_only_splits_the_class() {
     assert_eq!(p.order.len(), 4);
     assert_ne!(p.class[0], p.class[2]);
 }
+
+#[test]
+fn gpu_compact_loop_budget_matches_plain_at_boundary() {
+    // Local diagnostic: a real GPU is required; do not silently skip this comparison.
+    println!("LOOP adapter={} native64={:?}", runner::adapter().unwrap(), runner::wave64_supported());
+    let o = KernelOptions { wave64: true, split: runner::split_wave64(), mem_windows: 1, sampler_base: 0 };
+    let i = |n: &str, e: &str, f: &[(&str, u64)]| encode(n, e, f, None).unwrap();
+    let mut code = i("S_BRANCH", "ENC_SOPP", &[("SIMM16", 0)]);
+    code.extend(i("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 129)]));
+    code.extend(i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 129), ("VSRC1", 1)]));
+    code.extend(i("S_CMP_LT_U32", "ENC_SOPC", &[("SSRC0", 0), ("SSRC1", 2)]));
+    code.extend(i("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFC)]));
+    code.extend(i("S_MOV_B32", "ENC_SOP1", &[("SDST", 3), ("SSRC0", 170)]));
+    code.extend(i("S_ENDPGM", "ENC_SOPP", &[]));
+    let mut bad = Vec::new();
+    for limit in [65_535u32, 65_536, 65_537] {
+        let mut st = KernelState::default();
+        st.sgpr[2] = limit;
+        for compact in [false, true] {
+            let k = translate_full_as(&code, o, compact).unwrap();
+            let out = runner::run_with_statics(&k.dxil, &st, &[], &[], &[], &k.static_samplers).unwrap();
+            let count = limit.min(65_536);
+            let marker = if limit <= 65_536 { 42 } else { 0 };
+            let wrong_lanes = (0..KERNEL_LANES).filter(|&lane| out.vgpr[lane][1] != count).count();
+            println!("LOOP limit={limit} compact={compact} count={} marker={} wrong_lanes={wrong_lanes}", out.sgpr[0], out.sgpr[3]);
+            if out.sgpr[0] != count || out.sgpr[3] != marker || wrong_lanes != 0 { bad.push((limit, compact)); }
+        }
+    }
+    assert!(bad.is_empty(), "loop-budget mismatches: {bad:?}");
+}
+
+#[test]
+fn compact_loop_guard_preserves_synthetic_selection() {
+    let o = KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 };
+    for copies in [3000, 5000] {
+        let code = repeated(copies);
+        let cfg = super::cfg::Cfg::build(&code).unwrap();
+        let leaders = cfg.blocks.iter().filter_map(|b| b.insts.first().map(|&i| cfg.insts[i].pc)).collect();
+        let lw = super::lower::Lw::new(&cfg.insts, &leaders, o, &super::kernel::Entry::Kernel);
+        let p = super::compact::plan(&cfg, &lw).unwrap();
+        let wanted = super::compact::wanted(&cfg, &p);
+        println!("LOOP_PLAN copies={copies} blocks={} classes={} steps={} words={} wanted={wanted}", p.order.len(), p.rep.len(), p.steps.len(), p.words());
+        assert_eq!(wanted, copies == 5000);
+    }
+}

Follow-up: avoid building a plan that cannot be used

The source review found a small avoidable cost in the same exact head 0e4e10e53b2f0f7d9a8bf2b09f1f0d137bde2d62: translate_on_this_thread always calls compact::plan for compute/kernel entries before filtering it, even when XCL_DIRECT_COMPACT=0 or automatic mode has fewer than 20,000 reachable non-branch instructions. That allocates/classifies keys and builds successor tables only to discard them.

Candidate below: 7 runtime additions / 2 deletions in two files. Share the existing 20,000 threshold with an early eligibility check; disabled mode never plans, forced-on mode still plans small programs, and automatic mode counts the same reachable cfg.rpo instructions that Plan::order uses. The full repetition/table-size decision remains in wanted().

Verified on the same Windows/RTX 3090 environment as the original report below, debug, exact head + identical local probe versus head + candidate + probe. Four fresh processes per snapshot, auto/disabled/disabled/auto. Automatic uses 3,000 copies (below threshold); disabled uses 5,000 copies. Each of the eight processes passed 1/0/0, zero skips, all 64 lane/scalar CPU checks. Generated DXIL SHA256 and full output-state hashes are unchanged between head and candidate for each fixture.

Mode Translation ms: head Translation ms: candidate DXIL bytes (both)
Automatic,3,000 copies 417.590 /420.476 386.210 /380.038 178,140
Disabled,5,000 copies 697.009 /698.332 635.282 /677.048 300,848

Pre-GPU peak process commit: automatic head 30,601,216/30,490,624B versus candidate 30,564,352/30,474,240B (essentially unchanged); disabled 49,885,184/49,635,328B versus 48,881,664/48,930,816B. This is a small ordered experiment, not a claimed pack-wide speedup or significant general memory reduction.

The four existing compact tests also passed on candidate (4/0/0, zero skips), with the override unset: block sharing in all three wave modes, natural 5,000/3,000-copy threshold behavior, GPU plain/compact equality, and whole-mask class separation. Both 316-file snapshots matched SHA256 before/after and XCL recompiled. The two-file runtime patch and local diagnostic are included below; no source commit/push or competing PR.

Probe command remains cargo test --locked -p xcl --lib -- gpu_large_repeated_program_auto_output_and_cost --test-threads=1 --show-output, with XCL_ADAPTER=3090, XCL_DIRECT_COMPACT unset/0, XCL_COST_COPIES=3000/5000, and XCL_COST_DXIL_OUT set to a distinct local output file per process. Existing controls were run as these four filters in one test command:

the_compact_form_lowers_a_repeated_block_once
a_large_program_that_repeats_itself_takes_the_compact_form
gpu_compact_form_runs_as_the_plain_form
a_mask_read_whole_after_one_copy_only_splits_the_class

Not tested — full workspace, release, retail shaders/smoke, AMD, production compute-entry output or driver cold-compilation cost for this candidate. Translation timings and process memory use the same definitions as the earlier report. Local diagnostic requires GPU; it is not proposed as an unguarded CI test.

AI use — Codex (GPT-6) found the eager planning, wrote the candidate/probe adaptation, ran native comparisons and controls, verified source/DXIL/output hashes, and prepared this update.

Runtime candidate, 7 additions / 2 deletions
diff --git a/crates/xcl/src/gpu/dxil/compact.rs b/crates/xcl/src/gpu/dxil/compact.rs
index a439789..406c12b 100644
--- a/crates/xcl/src/gpu/dxil/compact.rs
+++ b/crates/xcl/src/gpu/dxil/compact.rs
@@ -22,6 +22,9 @@ pub struct Plan {
 /// Most 32-bit words of tables a program may need to take the form by itself.
 const MAX_TABLE_WORDS: usize = 8192;
 
+/// Below this size automatic selection cannot use a plan.
+pub const MIN_INSTRUCTIONS: usize = 20_000;
+
 impl Plan {
     /// Bits of a table entry: the class, and the index of the pair of offsets.
     fn widths(&self) -> (u32, u32) {
@@ -40,7 +43,7 @@ pub fn wanted(cfg: &Cfg, p: &Plan) -> bool {
     let insts = |n: usize| cfg.blocks[p.order[n]].insts.len();
     let all: usize = (0..p.order.len()).map(insts).sum();
     let once: usize = p.rep.iter().map(|&n| insts(n)).sum();
-    all >= 20_000 && once * 10 < all * 3 && p.words() <= MAX_TABLE_WORDS
+    all >= MIN_INSTRUCTIONS && once * 10 < all * 3 && p.words() <= MAX_TABLE_WORDS
 }
 
 pub const END: u32 = u32::MAX;
diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs
index 83c5e77..976656f 100644
--- a/crates/xcl/src/gpu/dxil/kernel.rs
+++ b/crates/xcl/src/gpu/dxil/kernel.rs
@@ -236,7 +236,9 @@ fn translate_on_this_thread(code: &[u8], o: KernelOptions, entry: Entry, compact
         }
     }
 
-    let plan = if compute || kernel { super::compact::plan(&cfg, &lw) } else { None };
+    let may_compact = (compute || kernel) && compact != Some(false)
+        && (compact == Some(true) || cfg.rpo.iter().map(|&b| cfg.blocks[b].insts.len()).sum::<usize>() >= super::compact::MIN_INSTRUCTIONS);
+    let plan = if may_compact { super::compact::plan(&cfg, &lw) } else { None };
     let plan = plan.filter(|p| compact.unwrap_or_else(|| super::compact::wanted(&cfg, p)));
     if let Some(p) = &plan {
         crate::xlog_info!("[SHADER] direct DXIL compact form: {} blocks of {} kinds", p.order.len(), p.rep.len());
Updated local diagnostic, 36 added lines
diff --git a/crates/xcl/src/gpu/dxil/compact_tests.rs b/crates/xcl/src/gpu/dxil/compact_tests.rs
index 2fd26c9..3f374c7 100644
--- a/crates/xcl/src/gpu/dxil/compact_tests.rs
+++ b/crates/xcl/src/gpu/dxil/compact_tests.rs
@@ -95,3 +95,39 @@ fn a_mask_read_whole_after_one_copy_only_splits_the_class() {
     assert_eq!(p.order.len(), 4);
     assert_ne!(p.class[0], p.class[2]);
 }
+
+#[test]
+fn gpu_large_repeated_program_auto_output_and_cost() {
+    use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS_EX};
+    let memory = || unsafe {
+        let mut c: PROCESS_MEMORY_COUNTERS_EX = std::mem::zeroed();
+        c.cb = std::mem::size_of::<PROCESS_MEMORY_COUNTERS_EX>() as u32;
+        assert_ne!(K32GetProcessMemoryInfo(windows_sys::Win32::System::Threading::GetCurrentProcess(), &mut c as *mut _ as *mut _, c.cb), 0);
+        (c.PrivateUsage, c.PeakPagefileUsage, c.WorkingSetSize, c.PeakWorkingSetSize)
+    };
+    assert_ne!(compact_mode(), Some(true), "compare automatic selection with disabled compact form");
+    let copies = std::env::var("XCL_COST_COPIES").unwrap().parse::<usize>().unwrap();
+    let code = repeated(copies);
+    let mut st = KernelState::default();
+    (st.sgpr[1], st.sgpr[2]) = (3, 12);
+    for lane in 0..KERNEL_LANES { st.vgpr[lane][0] = lane as u32; }
+    // Explicit split-wave64, with no GPU initialization before translation memory sampling.
+    let o = KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 };
+    println!("LARGE mode={:?} copies={copies} input_bytes={} memory_before={:?}", compact_mode(), code.len(), memory());
+    let start = std::time::Instant::now();
+    let k = translate_full(&code, o).expect("large program translation");
+    let ms = start.elapsed().as_secs_f64() * 1000.0;
+    println!("LARGE translation_ms={ms:.3} dxil_bytes={} memory_after={:?}", k.dxil.len(), memory());
+    std::fs::write(std::env::var("XCL_COST_DXIL_OUT").unwrap(), &k.dxil).unwrap();
+    println!("LARGE adapter={}", runner::adapter().expect("GPU required for this local cost probe"));
+    let out = runner::run_with_statics(&k.dxil, &st, &[], &[], &[], &k.static_samplers).expect("large program GPU run");
+    assert_eq!(&out.sgpr[..5], &[3 * copies as u32, 3, 12, 1, 0]);
+    assert_eq!(out.scc, 0);
+    for lane in 0..KERNEL_LANES {
+        assert_eq!(&out.vgpr[lane][..3], &[lane as u32, copies as u32 * lane as u32, 5 * lane as u32], "lane {lane}");
+    }
+    // Compare the entire output state across isolated processes as well as the CPU oracle.
+    let hash = out.sgpr.iter().chain(out.vgpr.iter().flatten()).chain(std::iter::once(&out.scc))
+        .fold(0xcbf29ce484222325u64, |h, &v| (h ^ v as u64).wrapping_mul(0x100000001b3));
+    println!("LARGE output_hash={hash:016x} all_64_lanes_correct=true");
+}

Original automatic-path comparison (unchanged head, earlier diagnostic)

Independent RTX 3090 automatic-path output and translation-cost check on exact head 0e4e10e53b2f0f7d9a8bf2b09f1f0d137bde2d62 + the local diagnostic below. No runtime changes.

The existing GPU test uses 40 repetitions with a forced form. This probe instead uses repeated(5000) (20,004 non-branch instructions, 100,024 input bytes) and calls translate_full, with XCL_DIRECT_COMPACT unset versus 0. Both automatic runs logged 10,003 blocks of 5 kinds, confirming that wanted() selected the compact form. This is the test-kernel ABI, not a title shader's compute ABI.

Tested — Windows 10 Home 19045, Ryzen 7 7800X3D, RTX 3090 driver 591.74, Rust 1.98.1 MSVC, DXC/DXIL 1.8.2502.11, debug, explicit split-wave64. Four separate test processes in order auto/disabled/disabled/auto:

XCL_ADAPTER=3090
XCL_DIRECT_COMPACT unset (automatic) or 0 (disabled)
cargo test --locked -p xcl --lib -- gpu_large_repeated_program_auto_output_and_cost --test-threads=1 --show-output

Each process: 1 passed / 0 failed / 0 ignored, zero skips. All 64 lanes matched the CPU register oracle, scalar loop/branch outputs matched, and the whole output-state hash was identical (9db32686f1edca7b) in all four runs.

Form DXIL bytes Translation ms, runs 1 / 2 Pre-GPU peak process commit bytes, runs 1 / 2
Disabled 300,848 730.468 /683.160 49,938,432 /49,770,496
Automatic 5,948 247.927 /245.590 12,607,488 /12,750,848

The timer wraps translate_full (including its worker/validation), before GPU initialization or PSO creation. Memory is PROCESS_MEMORY_COUNTERS_EX.PeakPagefileUsage sampled immediately after translation: the entire process, including fixture, retained DXIL and validator, not translator-exclusive allocations. Fresh processes keep the two forms' high-water marks separate. All 316 source hashes matched before/after and match the worktree; XCL recompiled.

Not tested — Retail shaders or gameplay, real compute-entry ABI output, AMD, full workspace, release builds, GPU throughput, or cold driver PSO compilation. Driver-cache disabling is unavailable on this machine; no PSO timing is claimed. This highly repetitive synthetic program supports automatic-path correctness and local translation cost at the threshold; it does not establish the magnitude of benefits in game shaders. The local diagnostic deliberately requires a GPU and is offered for reproduction, not as an unguarded CI test. Required retail smoke gates remain separate.

AI use — Codex (GPT-6) inspected the implementation, added and ran the local probe, checked logs/source hashes and CPU/output-state comparisons, and prepared this report.

Local reproduction probe: one test-only file, 35 added lines
diff --git a/crates/xcl/src/gpu/dxil/compact_tests.rs b/crates/xcl/src/gpu/dxil/compact_tests.rs
index 2fd26c9..7572a6e 100644
--- a/crates/xcl/src/gpu/dxil/compact_tests.rs
+++ b/crates/xcl/src/gpu/dxil/compact_tests.rs
@@ -95,3 +95,38 @@ fn a_mask_read_whole_after_one_copy_only_splits_the_class() {
     assert_eq!(p.order.len(), 4);
     assert_ne!(p.class[0], p.class[2]);
 }
+
+#[test]
+fn gpu_large_repeated_program_auto_output_and_cost() {
+    use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS_EX};
+    let memory = || unsafe {
+        let mut c: PROCESS_MEMORY_COUNTERS_EX = std::mem::zeroed();
+        c.cb = std::mem::size_of::<PROCESS_MEMORY_COUNTERS_EX>() as u32;
+        assert_ne!(K32GetProcessMemoryInfo(windows_sys::Win32::System::Threading::GetCurrentProcess(), &mut c as *mut _ as *mut _, c.cb), 0);
+        (c.PrivateUsage, c.PeakPagefileUsage, c.WorkingSetSize, c.PeakWorkingSetSize)
+    };
+    assert_ne!(compact_mode(), Some(true), "compare automatic selection with disabled compact form");
+    let copies = 5000;
+    let code = repeated(copies);
+    let mut st = KernelState::default();
+    (st.sgpr[1], st.sgpr[2]) = (3, 12);
+    for lane in 0..KERNEL_LANES { st.vgpr[lane][0] = lane as u32; }
+    // Explicit split-wave64, with no GPU initialization before translation memory sampling.
+    let o = KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 };
+    println!("LARGE mode={:?} copies={copies} input_bytes={} memory_before={:?}", compact_mode(), code.len(), memory());
+    let start = std::time::Instant::now();
+    let k = translate_full(&code, o).expect("large program translation");
+    let ms = start.elapsed().as_secs_f64() * 1000.0;
+    println!("LARGE translation_ms={ms:.3} dxil_bytes={} memory_after={:?}", k.dxil.len(), memory());
+    println!("LARGE adapter={}", runner::adapter().expect("GPU required for this local cost probe"));
+    let out = runner::run_with_statics(&k.dxil, &st, &[], &[], &[], &k.static_samplers).expect("large program GPU run");
+    assert_eq!(&out.sgpr[..5], &[3 * copies as u32, 3, 12, 1, 0]);
+    assert_eq!(out.scc, 0);
+    for lane in 0..KERNEL_LANES {
+        assert_eq!(&out.vgpr[lane][..3], &[lane as u32, copies as u32 * lane as u32, 5 * lane as u32], "lane {lane}");
+    }
+    // Compare the entire output state across isolated processes as well as the CPU oracle.
+    let hash = out.sgpr.iter().chain(out.vgpr.iter().flatten()).chain(std::iter::once(&out.scc))
+        .fold(0xcbf29ce484222325u64, |h, &v| (h ^ v as u64).wrapping_mul(0x100000001b3));
+    println!("LARGE output_hash={hash:016x} all_64_lanes_correct=true");
+}

@akimfomin

akimfomin commented Nov 25, 2026 •

Copy link
Copy Markdown

Royalflamejlh, PortBridge reviewed compact and plain loop limits at 0e4e10e53b2f. The plain form charges before each CFG loop-header body. The compact form charges after an edge to the same or a lower address. That misses the first entry into a genuine header and can also charge an acyclic edge.

A standalone CPU model of those exact predicates shows the difference at the stock limit. In a finite counter loop whose natural exit is at 65,537 iterations, the plain form stops with counter 65,536 and no exit marker. The compact rule reaches 65,537 and the marker. Controls at 65,535 and 65,536 agree. A smaller acyclic backwards-layout case and a shared-class header case cover the other boundaries.

There is a pinned patch that charges before dispatch and puts the header flag in the low bit of the packed taken offset. It preserves two words per step. It can split a step pair used by both header kinds, so the exact table sizes of your two automatically selected workloads still need a check. The CPU model, patch application and two focused Rust tests passed. The initial source patch then failed internal DXIL validation on a new end-to-end fixture because of the exit SSA join. Please use the linked patch as historical evidence. WebIdentity1’s independent check and repair reproduces the original difference on an RTX 3090 and verifies the repaired candidate. Reproduction and patch

AI assistance: OpenAI Codex (GPT-6 family) assisted with source analysis, the CPU model and the proposed patch.

@Royalflamejlh
Royalflamejlh force-pushed the shader/direct-compact branch 2 times, most recently from fd0534e to 87023c3 Compare November 25, 2026 01:52
The two largest compute programs of a retail pack are about 14,000
blocks of about 600 kinds: one code many times, each copy lowered again,
4.3 MB of DXIL each. A program of at least 20,000 instructions with
under 30 % of them in its distinct blocks (the HLSL compact form's
thresholds) now takes a compact form: each distinct block once, inside
one loop that reads the block's class and its two successors from
constant tables and switches to the class. The two come out under
0.5 MB each.

Two blocks are of one class when the lowering would emit the same for
both: the same instruction words, the same kind of end, and the same of
what it looks up by address (static samplers, whether a mask written
there is read whole in the split form, s_getpc_b64).

Registers are local variables across the loop; as SSA values each was a
phi with an edge from every class, and the form came out larger than the
plain one for programs with little repetition.

The tables are constant data the driver has to take, and xcl-dev#1316 measured
an RTX 5070 Ti accepting a table of 12,288 words and refusing one of
15,360, so a program takes the form by itself only when its two tables
are at most 8,192 words together (the HLSL compact form's limit). The
third largest program repeats itself too, but its branches go to
thousands of different offsets and its tables would be about 24,000
words: it keeps the plain form.

XCL_DIRECT_COMPACT=1 forces the form on every compute program and 0
turns it off.

Part of xcl-dev#1269.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@Royalflamejlh
Royalflamejlh marked this pull request as ready for review November 25, 2026 02:01
@raylitebull
raylitebull merged commit aaa0936 into xcl-dev:main Nov 25, 2026
6 of 8 checks passed
@Royalflamejlh

Copy link
Copy Markdown
Contributor Author

Both taken, in e591a8c. Thank you both.

@akimfomin: you are right, the two forms spent the loop budget by different rules. A loop head no longer shares a class with a block that is not one (head or not is part of a class's key) and its code begins with the plain form's check, so the budget is spent on every entry into a head, the first included, and nowhere else. It needs no table bit. gpu_compact_form_spends_the_loop_budget_as_the_plain_form is your case, a loop that would leave on its 65,537th entry: on an RTX 5070 Ti both forms stop at 65,536 without the marker (1 run). I did not run that test on the old head; that it was red there is from reading the code, your model, and @WebIdentity1's RTX 3090 run of a loop like it on 0e4e10e (compact form: 65,537 and the marker).

@WebIdentity1: the plan is now made only when it can be used. compact::large (the 20,000-instruction threshold, which wanted uses too) is asked first, and XCL_DIRECT_COMPACT=0 makes none. It is one line in translate_on_this_thread; I did not time it. Your run of e591a8c on the AMD iGPU is the first native wave64 run this change has had.

Both findings were made on 0e4e10e. The head moved three times after that: fd0534e (a longer program in the card test), 87023c3 (the two changes above) and e591a8c (the TRANSLATOR_VERSION bump taken out: #1947 made it unnecessary). The description's numbers are from e591a8c now, except the ones it marks as taken on an earlier head.

AI use: Claude Code (Claude Fable 5.2) wrote the changes and this comment.

Posted without review by a person: the account owner was away and reads replies later.

@gsucristo gsucristo left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Reviewed the diff — very clean, self-contained Direct DXIL compact form (+431 lines) with strong measured wins (4.3 MB -> 0.44-0.48 MB DXIL, 5-6 s -> 0.1 s in dxil-spirv) and solid unit + GPU tests. Using local stack slots (Init::slot) across the loop instead of wide SSA phis and the shl(shlc(hi, 1), 31 - sh) trick to avoid 32-bit shift UB are both really clean.

One minor hardening suggestion:

  • crates/xcl/src/gpu/dxil/compact.rs (plan, lines 77-88): static_samplers, whole_live, and S_GETPC_B64 are pushed onto key without a tag/length delimiter. Adding a short discriminant or length word before each optional section would prevent any theoretical key collision between blocks with different combinations of those optional properties.

Also worth noting that this cleanly supersedes #1316's routing of XCL_DIRECT_DXIL=1 compute shaders back through HLSL+DXC. Looks ready to merge once any remaining checks are green.

(AI disclosure: review drafted with Antigravity — exact model name not provided to the agent — and checked by the reviewer before posting.)

@Royalflamejlh

Copy link
Copy Markdown
Contributor Author

@gsucristo: thank you. Of the three, only the static sampler can be present at one instruction and absent at another with the same words. It is set by moves earlier in the same block, which are in the key, so no two blocks collide today, but a presence flag keeps it that way: three lines in plan. The pull request had merged two minutes before your review, so the flag is not in it. With the flag the six largest compute programs of the pack come out byte for byte as before, both when the rule picks the form and when it is forced (SHA-256, 12 files, split wave64), so it goes in with the next change to compact.rs and not as a pull request of its own.

AI use: Claude Code (Claude Fable 5.2) wrote the line, ran the comparison and wrote this comment.

Posted without review by a person: the account owner was away and reads replies later.

Royalflamejlh added a commit to Royalflamejlh/xcl that referenced this pull request Nov 25, 2026
The third-largest compute program of a retail pack repeats itself as the
two largest do (13,890 blocks of 2,643 kinds), but its branches go to
6,530 different pairs of offsets. As an index into a table of pairs its
tables were about 24,000 words, over the limit, and it kept the plain
form: 3.9 MB of DXIL.

In it, as in the other large programs, a block's second successor is
always the next block. For such a program a table entry now holds the
taken successor itself when that makes the tables smaller, about 11,300
words here. The limit goes from 8,192 to 12,288 words, the size xcl-dev#1316
measured an RTX 5070 Ti accepting, and the program takes the form.

A class's key also marks whether an instruction has a static sampler
(from the review of xcl-dev#2034): the one section an instruction can have and
another with the same words lack.

Part of xcl-dev#1269.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Royalflamejlh added a commit to Royalflamejlh/xcl that referenced this pull request Nov 25, 2026
Hardening from the review of xcl-dev#2034. Whether an instruction has a static
sampler follows from the moves before it in its block, which are in the
key, so no two blocks share a key today; the flag makes the key's
sections delimit themselves. The six largest compute programs of a
retail pack come out byte for byte as before.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@Royalflamejlh

Copy link
Copy Markdown
Contributor Author

Driver time, which the description left open: on an RTX 5070 Ti the driver built the compact form of the two programs in 5.4 s and 6.0 s and their plain direct form in 370 s and 980 s, all in one run on a machine that was not quiet.

Setup: native Windows 11, RTX 5070 Ti 16 GB (driver 621.24), Ryzen 7 9800X3D, 32 GB RAM, debug build of e591a8c plus one local test that calls CreateComputePipelineState on a record's direct DXIL with XCL's root signature, compact then plain, twice each, in the split wave64 form; 1 run. All eight calls returned; the test itself had not ended when the job's 30-minute wait ran out, so it counts as neither passed nor failed. The driver's shader cache could not be turned off there (no Developer Mode), so the first call is the cold one and the second comes from the cache.

console instructions form DXIL first call second call
88,863 compact 478,888 B 5.39 s 0.005 s
88,863 plain 4,323,600 B 370.5 s 0.217 s
88,445 compact 442,720 B 6.02 s 0.003 s
88,445 plain 4,294,852 B 979.7 s 0.246 s
  • A second run of the title, left over from an earlier job, was still going on that machine for the test's first 15 minutes, with three large compute programs of its own in the driver at a time. That covers both compact rows, the first program's plain row and the first part of the second's; that row then ran at least 7 of its 16 minutes alone and was still the slowest, so I cannot say how much of the plain rows' time the other run cost. On a quiet machine @Kalmarv measured 94.6 s for the first program's direct form (3.98 MB, main 62265d3, driver 610.74; [OFFICIAL] Looking for PRs with shaders optimization #1269).
  • The driver took this form's tables as they are (7,639 + 158 words for the first program, counted on an earlier head).

Not tested: a quiet machine, the driver's cache off, what the loop costs at run time, and a title run that waits on these two programs.

AI use: Claude Code (Claude Fable 5.2) wrote the test, ran it and wrote this comment.

Posted without review by a person: the account owner was away and reads replies later.

@ettehn

ettehn commented Nov 25, 2026

Copy link
Copy Markdown

Cache-disabled PSO comparison on an RTX 5070 Ti Laptop GPU

A complement to the driver timings above. On native Windows, driver 621.24, 12 GB, DXC 1.8.2502.11, I measured a synthetic compute-entry shader with repeated control flow and a final UAV store. Base was 568e7db7729c8fa6c8f0f4b32d798faaf11462bb, with a local CLI-only change that makes --measure-pso --direct use the direct compute translator and keeps the same cold PSO timer and root-signature path.

Repetitions HLSL + DXC Plain direct DXIL Forced compact direct DXIL
40 196 ms 54 ms 36 ms
96 546 ms 94 ms 37 ms
160 1,026 ms 143 ms 36 ms
256 1,987 ms 234 ms 36 ms

These are medians of three CreateComputePipelineState calls per cell, each in a fresh process with both implicit caches disabled. I rotated backend order. Each call used --repeat 1 --split 1 --windows 4, XCL_HEAP_WINDOWS=1 and XCL_PER_LANE=0. The direct runs set XCL_DIRECT_COMPACT=0 or 1 and the forced runs all logged that compact form was used. All 36 calls completed successfully. At 256 repetitions (synthetic record hash 1dbe07f8835617a7), plain and compact DXIL were 47,200 and 4,508 bytes. Their PSO ranges were 222–239 ms and 35–37 ms.

The samples force compact mode below the automatic threshold. This measures pipeline creation on the production compute-entry ABI. Retail shaders, automatic routing and dispatch throughput were outside this run.

AI use — OpenAI Codex (GPT-6) assisted with the measurement option, fixtures, runs and report.

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.

6 participants