From a89f714b66f0e1853cde77fd48023f6b3c3bf475 Mon Sep 17 00:00:00 2001 From: ivall Date: Sat, 21 Nov 2026 12:02:26 +0100 Subject: [PATCH] Translator: faster DXC - skip-flag structuring, branch-free helpers, DXC worker pool - forward jumps out of nested code (loop breaks, jumps past an exec join, s_endpgm before the end) become skip flags; loops entered in the middle are rotated; if/else only when no pending target lands inside; nesting capped at 24. Retail pack: programs needing the pc dispatcher 9.4% (was ~42% in the sample) - format decoding, mul_legacy, ballot, conversions and bit-field helpers without loops, ?: or short-circuit operators - DXC runs on a pool of worker threads with 64 MB stacks (its passes overflowed 2 MB on big pixel shaders; game threads may have small stacks) - same 241-shader sample back to back: DXC total 228 s -> 152 s, max 9.3 s -> 5.9 s; the whole pack still translates completely --- HANDOFF.md | 21 ++ crates/xcl/src/gpu/recomp/dxc.rs | 44 ++++ crates/xcl/src/gpu/recomp/emit.rs | 70 ++--- crates/xcl/src/gpu/recomp/mod.rs | 399 ++++++++++++++++++++++------- crates/xcl/src/gpu/recomp/tests.rs | 97 +++++++ 5 files changed, 508 insertions(+), 123 deletions(-) diff --git a/HANDOFF.md b/HANDOFF.md index 6f7885c..6572a62 100644 --- a/HANDOFF.md +++ b/HANDOFF.md @@ -546,6 +546,27 @@ Nic otwartego. cache (`dxc::compile_cached`, klucz = HLSL) albo wcześniejsze zapełnienie cache z `shaders.rpf`. - MS (NGG) i GS/ES kompilować jako **cs_6_6** (działają jako compute + przejściowy mesh shader; profil ms/gs → „WaveSize only allowed on compute”). +- **Optymalizacja czasu DXC (sesja 5, druga runda)** – porównanie tej samej próbki (co 100. rekord, 241 wariantów) kod + stary / nowy jeden po drugim: suma **228 → 152 s (−33%)**, mediana 0,29 → 0,22 s, p90 2,76 → 2,29 s, max 9,3 → 5,9 s; + najwolniejszy PS (PS_PedTextured_Eight_Fire, 8 600 instrukcji) ~6,5 → 3,4 s, MS (MSNC_VS_PedTransformSkinAlpha) 3,8 → 1,7 s. + Pomiary czasów między różnymi chwilami skaczą o ±20% (stan maszyny) – porównywać tylko obok siebie. + - `dxc.exe -ftime-report` (SDK) pokazał: przy -O0 DXC i tak liczy ~4 s (to nie optymalizator), przy -O3 najdroższy + był **Jump Threading** (25%) na pętli `pc`, a w shaderach MS **rozwijanie pętli** z funkcji pomocniczych. + - **Struktura:** skoki naprzód wychodzące z bloku (break z pętli, skok za złączenie exec, s_endpgm w środku – discard + w PS) jako **flagi `xcl_skip_`**; pętle wchodzone w środku (`s_branch` tuż przed głową, też przez `s_nop`) w formie + obróconej; if/else tylko gdy żaden oczekujący cel nie wpada do środka (inaczej zwykły if / flaga); analiza i emisja + idą tą samą funkcją `item_at`, analiza z pamięcią (`memo`). Głębokość if/pętli ≤ 24 (`MAX_NEST`; łańcuchy discard + w PS dawały setki zagnieżdżeń). Shadery z blokami `pc`: 102 → 23 / 241 (pozostały wzorzec: wyjście z pętli + umieszczone w jej środku i skok wstecz do niego). + - **Pomocniki HLSL bez pętli i rozgałęzień** (HLSL 2021 zamienia skalarne `?:`, `&&`, `||`, `if` na skoki): + `fmt_comp`/`fmt_bytes`/`bits_at`/`uf_small` (dekodowanie formatów buforów – w MS po 140 razy), `mul_legacy` + (1 200 razy w PS), `ballot`, `first_lane`, `cvt_u32/i32`, `bfe_*`, `sbfe_*`, `ffbh_i`, `alignbit`, `img_cls`, + `dst_sel`, `f16_rtz`. Uwaga: `unorm`/`snorm` to słowa kluczowe HLSL (nie nazywać tak zmiennych). + - **DXC na własnych wątkach** (`dxc.rs`: pula, wątek na rdzeń, stos 64 MB, własny kompilator): przebiegi LLVM DXC + rekurencyjnie przepełniały 2 MB stosu na dużych PS (PS_TexturedLit_8); wątki gry mogą mieć mały stos. + - Nieudane (bez zysku, w szumie): liczenie `lanebit(exec)` raz przy zmianie exec, usunięcie komentarzy z HLSL. + - Pomocniki: `retail_shader_cost` (`XCL_NAMES=a,b`, `XCL_DXC_ARGS`, `XCL_HLSL_OUT`, limit 8 GB) i w przeglądzie + `XCL_SURVEY_TRACE`, podział czasu strukturalne / z `pc`, 10 najwolniejszych, najmniejsze niestrukturalne. - Gra **nie używa FSPX/ACCC**: wszystkie 23 869 shaderów w `shaders.rpf` to XDAT/XBCH/FSSM – FSPX to tylko własne pipeline'y FSR4 (dla gry bez znaczenia, ewentualnie test). diff --git a/crates/xcl/src/gpu/recomp/dxc.rs b/crates/xcl/src/gpu/recomp/dxc.rs index 9881092..e6e1161 100644 --- a/crates/xcl/src/gpu/recomp/dxc.rs +++ b/crates/xcl/src/gpu/recomp/dxc.rs @@ -96,8 +96,52 @@ fn compiler() -> Result { }) } +/// Stack of the thread DXC runs on: its LLVM passes recurse along long dependency chains of +/// big translated programs (2 MB overflowed on a 7 000-instruction retail PS); the caller may +/// be a game thread with a small stack. Reserved, committed only as used. +const DXC_STACK: usize = 64 << 20; + +struct Job { + src: String, + entry: String, + profile: String, + extra: Vec, + reply: std::sync::mpsc::Sender, String>>, +} + +/// DXC workers (one per core, each with its own compiler and a `DXC_STACK` stack), started +/// on first use; callers wait for their job. +fn pool() -> &'static std::sync::Mutex> { + static POOL: OnceLock>> = OnceLock::new(); + POOL.get_or_init(|| { + let (tx, rx) = std::sync::mpsc::channel::(); + let rx = std::sync::Arc::new(std::sync::Mutex::new(rx)); + for k in 0..std::thread::available_parallelism().map_or(4, |n| n.get()) { + let rx = rx.clone(); + let _ = std::thread::Builder::new().name(format!("xcl-dxc-{k}")).stack_size(DXC_STACK).spawn(move || loop { + let job = match rx.lock().unwrap().recv() { + Ok(j) => j, + Err(_) => return, + }; + let extra: Vec<&str> = job.extra.iter().map(|s| s.as_str()).collect(); + let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| compile_here(&job.src, &job.entry, &job.profile, &extra))) + .unwrap_or_else(|_| Err("DXC: panika w wątku kompilacji".into())); + let _ = job.reply.send(r); + }); + } + std::sync::Mutex::new(tx) + }) +} + /// Compile HLSL to signed DXIL. `profile` e.g. "cs_6_6"; `extra` are dxc arguments. pub fn compile(src: &str, entry: &str, profile: &str, extra: &[&str]) -> Result, String> { + let (reply, rx) = std::sync::mpsc::channel(); + let job = Job { src: src.into(), entry: entry.into(), profile: profile.into(), extra: extra.iter().map(|s| s.to_string()).collect(), reply }; + pool().lock().unwrap().send(job).map_err(|_| "DXC: brak wątków kompilacji".to_string())?; + rx.recv().map_err(|_| "DXC: wątek kompilacji zakończył się".to_string())? +} + +fn compile_here(src: &str, entry: &str, profile: &str, extra: &[&str]) -> Result, String> { let c = compiler()?; let mut args: Vec> = ["-E", entry, "-T", profile, "-HV", "2021"].iter().map(|a| crate::util::wide(a)).collect(); // DXC's optimiser was superlinear on translated programs full of short-circuit `?:` / diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index b48bbb3..5efa385 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -3295,37 +3295,37 @@ uint4 ld_raw(uint a) { if (s == 0u) return uint4(w0, w1, w2, w3); return uint4((w0 >> s) | (w1 << (32u - s)), (w1 >> s) | (w2 << (32u - s)), (w2 >> s) | (w3 << (32u - s)), (w3 >> s) | (w4 << (32u - s))); } +// format helpers: no loops, no branches (inlined at every buffer access; `?:` and `if` +// on scalars become control flow in HLSL 2021, which DXC is slow to clean up) uint bits_at(uint4 r, uint off, uint w) { uint i = off >> 5; uint s = off & 31u; - uint lo = r[i]; uint hi = (i < 3u) ? r[i + 1u] : 0u; - uint v = (s == 0u) ? lo : ((lo >> s) | (hi << (32u - s))); - return w >= 32u ? v : (v & ((1u << w) - 1u)); + uint lo = r[i]; uint hi = select(i < 3u, r[min(i + 1u, 3u)], 0u); + uint v = select(s == 0u, lo, (lo >> s) | (hi << ((32u - s) & 31u))); + return select(w >= 32u, v, v & ((1u << (w & 31u)) - 1u)); } float uf_small(uint v, uint mb) { uint e = v >> mb; uint m = v & ((1u << mb) - 1u); float fm = (float)m / (float)(1u << mb); - if (e == 31u) return m != 0u ? asfloat(0x7FC00000u) : asfloat(0x7F800000u); - if (e == 0u) return fm * exp2(-14.0f); - return exp2((float)e - 15.0f) * (1.0f + fm); + float special = select(m != 0u, asfloat(0x7FC00000u), asfloat(0x7F800000u)); + return select(e == 31u, special, select(e == 0u, fm * exp2(-14.0f), exp2((float)e - 15.0f) * (1.0f + fm))); } -uint fmt_bytes(uint info) { uint n = 0u; [unroll] for (uint k = 0u; k < 4u; k++) n += (info >> (8u + 6u * k)) & 63u; return n / 8u; } +uint fmt_bytes(uint info) { return (((info >> 8) & 63u) + ((info >> 14) & 63u) + ((info >> 20) & 63u) + ((info >> 26) & 63u)) / 8u; } uint fmt_comp(uint4 r, uint info, uint c) { uint n = info & 7u; uint ty = (info >> 3) & 7u; - bool isint = ty == 4u || ty == 5u; - if (c >= n) return c == 3u ? (isint ? 1u : 0x3F800000u) : 0u; - uint off = 0u; [unroll] for (uint k = 0u; k < 3u; k++) if (k < c) off += (info >> (8u + 6u * k)) & 63u; - uint w = (info >> (8u + 6u * c)) & 63u; + bool isint = or(ty == 4u, ty == 5u); + uint off = select(c > 0u, (info >> 8) & 63u, 0u) + select(c > 1u, (info >> 14) & 63u, 0u) + select(c > 2u, (info >> 20) & 63u, 0u); + uint w = (info >> ((8u + 6u * c) & 31u)) & 63u; uint v = bits_at(r, off, w); - int sv = w >= 32u ? (int)v : (((int)(v << (32u - w))) >> (32u - w)); - float maxu = w >= 32u ? 4294967295.0f : (float)((1u << w) - 1u); - float maxs = w >= 32u ? 2147483647.0f : (float)((1u << (w - 1u)) - 1u); + uint sh = (32u - w) & 31u; + int sv = select(w >= 32u, (int)v, ((int)(v << sh)) >> sh); + float maxu = select(w >= 32u, 4294967295.0f, (float)((1u << (w & 31u)) - 1u)); + float maxs = select(w >= 32u, 2147483647.0f, (float)((1u << ((w - 1u) & 31u)) - 1u)); + float fv = (float)v; float fsv = (float)sv; // exact endpoints (the hardware conversion is exact; DXC divides approximately) - if (ty == 0u) return asuint(v == 0u ? 0.0f : ((float)v >= maxu ? 1.0f : (float)v / maxu)); - if (ty == 1u) return asuint(sv == 0 ? 0.0f : ((float)sv >= maxs ? 1.0f : max((float)sv / maxs, -1.0f))); - if (ty == 2u) return asuint((float)v); - if (ty == 3u) return asuint((float)sv); - if (ty == 4u) return v; - if (ty == 5u) return (uint)sv; - return w == 32u ? v : (w == 16u ? asuint(f16tof32(v)) : asuint(uf_small(v, w == 11u ? 6u : 5u))); + uint f_un = asuint(select(v == 0u, 0.0f, select(fv >= maxu, 1.0f, fv / maxu))); + uint f_sn = asuint(select(sv == 0, 0.0f, select(fsv >= maxs, 1.0f, max(fsv / maxs, -1.0f)))); + uint flt = select(w == 32u, v, select(w == 16u, asuint(f16tof32(v)), asuint(uf_small(v, select(w == 11u, 6u, 5u))))); + uint res = select(ty == 0u, f_un, select(ty == 1u, f_sn, select(ty == 2u, asuint(fv), select(ty == 3u, asuint(fsv), select(ty == 4u, v, select(ty == 5u, (uint)sv, flt)))))); + return select(c >= n, select(c == 3u, select(isint, 1u, 0x3F800000u), 0u), res); } // image_bvh(64)_intersect_ray: node = id (low 3 bits: type), at base + (id & ~7) * 8. // box32 (5) / box16 (4): 4 child ids + boxes → hit children (closest first when sorting), @@ -3375,7 +3375,7 @@ uint4 bvh_intersect(uint node, uint base, float tmax, float3 o, float3 d, float3 } return uint4(0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu); } -uint img_cls(uint fmt) { uint ty = fmt <= 77u ? ((FMT_INFO[fmt] >> 3) & 7u) : 6u; return ty == 4u ? 1u : (ty == 5u ? 2u : 0u); } +uint img_cls(uint fmt) { uint ty = select(fmt <= 77u, (FMT_INFO[min(fmt, 77u)] >> 3) & 7u, 6u); return select(ty == 4u, 1u, select(ty == 5u, 2u, 0u)); } void put_bits(inout uint4 r, uint off, uint w, uint v) { uint m = w >= 32u ? 0xFFFFFFFFu : ((1u << w) - 1u); v &= m; uint i = off >> 5; uint s = off & 31u; @@ -3407,7 +3407,7 @@ void st_bytes(uint a, uint4 r, uint n) { st_part(b, m << s, r.x << s); if (s != 0u && s + 8u * n > 32u) st_part(b + 4u, m >> (32u - s), r.x >> (32u - s)); } -uint dst_sel(uint4 c, uint sel, bool isint) { return sel == 0u ? 0u : (sel == 1u ? (isint ? 1u : 0x3F800000u) : c[(sel - 4u) & 3u]); } +uint dst_sel(uint4 c, uint sel, bool isint) { return select(sel == 0u, 0u, select(sel == 1u, select(isint, 1u, 0x3F800000u), c[(sel - 4u) & 3u])); } "#; const PRELUDE: &str = r#" @@ -3416,7 +3416,7 @@ static uint lane_id; static bool xcl_w32 = false; static uint xcl_half = 0u; bool lanebit(uint lo, uint hi) { return ((select(lane_id < 32u, lo, hi) >> (lane_id & 31u)) & 1u) != 0u; } -uint2 ballot(bool b) { uint4 m = WaveActiveBallot(b); return xcl_w32 ? uint2(xcl_half != 0u ? m.y : m.x, 0u) : m.xy; } +uint2 ballot(bool b) { uint4 m = WaveActiveBallot(b); return uint2(select(and(xcl_w32, xcl_half != 0u), m.y, m.x), select(xcl_w32, 0u, m.y)); } uint rla(uint v, uint l) { return WaveReadLaneAt(v, l + 32u * xcl_half); } bool lanebit_at(uint lo, uint hi, uint l) { return ((select(l < 32u, lo, hi) >> (l & 31u)) & 1u) != 0u; } uint sdwa_sel(uint x, uint sel, bool sext) { @@ -3447,26 +3447,26 @@ float3 cube_dir(float s, float t, float face) { if (f == 4u) return float3(u, -v, 1.0f); return float3(-u, -v, -1.0f); } -uint first_lane(uint lo, uint hi) { return lo != 0u ? firstbitlow(lo) : (hi != 0u ? 32u + firstbitlow(hi) : 0u); } +uint first_lane(uint lo, uint hi) { return select(lo != 0u, firstbitlow(lo), select(hi != 0u, 32u + firstbitlow(hi), 0u)); } uint lanemask_lt_lo() { return lane_id >= 32u ? 0xFFFFFFFFu : (lane_id == 0u ? 0u : (0xFFFFFFFFu >> (32u - lane_id))); } uint lanemask_lt_hi() { return lane_id <= 32u ? 0u : (0xFFFFFFFFu >> (64u - lane_id)); } uint wqm(uint m) { uint q = m | (m >> 1); q = q | (q >> 2); q &= 0x11111111u; return q * 15u; } -float mul_legacy(float a, float b) { return (a == 0.0f || b == 0.0f) ? 0.0f : a * b; } +float mul_legacy(float a, float b) { return select(or(a == 0.0f, b == 0.0f), 0.0f, a * b); } float fma_legacy(float a, float b, float c) { return (a == 0.0f || b == 0.0f) ? c : mad(a, b, c); } float mad_nf(float a, float b, float c) { precise float p = a * b; precise float r = p + c; return r; } float med3f(float a, float b, float c) { return max(min(a, b), min(max(a, b), c)); } uint med3u(uint a, uint b, uint c) { return max(min(a, b), min(max(a, b), c)); } int med3i(int a, int b, int c) { return max(min(a, b), min(max(a, b), c)); } float fract_f(float x) { return min(x - floor(x), asfloat(0x3F7FFFFFu)); } -uint cvt_u32(float f) { return (isnan(f) || f <= 0.0f) ? 0u : (f >= 4294967296.0f ? 0xFFFFFFFFu : (uint)f); } -int cvt_i32(float f) { return isnan(f) ? 0 : (f <= -2147483648.0f ? (int)0x80000000u : (f >= 2147483648.0f ? 0x7FFFFFFF : (int)f)); } +uint cvt_u32(float f) { return select(or(isnan(f), f <= 0.0f), 0u, select(f >= 4294967296.0f, 0xFFFFFFFFu, (uint)f)); } +int cvt_i32(float f) { return select(isnan(f), 0, select(f <= -2147483648.0f, (int)0x80000000u, select(f >= 2147483648.0f, 0x7FFFFFFF, (int)f))); } int i24(uint v) { return ((int)(v << 8)) >> 8; } -uint bfe_u(uint v, uint o, uint w) { o &= 31u; w &= 31u; return w == 0u ? 0u : ((v >> o) & (0xFFFFFFFFu >> (32u - w))); } -int bfe_i(uint v, uint o, uint w) { o &= 31u; w &= 31u; if (w == 0u) return 0; uint s = 32u - w; return ((int)((v >> o) << s)) >> s; } -uint sbfe_u(uint v, uint c) { uint o = c & 31u; uint w = (c >> 16) & 0x7Fu; return w == 0u ? 0u : (w >= 32u ? (v >> o) : ((v >> o) & (0xFFFFFFFFu >> (32u - w)))); } -int sbfe_i(uint v, uint c) { uint o = c & 31u; uint w = (c >> 16) & 0x7Fu; if (w == 0u) return 0; if (w >= 32u) return ((int)v) >> o; uint s = 32u - w; return ((int)((v >> o) << s)) >> s; } -uint ffbh_i(uint v) { uint x = ((int)v < 0) ? ~v : v; return x == 0u ? 0xFFFFFFFFu : 31u - firstbithigh(x); } -uint alignbit(uint s0, uint s1, uint s) { s &= 31u; return s == 0u ? s1 : ((s1 >> s) | (s0 << (32u - s))); } +uint bfe_u(uint v, uint o, uint w) { o &= 31u; w &= 31u; return select(w == 0u, 0u, (v >> o) & (0xFFFFFFFFu >> ((32u - w) & 31u))); } +int bfe_i(uint v, uint o, uint w) { o &= 31u; w &= 31u; uint s = (32u - w) & 31u; return select(w == 0u, 0, ((int)((v >> o) << s)) >> s); } +uint sbfe_u(uint v, uint c) { uint o = c & 31u; uint w = (c >> 16) & 0x7Fu; return select(w == 0u, 0u, select(w >= 32u, v >> o, (v >> o) & (0xFFFFFFFFu >> ((32u - w) & 31u)))); } +int sbfe_i(uint v, uint c) { uint o = c & 31u; uint w = (c >> 16) & 0x7Fu; uint s = (32u - w) & 31u; return select(w == 0u, 0, select(w >= 32u, ((int)v) >> o, ((int)((v >> o) << s)) >> s)); } +uint ffbh_i(uint v) { uint x = select((int)v < 0, ~v, v); return select(x == 0u, 0xFFFFFFFFu, 31u - firstbithigh(x)); } +uint alignbit(uint s0, uint s1, uint s) { s &= 31u; return select(s == 0u, s1, (s1 >> s) | (s0 << ((32u - s) & 31u))); } uint perm_b32(uint s0, uint s1, uint sel) { uint r = 0u; [unroll] for (uint i = 0u; i < 4u; i++) { @@ -3478,7 +3478,7 @@ uint perm_b32(uint s0, uint s1, uint sel) { } return r; } -uint f16_rtz(float f) { uint h = f32tof16(f) & 0xFFFFu; if (!isnan(f) && (h & 0x7FFFu) != 0u && abs(f16tof32(h)) > abs(f)) h -= 1u; return h; } +uint f16_rtz(float f) { uint h = f32tof16(f) & 0xFFFFu; return h - (uint)and(and(!isnan(f), (h & 0x7FFFu) != 0u), abs(f16tof32(h)) > abs(f)); } float frexp_mant(float x) { float e; return (isinf(x) || isnan(x)) ? x : frexp(x, e); } int frexp_exp(float x) { float e; frexp(x, e); return (isinf(x) || isnan(x)) ? 0 : (int)e; } double floor_d(double x) { double t = (double)(int64_t)x; return t > x ? t - 1.0 : t; } diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index b92d307..753b0ed 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -4,6 +4,11 @@ //! * every branch in AMD GPU code is scalar, i.e. uniform across the wave, so the program //! becomes a dispatcher loop over basic blocks (`switch (pc)`) with one `pc` per wave; //! branch-free programs are emitted as straight-line code, +//! * structured form where possible (DXC compiles it much faster): forward skips as `if`, +//! if / else, loops with the back edge at their end (also entered in the middle: rotated), +//! and any other forward jump – loop breaks, jumps past a join, s_endpgm before the end – +//! as a skip flag (`xcl_skip_`: set at the jump, the code up to the target runs +//! under `if (!flag)`, loops `break`); retail pack: 90% of the programs need no `pc`, //! * SGPRs, VCC, EXEC, M0 and SCC are ordinary variables that every lane computes alike //! (uniform); lane masks produced by vector instructions come from `WaveActiveBallot`, //! * VGPRs are per-lane variables; vector writes are masked by the lane's EXEC bit, @@ -336,6 +341,8 @@ struct Ctx<'a> { loops: &'a [(u64, u64)], /// every branch: (address of the branch, target) edges: &'a [(u64, u64)], + /// `structurable_to` results: (lo, hi, exit) → targets leaving the range + memo: std::cell::RefCell, usize), Option>>>, } /// How a block ends (from its last instruction). @@ -372,11 +379,132 @@ fn why(_at: u64, msg: &str) { } } +/// Target of an s_endpgm before the end of the program: "skip to the end". +const END: u64 = u64::MAX; +/// Deepest if / loop nesting of structured code: deeper conditional jumps become skip flags +/// (flat). Pixel shaders check for "no live lane left" after every discard and jump to one +/// shared exit – as ifs that would nest hundreds deep (the translator's recursion and DXC's +/// run out of stack). +const MAX_NEST: usize = 24; + +/// Flag of a forward jump out of nested structured code: set at the jump, every level skips +/// its following code while it is set, cleared where its target starts. +fn skip_flag(t: u64) -> String { + if t == END { + "xcl_skip_end".into() + } else { + format!("xcl_skip_{t:x}") + } +} + +/// One item of a structured level. +#[derive(Clone, Copy, Debug)] +enum Item { + /// loop [a, b) whose last block (`latch`) branches back to a; `entry`: entered by a jump + /// to this point inside (the rotated form `for (;;) { [entry, latch) latch [a, entry) }`) + Loop { a: u64, b: u64, latch: u64, entry: Option }, + /// `if (!cond) { [end, t) } [else { [t, u) }]` after the block [start, end) + If { start: u64, end: u64, t: u64, u: Option }, + /// a plain block; `raise`: the forward target it jumps to past the code that follows + /// (conditional / unconditional branch, s_endpgm before the end → END) + Block { start: u64, end: u64, raise: Option }, +} + +impl Item { + fn range(&self) -> (u64, u64) { + match *self { + Item::Loop { a, b, .. } => (a, b), + Item::If { start, t, u, .. } => (start, u.unwrap_or(t)), + Item::Block { start, end, .. } => (start, end), + } + } +} + +/// The item starting at leader `i` of a level [lo, hi) and the index after it (`exit`: the +/// jump ending an if branch over its else branch; `pending`: forward targets of earlier jumps +/// at this level – no if may swallow one, a conditional jump past it becomes a skip flag). +/// Err: a shape the structured form cannot express (backward jumps other than loop latches, +/// s_setpc …). +fn item_at(c: &Ctx, i: usize, lo: u64, hi: u64, exit: Option, nest: usize, pending: &BTreeSet) -> Result<(Item, usize), String> { + let start = c.leaders[i]; + let end = block_end(c, i); + let next = |x: u64| c.leaders.partition_point(|&l| l < x); + let inside = |a: u64, b: u64| pending.iter().any(|&p| p > a && p < b); + if let Some(&(a, b)) = c.loops.iter().find(|&&(a, b)| a == start && b <= hi && (a, b) != (lo, hi)) { + let last = next(b) - 1; + let latch = c.leaders[last]; + if !matches!(term(c, latch, b), Term::Cond(t) if t == a) { + return Err(format!("pętla {a:#x}..{b:#x}: koniec {:?}", term(c, latch, b))); + } + return Ok((Item::Loop { a, b, latch, entry: None }, next(b))); + } + let last_pc = c.insts.last().map_or(0, |d| d.pc); + let item = match term(c, start, end) { + Term::Next => Item::Block { start, end, raise: None }, + // a jump into the loop that starts right after: the rotated form (the jump itself is + // the loop entry, emitted as nothing) + Term::Jump(u) if rotated_loop(c, start, end, u, lo, hi).is_some() => Item::Block { start, end, raise: None }, + Term::Cond(t) if nest < MAX_NEST && t >= end && t <= hi && (t == hi || c.leaders.binary_search(&t).is_ok()) && !inside(start, t) => { + // if / else only when both branches are structured on their own, the if branch + // does not jump into the else branch and no earlier jump lands in it; otherwise a + // plain if (the else branch then runs under the skip flag of the jump over it) + let u = else_end(c, end, t, hi).filter(|&u| !inside(start, u) && else_ok(c, end, t, u, nest)); + return Ok((Item::If { start, end, t, u }, next(u.unwrap_or(t)))); + } + // past the level, or over a target an earlier jump waits for: a skip flag + Term::Cond(t) if t > end => Item::Block { start, end, raise: Some(t) }, + Term::Jump(u) if Some(u) == exit && end == hi => Item::Block { start, end, raise: None }, + Term::Jump(u) if u >= end => Item::Block { start, end, raise: Some(u) }, + // the last block of the program: the natural end + Term::End if end == u64::MAX || last_pc < end => Item::Block { start, end, raise: None }, + Term::End => Item::Block { start, end, raise: Some(END) }, + other => return Err(format!("blok {start:#x}..{end:#x} w {lo:#x}..{hi:#x}: {other:?}")), + }; + Ok((item, i + 1)) +} + +/// The rotated loop entered by the jump ending block `i` (see `rotated_loop`). +fn rotated_after(c: &Ctx, i: usize, lo: u64, hi: u64) -> Option { + let (start, end) = (c.leaders[i], block_end(c, i)); + let Term::Jump(u) = term(c, start, end) else { return None }; + let (a, b, latch) = rotated_loop(c, start, end, u, lo, hi)?; + Some(Item::Loop { a, b, latch, entry: Some(u) }) +} + +/// A loop [a, b) starting at `end` (the block [start, end) ends with `s_branch u` into it), +/// entered only by that jump: (a, b, latch). +fn rotated_loop(c: &Ctx, start: u64, end: u64, u: u64, lo: u64, hi: u64) -> Option<(u64, u64, u64)> { + // the loop starts right after the jump, past s_nop padding (dead code, not emitted) + let padding = |a: u64| c.insts.iter().filter(|d| d.pc >= end && d.pc < a).all(|d| d.inst.name == "S_NOP"); + let &(a, b) = c.loops.iter().find(|&&(a, b)| a >= end && u > a && u < b && b <= hi && (a, b) != (lo, hi) && padding(a))?; + if c.edges.iter().any(|&(_, dst)| dst >= end && dst < a) { + return None; + } + c.leaders.binary_search(&u).ok()?; + let last = c.leaders.partition_point(|&l| l < b) - 1; + let latch = c.leaders[last]; + if u > latch || !matches!(term(c, latch, b), Term::Cond(t) if t == a) { + return None; + } + let outside_in = c.edges.iter().any(|&(src, dst)| dst >= a && dst < b && (src < a || src >= b) && !(dst == u && src >= start && src < end)); + (!outside_in).then_some((a, b, latch)) +} + +/// `if (!c) { [end, t) } else { [t, u) }` holds: both branches structured, the if branch does +/// not jump into the else branch. +fn else_ok(c: &Ctx, end: u64, t: u64, u: u64, nest: usize) -> bool { + match structurable_to(c, end, t, Some(u), nest + 1) { + Some(r) if !r.iter().any(|&x| x >= t && x < u) => structurable_to(c, t, u, None, nest + 1).is_some(), + _ => false, + } +} + /// Can [lo, hi) be emitted as structured code (no `pc` guards)? Linear blocks, forward -/// conditional skips that nest inside the range, loops whose only way back is a branch at -/// their end, and s_endpgm only as the very last block (`top`). -fn structurable(c: &Ctx, lo: u64, hi: u64, top: bool) -> bool { - structurable_to(c, lo, hi, top, None) +/// conditional skips, if / else, loops whose only way back is a branch at their end, and +/// forward jumps out of nested code (loop breaks, jumps past a join, s_endpgm before the end) +/// whose target starts an item of an enclosing level. Some(targets that leave the range). +fn structurable(c: &Ctx, lo: u64, hi: u64) -> Option> { + structurable_to(c, lo, hi, None, 0) } /// The else branch of `if (cond) { [then_lo, t) } else { [t, u) }`: the last block of the @@ -393,51 +521,80 @@ fn else_end(c: &Ctx, then_lo: u64, t: u64, hi: u64) -> Option { } } -fn structurable_to(c: &Ctx, lo: u64, hi: u64, top: bool, exit: Option) -> bool { - let mut i = c.leaders.partition_point(|&l| l < lo); - while i < c.leaders.len() && c.leaders[i] < hi { - let start = c.leaders[i]; - let end = block_end(c, i); - if let Some(&(a, b)) = c.loops.iter().find(|&&(a, b)| a == start && b <= hi && (a, b) != (lo, hi)) { - // the latch is the last block of the loop: a branch back to its start - let last = c.leaders.partition_point(|&l| l < b) - 1; - let latch = c.leaders[last]; - if !matches!(term(c, latch, b), Term::Cond(t) if t == a) { - why(start, &format!("pętla {a:#x}..{b:#x}: koniec {:?}", term(c, latch, b))); - return false; - } - if !structurable_to(c, a, latch, false, None) { - return false; - } - i = c.leaders.partition_point(|&l| l < b); - continue; - } - match term(c, start, end) { - Term::Next => i += 1, - Term::Cond(t) if t >= end && t <= hi && (t == hi || c.leaders.binary_search(&t).is_ok()) => { - // if / else: the skipped range ends with a jump over the else range - if let Some(u) = else_end(c, end, t, hi) { - if !structurable_to(c, end, t, false, Some(u)) || !structurable_to(c, t, u, false, None) { - return false; - } - i = c.leaders.partition_point(|&l| l < u); - continue; - } - if !structurable_to(c, end, t, false, None) { - return false; - } - i = c.leaders.partition_point(|&l| l < t); - } - Term::Jump(u) if Some(u) == exit && end == hi => i += 1, - Term::End if top && end == u64::MAX => i += 1, - Term::End if top && c.insts.iter().all(|d| d.pc < end) => i += 1, - other => { - why(start, &format!("blok {start:#x}..{end:#x} w {lo:#x}..{hi:#x}: {other:?}")); - return false; - } - } +fn structurable_to(c: &Ctx, lo: u64, hi: u64, exit: Option, nest: usize) -> Option> { + let key = (lo, hi, exit, nest.min(MAX_NEST)); + if let Some(r) = c.memo.borrow().get(&key) { + return r.clone(); } - true + let r = structurable_uncached(c, lo, hi, exit, nest); + c.memo.borrow_mut().insert(key, r.clone()); + r +} + +fn structurable_uncached(c: &Ctx, lo: u64, hi: u64, exit: Option, nest: usize) -> Option> { + let mut pending: BTreeSet = BTreeSet::new(); + let mut i = c.leaders.partition_point(|&l| l < lo); + let mut queued: Option = None; + while queued.is_some() || (i < c.leaders.len() && c.leaders[i] < hi) { + let it = match queued.take() { + Some(q) => q, + None => { + pending.remove(&c.leaders[i]); + match item_at(c, i, lo, hi, exit, nest, &pending) { + Ok((it, n)) => { + queued = rotated_after(c, i, lo, hi); + i = if let Some(Item::Loop { b, .. }) = queued { c.leaders.partition_point(|&l| l < b) } else { n }; + it + } + Err(e) => { + why(lo, &e); + return None; + } + } + } + }; + let (s, e) = it.range(); + pending.remove(&s); + if let Some(t) = pending.iter().find(|&&t| t > s && t < e) { + why(s, &format!("skok do {t:#x} wewnątrz {s:#x}..{e:#x}")); + return None; + } + let raised: BTreeSet = match it { + Item::Loop { a, latch, entry: None, .. } => { + let mut r = structurable_to(c, a, latch, None, nest + 1)?; + r.remove(&latch); + r + } + Item::Loop { a, latch, entry: Some(u), .. } => { + // the head [a, u) runs at the end of an iteration and may only fall into u + if structurable_to(c, a, u, None, nest + 1)?.iter().any(|&t| t != u) { + why(a, &format!("pętla obrócona {a:#x}: głowa wychodzi poza {u:#x}")); + return None; + } + let mut r = structurable_to(c, u, latch, None, nest + 1)?; + r.remove(&latch); + r + } + Item::If { end, t, u, .. } => { + let mut r = structurable_to(c, end, t, u, nest + 1)?; + if let Some(u) = u { + if r.contains(&t) { + why(t, &format!("skok z if na początek else {t:#x}")); + return None; + } + r.extend(structurable_to(c, t, u, None, nest + 1)?); + } + r + } + Item::Block { raise, .. } => raise.into_iter().collect(), + }; + if let Some(t) = raised.iter().find(|&&t| t < e) { + why(s, &format!("skok wstecz/do środka {t:#x} z {s:#x}..{e:#x}")); + return None; + } + pending.extend(raised); + } + Some(pending) } /// The instructions of block [start, end) at `depth`; the flow of the last one. @@ -457,44 +614,102 @@ fn emit_block(c: &Ctx, em: &mut emit::Em, body: &mut String, start: u64, end: u6 flow } -/// Emit a range `structurable` accepted. -fn emit_structured(c: &Ctx, em: &mut emit::Em, body: &mut String, lo: u64, hi: u64, depth: usize, blocks: &mut usize) { +/// Emit a range `structurable` accepted; returns the jump targets that leave it (their flags +/// are set; `flags` collects every flag for the declarations). +fn emit_structured(c: &Ctx, em: &mut emit::Em, body: &mut String, lo: u64, hi: u64, exit: Option, nest: usize, depth: usize, blocks: &mut usize, flags: &mut BTreeSet) -> BTreeSet { let pad = " ".repeat(depth); + let mut pending: BTreeSet = BTreeSet::new(); + // flags of the open `if (!(skip …)) {` around the following items + let mut guard: Option> = None; let mut i = c.leaders.partition_point(|&l| l < lo); - while i < c.leaders.len() && c.leaders[i] < hi { - let start = c.leaders[i]; - let end = block_end(c, i); - if let Some(&(a, b)) = c.loops.iter().find(|&&(a, b)| a == start && b <= hi && (a, b) != (lo, hi)) { - let last = c.leaders.partition_point(|&l| l < b) - 1; - let latch = c.leaders[last]; - body.push_str(&format!("{pad}[loop] for (;;) {{\n")); - emit_structured(c, em, body, a, latch, depth + 1, blocks); - match emit_block(c, em, body, latch, b, depth + 1, blocks) { - emit::Flow::Cond(cond, _) => body.push_str(&format!("{pad} if (!({cond})) break;\n")), - _ => body.push_str(&format!("{pad} break;\n")), + let mut queued: Option = None; + while queued.is_some() || (i < c.leaders.len() && c.leaders[i] < hi) { + let resolved = queued.is_none() && pending.remove(&c.leaders[i]); + let it = match queued.take() { + Some(q) => q, + None => { + let Ok((it, n)) = item_at(c, i, lo, hi, exit, nest, &pending) else { break }; + queued = rotated_after(c, i, lo, hi); + i = if let Some(Item::Loop { b, .. }) = queued { c.leaders.partition_point(|&l| l < b) } else { n }; + it + } + }; + let (s, _) = it.range(); + if guard.as_ref() != Some(&pending).filter(|p| !p.is_empty()) { + if guard.take().is_some() { + body.push_str(&format!("{pad}}}\n")); + } + if !pending.is_empty() { + let cond: Vec = pending.iter().map(|&t| skip_flag(t)).collect(); + body.push_str(&format!("{pad}if (!({})) {{\n", cond.join(" || "))); + guard = Some(pending.clone()); } - body.push_str(&format!("{pad}}}\n")); - i = c.leaders.partition_point(|&l| l < b); - continue; } - match emit_block(c, em, body, start, end, depth, blocks) { - emit::Flow::Cond(cond, t) => { - body.push_str(&format!("{pad}if (!({cond})) {{\n")); - emit_structured(c, em, body, end, t, depth + 1, blocks); - if let Some(u) = else_end(c, end, t, hi) { - body.push_str(&format!("{pad}}} else {{\n")); - emit_structured(c, em, body, t, u, depth + 1, blocks); - body.push_str(&format!("{pad}}}\n")); - i = c.leaders.partition_point(|&l| l < u); - } else { - body.push_str(&format!("{pad}}}\n")); - i = c.leaders.partition_point(|&l| l < t); + let d = depth + guard.is_some() as usize; + let ipad = " ".repeat(d); + if resolved { + body.push_str(&format!("{ipad}{} = false;\n", skip_flag(s))); + } + let raised: BTreeSet = match it { + Item::Loop { a, b, latch, entry } => { + body.push_str(&format!("{ipad}[loop] for (;;) {{\n")); + let mut r = emit_structured(c, em, body, entry.unwrap_or(a), latch, None, nest + 1, d + 1, blocks, flags); + for &t in &r { + if t == latch { + body.push_str(&format!("{ipad} {} = false;\n", skip_flag(t))); + } else { + body.push_str(&format!("{ipad} if ({}) break;\n", skip_flag(t))); + } + } + r.remove(&latch); + match emit_block(c, em, body, latch, b, d + 1, blocks) { + emit::Flow::Cond(cond, _) => body.push_str(&format!("{ipad} if (!({cond})) break;\n")), + _ => body.push_str(&format!("{ipad} break;\n")), + } + if let Some(u) = entry { + // rotated: the head after the latch, falling into the next iteration + for t in emit_structured(c, em, body, a, u, None, nest + 1, d + 1, blocks, flags) { + body.push_str(&format!("{ipad} {} = false;\n", skip_flag(t))); + } + } + body.push_str(&format!("{ipad}}}\n")); + r + } + Item::If { start, end, t, u } => { + let cond = match emit_block(c, em, body, start, end, d, blocks) { + emit::Flow::Cond(cond, _) => cond, + _ => "false".into(), + }; + body.push_str(&format!("{ipad}if (!({cond})) {{\n")); + let mut r = emit_structured(c, em, body, end, t, u, nest + 1, d + 1, blocks, flags); + if let Some(u) = u { + body.push_str(&format!("{ipad}}} else {{\n")); + r.extend(emit_structured(c, em, body, t, u, None, nest + 1, d + 1, blocks, flags)); + } + body.push_str(&format!("{ipad}}}\n")); + r + } + Item::Block { start, end, raise } => { + let flow = emit_block(c, em, body, start, end, d, blocks); + match raise { + None => BTreeSet::new(), + Some(t) => { + flags.insert(t); + match flow { + emit::Flow::Cond(cond, _) => body.push_str(&format!("{ipad}if ({cond}) {} = true;\n", skip_flag(t))), + _ => body.push_str(&format!("{ipad}{} = true;\n", skip_flag(t))), + } + BTreeSet::from([t]) + } } } - // the jump at the end of an if branch over the else branch: nothing to emit - _ => i += 1, - } + }; + pending.extend(raised); } + if guard.is_some() { + body.push_str(&format!("{pad}}}\n")); + } + pending } /// The longest range [start, x) (x ≤ hi) entered only at `start`, left only by falling into @@ -521,11 +736,11 @@ fn structured_span(c: &Ctx, i: usize, hi: u64) -> Option { } // entered only at start: no branch from outside lands strictly inside let entered_inside = |x: u64| c.edges.iter().any(|&(src, dst)| dst > start && dst < x && (src < start || src >= x)); - ends.iter().rev().take(64).copied().find(|&x| !entered_inside(x) && structurable_to(c, start, x, false, None)) + ends.iter().rev().take(64).copied().find(|&x| !entered_inside(x) && structurable_to(c, start, x, None, 0).is_some_and(|r| r.iter().all(|&t| t == x))) } /// Emit the blocks starting in [lo, hi) at nesting `depth`; loop ranges become `while`. -fn emit_range(c: &Ctx, em: &mut emit::Em, body: &mut String, lo: u64, hi: u64, depth: usize, blocks: &mut usize) { +fn emit_range(c: &Ctx, em: &mut emit::Em, body: &mut String, lo: u64, hi: u64, depth: usize, blocks: &mut usize, flags: &mut BTreeSet) { let pad = " ".repeat(depth); let mut i = c.leaders.partition_point(|&l| l < lo); while i < c.leaders.len() && c.leaders[i] < hi { @@ -533,7 +748,7 @@ fn emit_range(c: &Ctx, em: &mut emit::Em, body: &mut String, lo: u64, hi: u64, d let inner = c.loops.iter().filter(|&&(a, b)| a == start && b <= hi && (a, b) != (lo, hi)).max_by_key(|x| x.1).copied(); if let Some((a, b)) = inner { body.push_str(&format!("{pad}[loop] while (pc >= {a}u && pc < {b}u) {{\n")); - emit_range(c, em, body, a, b, depth + 1, blocks); + emit_range(c, em, body, a, b, depth + 1, blocks, flags); body.push_str(&format!("{pad}}}\n")); i = c.leaders.partition_point(|&l| l < b); continue; @@ -541,7 +756,9 @@ fn emit_range(c: &Ctx, em: &mut emit::Em, body: &mut String, lo: u64, hi: u64, d // a single-entry, single-exit stretch: structured code under one guard if let Some(x) = structured_span(c, i, hi) { body.push_str(&format!("{pad}if (pc == {start}u) {{\n")); - emit_structured(c, em, body, start, x, depth + 1, blocks); + for t in emit_structured(c, em, body, start, x, None, 0, depth + 1, blocks, flags) { + body.push_str(&format!("{pad} {} = false;\n", skip_flag(t))); + } let next = if x == u64::MAX || !c.starts.contains(&x) { "0xFFFFFFFFu".to_string() } else { format!("{x}u") }; body.push_str(&format!("{pad} pc = {next};\n{pad}}}\n")); i = c.leaders.partition_point(|&l| l < x); @@ -731,15 +948,21 @@ pub fn translate(code: &[u8], opt: &Options) -> Result { loops.sort(); loops.dedup(); let edges: Vec<(u64, u64)> = insts.iter().filter_map(|d| rdna2::branch_target(d).map(|t| (d.pc, t))).collect(); - let ctx = Ctx { insts: &insts, starts: &starts, leaders: &leaders, loops: &loops, edges: &edges }; - if gs_jump.is_none() && std::env::var_os("XCL_RECOMP_NO_STRUCTURED").is_none() && structurable(&ctx, 0, u64::MAX, true) { + let ctx = Ctx { insts: &insts, starts: &starts, leaders: &leaders, loops: &loops, edges: &edges, memo: Default::default() }; + let mut flags = BTreeSet::new(); + let mut code = String::new(); + if gs_jump.is_none() && std::env::var_os("XCL_RECOMP_NO_STRUCTURED").is_none() && structurable(&ctx, 0, u64::MAX).is_some() { // structured control flow: plain if / loops, no block dispatch on `pc` (much // smaller for DXC and the driver on big programs) - emit_structured(&ctx, &mut em, &mut body, 0, u64::MAX, 1, &mut blocks); + emit_structured(&ctx, &mut em, &mut code, 0, u64::MAX, None, 0, 1, &mut blocks, &mut flags); } else { - body.push_str(" uint pc = 0;\n"); - emit_range(&ctx, &mut em, &mut body, 0, u64::MAX, 1, &mut blocks); + code.push_str(" uint pc = 0;\n"); + emit_range(&ctx, &mut em, &mut code, 0, u64::MAX, 1, &mut blocks, &mut flags); } + for &t in &flags { + body.push_str(&format!(" bool {} = false;\n", skip_flag(t))); + } + body.push_str(&code); } let hlsl = em.finish(&body); Ok(Translation { hlsl, unsupported: em.unsupported, unsupported_why: em.unsupported_why, ignored: em.ignored, instructions: insts.len(), blocks }) diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 2eefac8..72dced5 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -2002,6 +2002,11 @@ fn retail_translation_survey() { instructions: usize, // DXC: seconds per variant, failures "stage: first line" → (count, example) dxc_times: Vec<(f64, String)>, + // DXC seconds / variants: fully structured, with `pc` guards + dxc_structured: (f64, usize), + dxc_hybrid: (f64, usize), + hybrid: usize, + hybrid_names: Vec<(usize, String)>, dxc_errors: BTreeMap, } let with_dxc = std::env::var_os("XCL_SURVEY_DXC").is_some() && super::dxc::location().is_ok(); @@ -2045,8 +2050,12 @@ fn retail_translation_survey() { Ok((super::translate(code, &Options { mode, wave64: super::detect_wave64(code), ..Default::default() })?, profile)) }); // DXC outside the lock + let guarded = matches!(&res, Ok(Ok((t, _))) if t.hlsl.contains("pc ==")); let dxc = match (&res, with_dxc) { (Ok(Ok((t, profile))), true) => { + if std::env::var_os("XCL_SURVEY_TRACE").is_some() { + eprintln!("dxc start {} ({} KB)", r.name, t.hlsl.len() / 1024); + } let t1 = std::time::Instant::now(); let r = super::dxc::compile(&t.hlsl, "main", profile, &[]); Some((t1.elapsed().as_secs_f64(), r.err().map(|e| e.lines().find(|l| l.contains("error")).unwrap_or(e.lines().next().unwrap_or("")).to_string()))) @@ -2060,8 +2069,15 @@ fn retail_translation_survey() { let x = a.errors.entry(format!("{stage}: {msg}")).or_insert((0, r.name.clone())); x.0 += 1; }; + a.hybrid += guarded as usize; + if let (true, Ok(Ok((t, _)))) = (guarded, &res) { + a.hybrid_names.push((t.instructions, r.name.clone())); + } if let Some((secs, err)) = dxc { a.dxc_times.push((secs, r.name.clone())); + let b = if guarded { &mut a.dxc_hybrid } else { &mut a.dxc_structured }; + b.0 += secs; + b.1 += 1; if let Some(e) = err { // drop the file:line:col prefix so equal errors group let e = e.split("error:").nth(1).unwrap_or(&e).trim().to_string(); @@ -2090,6 +2106,10 @@ fn retail_translation_survey() { let a = acc.into_inner().unwrap(); let (all, done): (usize, usize) = a.stages.values().fold((0, 0), |s, v| (s.0 + v.0, s.1 + v.1)); println!("rekordów: {} (co {every}.), wariantów FSSM: {all}, przetłumaczonych w całości: {done} ({:.1}%), instrukcji: {}, czas {:.1} s", records.len(), 100.0 * done as f64 / all.max(1) as f64, a.instructions, t0.elapsed().as_secs_f64()); + println!("z blokami pc (nie w pełni strukturalne): {} / {all}", a.hybrid); + let mut hn = a.hybrid_names; + hn.sort(); + println!(" najmniejsze: {:?}", hn.iter().take(6).collect::>()); for (st, (n, ok)) in &a.stages { println!(" {st:<14} {ok:>6} / {n:<6} ({:.1}%)", 100.0 * *ok as f64 / (*n).max(1) as f64); } @@ -2110,7 +2130,19 @@ fn retail_translation_survey() { t.sort_by(|x, y| x.0.total_cmp(&y.0)); let q = |f: f64| t.get(((t.len() as f64 * f) as usize).min(t.len().saturating_sub(1))).map_or(0.0, |x| x.0); let failed: usize = a.dxc_errors.values().map(|v| v.0).sum(); + println!( + "DXC strukturalne: {} wariantów, {:.0} s (średnio {:.2} s); z blokami pc: {} wariantów, {:.0} s (średnio {:.2} s)", + a.dxc_structured.1, + a.dxc_structured.0, + a.dxc_structured.0 / a.dxc_structured.1.max(1) as f64, + a.dxc_hybrid.1, + a.dxc_hybrid.0, + a.dxc_hybrid.0 / a.dxc_hybrid.1.max(1) as f64 + ); println!("DXC: {} skompilowanych, {failed} błędów; czas mediana {:.2} s, p90 {:.2} s, max {:.1} s ({}), suma {:.0} s", t.len(), q(0.5), q(0.9), t.last().map_or(0.0, |x| x.0), t.last().map_or("", |x| x.1.as_str()), t.iter().map(|x| x.0).sum::()); + for (secs, name) in t.iter().rev().take(10) { + println!(" {secs:>6.2} s {name}"); + } let mut errs: Vec<_> = a.dxc_errors.into_iter().collect(); errs.sort_by(|x, y| y.1 .0.cmp(&x.1 .0)); for (k, (n, ex)) in errs.iter().take(20) { @@ -2118,3 +2150,68 @@ fn retail_translation_survey() { } } } + +/// Shape of the HLSL and DXC cost of named retail shaders (reverse engineering of compile +/// times): `XCL_SAMPLE_RPF`, `XCL_NAMES=a,b` (substring of the record name), `XCL_DXC_ARGS`, +/// `XCL_HLSL_OUT=` (writes the HLSL). The process is capped at 8 GB. +#[test] +#[ignore] +fn retail_shader_cost() { + let (Ok(path), Ok(names)) = (std::env::var("XCL_SAMPLE_RPF"), std::env::var("XCL_NAMES")) else { return }; + unsafe { + use windows_sys::Win32::System::JobObjects::*; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + let job = CreateJobObjectW(std::ptr::null(), std::ptr::null()); + let mut info: JOBOBJECT_EXTENDED_LIMIT_INFORMATION = std::mem::zeroed(); + info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY; + info.ProcessMemoryLimit = 8 << 30; + SetInformationJobObject(job, JobObjectExtendedLimitInformation, &info as *const _ as *const _, std::mem::size_of_val(&info) as u32); + AssignProcessToJobObject(job, GetCurrentProcess()); + } + let args = std::env::var("XCL_DXC_ARGS").unwrap_or_default(); + let extra: Vec<&str> = args.split_whitespace().collect(); + let data = std::fs::read(path).unwrap(); + for r in crate::gpu::pack::scan(&data, 0x40) { + if !names.split(',').any(|n| !n.is_empty() && r.name.contains(n)) { + continue; + } + let Some(blob) = crate::gpu::pack::inflate(&data, &r) else { continue }; + let Some(sh) = crate::gpu::xbox::parse(&blob) else { continue }; + for f in &sh.fssm { + let Some(mode) = super::interface(&blob, &sh, f) else { continue }; + let profile = match &mode { + Mode::Vertex(_) => "vs_6_6", + Mode::Pixel(_) => "ps_6_6", + _ => "cs_6_6", + }; + let p = f.programs[0]; + let code = &f.data[p.offset..p.offset + p.len]; + let t = super::translate(code, &Options { mode, wave64: super::detect_wave64(code), ..Default::default() }).unwrap(); + let owned = t.hlsl.clone(); + let h = &owned; + if let Ok(dir) = std::env::var("XCL_HLSL_OUT") { + let _ = std::fs::write(std::path::Path::new(&dir).join(format!("{}.hlsl", r.name)), h); + eprintln!("HLSL zapisany: {} ({} KB)", r.name, h.len() / 1024); + } + let t0 = std::time::Instant::now(); + let r2 = super::dxc::compile(h, "main", profile, &extra); + let secs = t0.elapsed().as_secs_f64(); + println!( + "{} [{profile}] instrukcji {}, HLSL {} KB, linii {}, pc-dispatch {}, if {}, for(;;) {}, select {} → DXC {:.2} s, {}", + r.name, + t.instructions, + h.len() / 1024, + h.lines().count(), + h.matches("pc ==").count(), + h.matches("if (").count(), + h.matches("for (;;)").count(), + h.matches("select(").count(), + secs, + r2.as_ref().map(|b| format!("DXIL {} KB", b.len() / 1024)).unwrap_or_else(|e| e.lines().next().unwrap_or("").to_string()) + ); + if let Ok(dir) = std::env::var("XCL_HLSL_OUT") { + let _ = std::fs::write(std::path::Path::new(&dir).join(format!("{}.hlsl", r.name)), h); + } + } + } +}