Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
177 changes: 146 additions & 31 deletions crates/xcl/src/gpu/recomp/emit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4185,7 +4185,7 @@ impl Em {
}

/// Storage and functions of the split wave64 form (`PRELUDE_X64`).
fn x64_prelude(&self, h: &mut String) {
fn x64_prelude(&self, h: &mut String, outline: bool) {
let threads = self.x64_threads();
let waves = threads.div_ceil(64).max(1) as usize;
let slot = self.x64_words;
Expand All @@ -4206,7 +4206,7 @@ impl Em {
let _ = writeln!(h, "groupshared uint xcl_xs[{slots}];\ngroupshared uint xcl_xc[{counters}];\ngroupshared uint xcl_xw;");
h.push_str("#define XCL_XS(i) xcl_xs[(i)]\n#define XCL_XC(i) xcl_xc[(i)]\n#define XCL_XW xcl_xw\n");
}
h.push_str(PRELUDE_X64);
h.push_str(&PRELUDE_X64.replace("XCL_EXCHANGE_FN ", if outline { "[noinline] " } else { "" }));
}

/// Storage and functions for early-exit-safe, bounded `s_barrier` (`PRELUDE_SAFE_BARRIER`).
Expand All @@ -4231,7 +4231,10 @@ impl Em {
h.push_str(" xcl_xn = XCL_X_THREADS > ((xcl_tid & ~31u) ^ 32u) ? min(32u, XCL_X_THREADS - ((xcl_tid & ~31u) ^ 32u)) : 0u;\n");
}

pub fn finish(&self, body: &str) -> String {
pub fn finish(&self, body: &str, instructions: usize) -> String {
// DXC otherwise copies each window switch and split-wave rendezvous to every call
// site. Keep short programs inline so the compiler can specialize their accesses.
let outline = instructions >= 1024 && matches!(self.opt.mode, Mode::Kernel | Mode::Compute(_));
let mut h = String::new();
h.push_str("// generated by XCL (RDNA2 -> HLSL), do not edit\n");
if matches!(self.opt.mode, Mode::Pixel(_)) {
Expand Down Expand Up @@ -4261,7 +4264,7 @@ impl Em {
}
h.push_str(PRELUDE);
if self.x64() {
self.x64_prelude(&mut h);
self.x64_prelude(&mut h, outline);
}
if let Some(u) = &self.upper {
// wave64 VS / PS on a GPU with 32-lane waves only (`upper_lanes`)
Expand All @@ -4272,7 +4275,9 @@ impl Em {
}
let infos: Vec<String> = (0..BUF_FORMATS.len()).map(|i| format!("0x{:08X}u", buf_format_info(i))).collect();
let _ = writeln!(h, "static const uint FMT_INFO[78] = {{ {} }};", infos.join(", "));
h.push_str(PRELUDE_MEM);
// Typed buffer conversions are large and often repeated hundreds or thousands of
// times in one program. Keep their scalar implementations shared in larger CSs.
h.push_str(&format_mem_prelude(instructions >= 256 && matches!(self.opt.mode, Mode::Kernel | Mode::Compute(_))));
if self.uses_scratch {
h.push_str(PRELUDE_SCRATCH);
}
Expand Down Expand Up @@ -4704,7 +4709,7 @@ impl Em {
}
if windows > 1 {
let coherent = if matches!(self.opt.mode, Mode::Compute(_)) { "globallycoherent " } else { "" };
h = windowed(&h, windows, self.opt.heap_windows.then_some(coherent));
h = windowed(&h, windows, self.opt.heap_windows.then_some(coherent), outline);
}
h
}
Expand Down Expand Up @@ -5095,7 +5100,8 @@ const LOADX4_ONE_WINDOW: &str = "uint4 xcl_loadx4(uint4 a) { return uint4(mem.Lo
/// definitions replace the placeholder.
/// `heap`: Some(storage class) – the accessors take window k from the descriptor heap
/// (`Options::heap_windows`) instead of switching over the root UAVs.
fn windowed(h: &str, windows: u32, heap: Option<&str>) -> String {
fn windowed(h: &str, windows: u32, heap: Option<&str>, outline: bool) -> String {
let outline = outline && heap.is_none();
let mut out = String::with_capacity(h.len() + 8192);
let mut rest = h;
while let Some(i) = rest.find("mem.") {
Expand All @@ -5107,13 +5113,95 @@ fn windowed(h: &str, windows: u32, heap: Option<&str>) -> String {
out.push_str("xcl_m");
out.push_str(&tail[..name_len]);
rest = &tail[name_len..];
if outline && scalar_window_method(&tail[..name_len]) {
out.push_str("(xcl_w, ");
rest = &rest[1..];
}
} else {
out.push_str(&rest[..i + 4]);
rest = tail;
}
}
out.push_str(rest);
out.replacen(MEM_ACCESSORS_HERE, &mem_accessors(windows, heap), 1)
out.replacen(MEM_ACCESSORS_HERE, &mem_accessors(windows, heap, outline), 1)
}

// SM 6.6 DXIL retains scalar calls. Vector accessors use scalar out parameters below
// so the driver sees one copy of the memory-window switch instead of one per use.
fn scalar_window_method(name: &str) -> bool {
matches!(name, "Load" | "Store") || name.starts_with("Interlocked")
}

fn vector_window_accessor(windows: u32, name: &str, components: usize, store: bool, separate_addresses: bool) -> String {
let lanes = &['x', 'y', 'z', 'w'][..components];
let ty = format!("uint{components}");
let method = if separate_addresses { "Load".to_string() } else { name.trim_start_matches("xcl_m").to_string() };
let mut s = String::new();
let input = if separate_addresses {
lanes.iter().map(|c| format!("uint a{c}")).collect::<Vec<_>>().join(", ")
} else {
"uint a".into()
};
let extra = lanes.iter().map(|c| format!("{}uint {}{c}", if store { "" } else { "out " }, if store { 'v' } else { 'o' })).collect::<Vec<_>>().join(", ");
let _ = write!(s, "[noinline] void {name}_shared(uint window, {input}, {extra}) {{ ");
if store {
let values = lanes.iter().map(|c| format!("v{c}")).collect::<Vec<_>>().join(", ");
let _ = write!(s, "{ty} v = {ty}({values}); ");
} else {
let _ = write!(s, "{ty} v; ");
}
s.push_str("[branch] switch (window) { ");
for k in 0..windows {
let mem = if k == 0 { "mem".to_string() } else { format!("mem{k}") };
let _ = write!(s, "case {k}u: ");
if store {
let _ = write!(s, "{mem}.{method}(a, v); ");
} else if separate_addresses {
let values = lanes.iter().map(|c| format!("{mem}.Load(a{c})")).collect::<Vec<_>>().join(", ");
let _ = write!(s, "v = {ty}({values}); ");
} else {
let _ = write!(s, "v = {mem}.{method}(a); ");
}
s.push_str("break; ");
}
if !store {
let zeros = vec!["0u"; components].join(", ");
let _ = write!(s, "default: v = {ty}({zeros}); break; }} ");
for c in lanes {
let _ = write!(s, "o{c} = v.{c}; ");
}
} else {
s.push_str("default: break; } ");
}
s.push_str("}\n");
let wrapper_input = if separate_addresses { format!("{ty} a") } else if store { format!("uint a, {ty} v") } else { "uint a".into() };
let _ = write!(s, "{} {name}({wrapper_input}) {{ ", if store { "void" } else { &ty });
if !store {
for c in lanes {
let _ = write!(s, "uint o{c}; ");
}
}
let source = if separate_addresses {
lanes.iter().map(|c| format!("a.{c}")).collect::<Vec<_>>().join(", ")
} else if store {
let values = lanes.iter().map(|c| format!("v.{c}")).collect::<Vec<_>>().join(", ");
format!("a, {values}")
} else {
"a".into()
};
let _ = write!(s, "{name}_shared(xcl_w, {source}");
if !store {
for c in lanes {
let _ = write!(s, ", o{c}");
}
}
s.push_str("); ");
if !store {
let values = lanes.iter().map(|c| format!("o{c}")).collect::<Vec<_>>().join(", ");
let _ = write!(s, "return {ty}({values}); ");
}
s.push_str("}\n");
s
}

/// The accessor functions: one per `mem` method (and overload) the translator emits.
Expand All @@ -5122,7 +5210,8 @@ fn windowed(h: &str, windows: u32, heap: Option<&str>) -> String {
/// out-of-UMA pointers can never wrap onto live memory windows.
/// `heap`: Some(storage class) – window k is taken from the descriptor heap
/// (`Options::heap_windows`) and the same rule is one comparison before the access.
fn mem_accessors(windows: u32, heap: Option<&str>) -> String {
fn mem_accessors(windows: u32, heap: Option<&str>, outline: bool) -> String {
let outline = outline && heap.is_none();
let mut sigs: Vec<(&str, String, &str, &str, &str)> = vec![
("uint", "Load".into(), "uint a", "a", "return 0u;"),
("uint2", "Load2".into(), "uint a", "a", "return uint2(0u, 0u);"),
Expand Down Expand Up @@ -5160,14 +5249,27 @@ fn mem_accessors(windows: u32, heap: Option<&str>) -> String {
}
return s;
}
let _ = write!(s, "uint4 xcl_loadx4(uint4 a) {{ [branch] switch (xcl_w) {{ ");
let _ = write!(s, "case 0u: return uint4(mem.Load(a.x), mem.Load(a.y), mem.Load(a.z), mem.Load(a.w)); ");
for k in 1..windows {
let _ = write!(s, "case {k}u: return uint4(mem{k}.Load(a.x), mem{k}.Load(a.y), mem{k}.Load(a.z), mem{k}.Load(a.w)); ");
if outline {
s.push_str(&vector_window_accessor(windows, "xcl_loadx4", 4, false, true));
} else {
let _ = write!(s, "uint4 xcl_loadx4(uint4 a) {{ [branch] switch (xcl_w) {{ ");
let _ = write!(s, "case 0u: return uint4(mem.Load(a.x), mem.Load(a.y), mem.Load(a.z), mem.Load(a.w)); ");
for k in 1..windows {
let _ = write!(s, "case {k}u: return uint4(mem{k}.Load(a.x), mem{k}.Load(a.y), mem{k}.Load(a.z), mem{k}.Load(a.w)); ");
}
let _ = writeln!(s, "default: return uint4(0u, 0u, 0u, 0u); }} }}");
}
let _ = writeln!(s, "default: return uint4(0u, 0u, 0u, 0u); }} }}");
for (ret, name, params, args, def) in sigs {
let _ = write!(s, "{ret} xcl_m{name}({params}) {{ [branch] switch (xcl_w) {{ ");
if outline && matches!(name.as_str(), "Load2" | "Load3" | "Load4" | "Store2" | "Store3" | "Store4") {
let components = name.chars().last().unwrap().to_digit(10).unwrap() as usize;
s.push_str(&vector_window_accessor(windows, &format!("xcl_m{name}"), components, name.starts_with("Store"), false));
continue;
}
if outline && scalar_window_method(&name) {
let _ = write!(s, "[noinline] {ret} xcl_m{name}(uint window, {params}) {{ [branch] switch (window) {{ ");
} else {
let _ = write!(s, "{ret} xcl_m{name}({params}) {{ [branch] switch (xcl_w) {{ ");
}
if ret == "void" {
let _ = write!(s, "case 0u: mem.{name}({args}); break; ");
for k in 1..windows {
Expand Down Expand Up @@ -5261,6 +5363,11 @@ void scr_st(uint a, uint v, uint n) {
}
"#;

fn format_mem_prelude(outline: bool) -> String {
// Retained DXIL calls require scalar parameters and results on the supported profiles.
PRELUDE_MEM.replace("XCL_FORMAT_FN ", if outline { "[noinline] " } else { "" })
}

const PRELUDE_MEM: &str = r#"
uint4 ld_raw(uint a) {
// one Load4 + one Load (with several memory windows each is a switch) and no branch
Expand Down Expand Up @@ -5290,12 +5397,10 @@ float uf_small(uint v, uint mb) {
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) { 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 = 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);
uint fmt_offset(uint info, uint c) {
return select(c > 0u, (info >> 8) & 63u, 0u) + select(c > 1u, (info >> 14) & 63u, 0u) + select(c > 2u, (info >> 20) & 63u, 0u);
}
XCL_FORMAT_FN uint fmt_value(uint v, uint w, uint ty) {
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));
Expand All @@ -5305,8 +5410,12 @@ uint fmt_comp(uint4 r, uint info, uint c) {
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);
return 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))))));
}
uint fmt_one(uint ty) { return select(or(ty == 4u, ty == 5u), 1u, 0x3F800000u); }
uint fmt_comp(uint4 r, uint info, uint c) {
uint ty = (info >> 3) & 7u, w = (info >> (8u + 6u * c)) & 63u;
return select(c >= (info & 7u), select(c == 3u, fmt_one(ty), 0u), fmt_value(bits_at(r, fmt_offset(info, c), w), w, ty));
}
// image_bvh(64)_intersect_ray: type = node & 7, at = low 32 bits of base + (node & ~7) * 8.
// box32 (5) / box16 (4): 4 child ids + boxes → hit children (closest first when sorting),
Expand Down Expand Up @@ -5381,19 +5490,23 @@ uint fmt_encode(uint x, uint info, uint c) {
uint h = f32tof16(f);
return w == 11u ? ((h >> 4) & 0x7FFu) : ((h >> 5) & 0x3FFu);
}
uint4 fmt_pack(uint4 v, uint info) {
XCL_FORMAT_FN void fmt_pack_shared(uint v0, uint v1, uint v2, uint v3, uint info, out uint o0, out uint o1, out uint o2, out uint o3) {
uint4 v = uint4(v0, v1, v2, v3);
uint4 r = uint4(0u, 0u, 0u, 0u); uint n = info & 7u; uint off = 0u;
[unroll] for (uint c = 0u; c < 4u; c++) { if (c < n) { uint w = (info >> (8u + 6u * c)) & 63u; put_bits(r, off, w, fmt_encode(v[c], info, c)); off += w; } }
return r;
o0 = r.x; o1 = r.y; o2 = r.z; o3 = r.w;
}
uint4 fmt_pack(uint4 v, uint info) { uint o0, o1, o2, o3; fmt_pack_shared(v.x, v.y, v.z, v.w, info, o0, o1, o2, o3); return uint4(o0, o1, o2, o3); }
void st_part(uint b, uint m, uint v) { mem.InterlockedAnd(b, ~m); mem.InterlockedOr(b, v & m); }
void st_bytes(uint a, uint4 r, uint n) {
XCL_FORMAT_FN void st_bytes_shared(uint a, uint r0, uint r1, uint r2, uint r3, uint n) {
uint4 r = uint4(r0, r1, r2, r3);
uint s = (a & 3u) * 8u; uint b = a & ~3u;
if (s == 0u && (n & 3u) == 0u) { [unroll] for (uint k = 0u; k < 4u; k++) if (k * 4u < n) mem.Store(b + 4u * k, r[k]); return; }
uint m = n >= 4u ? 0xFFFFFFFFu : ((1u << (8u * n)) - 1u);
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));
}
void st_bytes(uint a, uint4 r, uint n) { st_bytes_shared(a, r.x, r.y, r.z, r.w, n); }
uint dst_sel(uint4 c, uint sel, bool isint) { return select(sel == 0u, 0u, select(sel == 1u, select(isint, 1u, 0x3F800000u), pick4(c, (sel - 4u) & 3u))); }
"#;

Expand Down Expand Up @@ -5432,7 +5545,7 @@ uint xcl_x_at(uint half, uint k) { return ((xcl_cw * 2u + half) * 2u + (k & 1u))
void xcl_x_put(uint i, uint v) { XCL_XS(xcl_x_at(xcl_half, xcl_xk) + i) = v; }
uint xcl_x_get(uint i) { return XCL_XS(xcl_x_at(xcl_half ^ 1u, xcl_xk - 1u) + i); }
// meet the other half after `xcl_x_put`: true = its words are readable (`xcl_x_get`)
bool xcl_x_meet() {
XCL_EXCHANGE_FN bool xcl_x_meet() {
uint k = xcl_xk;
xcl_xk = k + 1u;
if (xcl_xn == 0u) return false;
Expand Down Expand Up @@ -5466,21 +5579,23 @@ bool xcl_x_meet() {
#endif
return true;
}
uint2 xcl_x_ballot(bool b) {
XCL_EXCHANGE_FN void xcl_x_ballot_shared(bool b, out uint lo, out uint hi) {
uint m = WaveActiveBallot(b).x;
xcl_x_put(0u, m);
uint o = xcl_x_meet() ? xcl_x_get(0u) : 0u;
return xcl_half != 0u ? uint2(o, m) : uint2(m, o);
lo = xcl_half != 0u ? o : m;
hi = xcl_half != 0u ? m : o;
}
uint2 xcl_x_ballot(bool b) { uint lo, hi; xcl_x_ballot_shared(b, lo, hi); return uint2(lo, hi); }
// v_readlane / v_readfirstlane: the same lane index in both halves; the owner half's value
uint xcl_x_rla_uniform(uint v, uint l) {
XCL_EXCHANGE_FN uint xcl_x_rla_uniform(uint v, uint l) {
uint m = WaveReadLaneAt(v, l & 31u);
xcl_x_put(0u, m);
uint o = xcl_x_meet() ? xcl_x_get(0u) : 0u;
return (l >> 5) == xcl_half ? m : o;
}
// ds_bpermute: any lane of the wave
uint xcl_x_rla_any(uint v, uint l) {
XCL_EXCHANGE_FN uint xcl_x_rla_any(uint v, uint l) {
xcl_x_put(WaveGetLaneIndex(), v);
uint o = xcl_x_meet() ? xcl_x_get(l & 31u) : 0u;
uint m = WaveReadLaneAt(v, l & 31u);
Expand Down
2 changes: 1 addition & 1 deletion crates/xcl/src/gpu/recomp/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1510,7 +1510,7 @@ pub fn translate(code: &[u8], opt: &Options) -> Result<Translation, String> {
}
body.push_str(&code);
}
let hlsl = em.finish(&body);
let hlsl = em.finish(&body, insts.len());
let static_samplers = em.static_used.clone();
Ok(Translation { hlsl, unsupported: em.unsupported, unsupported_why: em.unsupported_why, ignored: em.ignored, instructions: insts.len(), blocks, static_samplers })
}
Expand Down
Loading
Loading