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
1 change: 1 addition & 0 deletions THIRD_PARTY.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ carry a note in their header about its origin and the date of changes (GPL-2.0
| [VIctory](https://github.com/Marvisak/VIctory) | GPL-3.0; used in XCL under GPL-2.0-only with its author's permission (2026-11-24) | `crates/xcl/src/hle/bcpack/`: port of its `victory-formats/src/bcpack.rs`, and `tables.rs` generated by `scripts/gen_bcpack_victory_tables.py` from its `bcpack-tables.bin` (the format's constant tables; its 128 rANS models are those of Microsoft's [silicon-rans](https://github.com/microsoft/silicon-rans) sample, MIT) | port to Rust; tables |
| [LLVM](https://github.com/llvm/llvm-project) | Apache-2.0 WITH LLVM-exception | `tests/data/llvm-amdgpu/*` (test data, not part of the program); GFX10 buffer format values (`UfmtSymbolicGFX10`) in `gpu/recomp/emit.rs` | test vectors; hardware facts |
| [WinDurango](https://github.com/WinDurango/WinDurango) | LGPL-3.0 | no code; d3d12_x.dll export numbers (facts) in `crates/xcl/data/stubdb.toml` | reference only |
| [PortBridge compact slots](https://github.com/akimfomin/PortBridge/tree/2e46a3635ee7725860ceec08ca246a2ab14615b9/research/xcl-2126-compact-slots) | GPL-2.0-only | `crates/xcl/src/gpu/dxil/module/split.rs` | payload lifetime and slot ordering applied to Kalmarv's XCL #2126 layout, with attribution in the file |
| [libHttpClient](https://github.com/microsoft/libHttpClient) | MIT | no code; XTaskQueue/XAsync contract | specification |
| Windows XGameRuntime (`System32\xgameruntime.dll`) | system | class GUIDs and slot order of the GDK thunk protocol in `hle/xgameruntime/api.rs` (facts, determined by analysis); APIs XCL does not implement are forwarded to it at runtime | interoperability; not distributed |
| docs.xbox.com | documentation | signatures, enums, structs written independently | reference |
Expand Down
163 changes: 140 additions & 23 deletions crates/xcl/src/gpu/dxil/module/split.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
//! Partition the optimized compute entry at CFG edges. A dispatch cannot
//! jump back to an earlier dispatch, so a strongly connected component is
//! indivisible. Each crossing edge has its own compact state layout.
//! indivisible. Scratch payload words can be reused across disjoint piece lifetimes.
//!
//! The PortBridge compact-slots patch (GPL-2.0-only, 2026-11-25) adds the
//! lifetime allocator to Kalmarv's persistent-payload layout at XCL #2126.
//! Source: https://github.com/akimfomin/PortBridge/tree/2e46a3635ee7725860ceec08ca246a2ab14615b9/research/xcl-2126-compact-slots

use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};

Expand All @@ -25,6 +29,57 @@ pub struct DispatchChain {
pub dwords_per_group: u32,
}

struct PayloadLifetime {
value: Value,
first: usize,
last: usize,
words: u32,
}

type ScratchLayout = (u32, BTreeMap<Value, u32>);

fn reuse_payload_slots(mut lifetimes: Vec<PayloadLifetime>) -> Option<ScratchLayout> {
lifetimes.sort_unstable_by_key(|life| (life.first, std::cmp::Reverse(life.last), life.value));
let mut active = BTreeSet::<(usize, u32, u32)>::new();
let mut free = BTreeSet::<u32>::new();
let mut pairs = BTreeSet::<u32>::new();
let mut slots = BTreeMap::new();
let mut stride = 1; // Slot zero is always the continuation tag.
for life in lifetimes {
// No slot can be restored and overwritten in the same piece. Restores
// can move after a branch, so the last carrying destination is inclusive.
while active.first().is_some_and(|&(last, _, _)| last < life.first) {
let (_, start, end) = active.pop_first()?;
for word in start..end {
if free.contains(&(word - 1)) {
pairs.insert(word - 1);
}
if free.contains(&(word + 1)) {
pairs.insert(word);
}
free.insert(word);
}
}
let slot = match life.words {
1 => free.first().copied().unwrap_or(stride),
2 => pairs.first().copied().unwrap_or_else(|| {
if free.contains(&(stride - 1)) { stride - 1 } else { stride }
}),
_ => return None,
};
let end = slot.checked_add(life.words)?;
for word in slot..end {
free.remove(&word);
pairs.remove(&word);
pairs.remove(&(word - 1));
}
stride = stride.max(end);
slots.insert(life.value, slot);
active.insert((life.last, slot, end));
}
Some((stride, slots))
}

struct Scratch {
uav: RawUav,
base: Value,
Expand Down Expand Up @@ -105,18 +160,7 @@ impl Shader {
if exchange != 0 { return None; }
}
let plan = self.m.dispatch_plan(limit)?;
// Slot zero is the tag. Every transported SSA value owns its payload slots
// until the chain finishes. An outgoing store can never overwrite a value
// restored by the same piece, even when the restore is sunk past a branch.
let mut stride = 1u32;
let mut slots = BTreeMap::new();
for value in plan.edges.iter().flat_map(|e| e.live.iter().copied()).collect::<BTreeSet<_>>() {
let words = self.m.transport_words(value)?;
if words != 0 {
slots.insert(value, stride);
stride = stride.checked_add(words)?;
}
}
let (stride, slots) = self.m.scratch_slots(&plan)?;
stride.checked_mul(threads[0])?.checked_mul(4)?;
let pieces = (0..plan.blocks.len()).map(|i| self.make_piece(&plan, i, stride, &slots, threads, &prefix)).collect::<Option<Vec<_>>>()?;
Some(DispatchChain { pieces, dwords_per_group: stride.checked_mul(threads[0])? })
Expand Down Expand Up @@ -218,7 +262,7 @@ impl Shader {
let Some(&(b, tag)) = exits.get(&(edge.from, edge.to)) else { continue };
dst.m.set_block(b);
for &v in &edge.live {
// The defining piece writes a distinct slot. Later pieces can bypass
// The defining piece writes its assigned slot. Later pieces can bypass
// it or read it without copying it at their own outgoing edges.
if let Some(&slot) = slots.get(&v) {
if !local.contains_key(&src.def_block[inst(v)?]) { continue; }
Expand Down Expand Up @@ -437,6 +481,48 @@ impl Module {
None
}

fn scratch_slots(&self, plan: &Plan) -> Option<ScratchLayout> {
let mut stages = vec![None; self.blocks.len()];
for (stage, blocks) in plan.blocks.iter().enumerate() {
for &block in blocks {
stages[block.0 as usize] = Some(stage);
}
}
let mut lifetimes = BTreeMap::<Value, PayloadLifetime>::new();
for edge in &plan.edges {
let from = stages[edge.from.0 as usize]?;
let to = stages[edge.to.0 as usize]?;
if from >= to {
return None;
}
for &value in &edge.live {
if let Some(life) = lifetimes.get_mut(&value) {
life.last = life.last.max(to);
continue;
}
let words = self.transport_words(value)?;
if words == 0 {
continue;
}
let definition = self.def_block[inst(value)?];
let first = stages[definition.0 as usize]?;
if first > from {
return None;
}
lifetimes.insert(value, PayloadLifetime { value, first, last: to, words });
}
}

let mut fixed = (1u32, BTreeMap::new());
for life in lifetimes.values() {
fixed.1.insert(life.value, fixed.0);
fixed.0 = fixed.0.checked_add(life.words)?;
}
let compact = reuse_payload_slots(lifetimes.into_values().collect())?;
// Keep the original offsets and emitted DXIL if reuse saves no space.
Some(if compact.0 < fixed.0 { compact } else { fixed })
}

fn transport_words(&self, v: Value) -> Option<u32> {
let def = &self.insts[inst(v)?];
match &self.types[def.ty.0 as usize] {
Expand Down Expand Up @@ -650,6 +736,28 @@ mod tests {
recomp::{runner, CsInterface},
};

#[test]
fn payload_slots_reopen_only_after_the_last_consumer() {
use super::{PayloadLifetime, Value, reuse_payload_slots};

let life = |id, first, last, words| PayloadLifetime {
value: Value::Inst(id), first, last, words,
};
let (stride, slots) = reuse_payload_slots(vec![
life(0, 0, 1, 2),
life(1, 0, 2, 1),
life(2, 1, 2, 1),
life(3, 2, 3, 2),
]).unwrap();
assert_eq!(stride, 5);
// Slot zero stays the continuation tag. On the shared boundary the
// first two-word value is live, so the next value still needs slot four.
assert_eq!(slots[&Value::Inst(1)], 1);
assert_eq!(slots[&Value::Inst(0)], 2);
assert_eq!(slots[&Value::Inst(2)], 4);
assert_eq!(slots[&Value::Inst(3)], 2);
}

#[test]
fn oversized_loop_occupies_one_piece_up_to_the_hard_ceiling() {
use super::{Block, Module};
Expand Down Expand Up @@ -698,8 +806,8 @@ mod tests {
assert!(m.dispatch_plan(4).is_none());
}

fn compare(threads: u32, extra_adds: u32) {
if !runner::wave32_supported().unwrap_or(false) {
fn compare(threads: u32, extra_adds: u32, run_gpu: bool) {
if run_gpu && !runner::wave32_supported().unwrap_or(false) {
runner::skip_test("no wave32 GPU");
return;
}
Expand Down Expand Up @@ -774,11 +882,17 @@ mod tests {
let plan = lw.s.m.dispatch_plan(40).expect("partition around oversized loop");
assert!(plan.blocks.iter().any(|piece| piece == &[oversized]));
}
let chain = lw.s.split_compute(geometry, split.then_some(tid), 40);
let chain = lw.s.split_compute(geometry, split.then_some(tid), 40)
.expect("split the synthetic program");
assert!(chain.pieces.len() >= 3);
if !split && extra_adds == 0 {
assert_eq!(chain.dwords_per_group, 256, "exercise actual Wave32 payload reuse");
}
if !run_gpu {
return;
}
let whole = lw.s.finish_optimized(geometry, Some(32)).unwrap();
crate::gpu::dxil::validate::validate(&whole).expect("valid unsplit fixture");
let chain = chain.expect("split the synthetic program");
assert!(chain.pieces.len() >= 3);
let initial: Vec<_> = (1..=threads * 3).collect();
let expected: Vec<_> = initial.iter().enumerate().map(|(i, &v)| {
let n = (i as u32 % 4) + 1;
Expand Down Expand Up @@ -917,15 +1031,18 @@ mod tests {
fn dispatch_chain_payload_survives_reused_edge_slot() { check_persistent_payload(true); }

#[test]
fn dispatch_chain_wave32_live_loops() { compare(32, 0); }
fn dispatch_chain_wave32_live_loops() { compare(32, 0, true); }

#[test]
fn dispatch_chain_wave32_reuses_scratch_before_gpu_run() { compare(32, 0, false); }

/// A guest wave64 split across two hardware wave32s.
#[test]
fn dispatch_chain_wave64_live_loops_and_exchange() { compare(64, 0); }
fn dispatch_chain_wave64_live_loops_and_exchange() { compare(64, 0, true); }
#[test]
fn dispatch_chain_oversized_loop_matches_whole() {
compare(32, 48);
compare(64, 48);
compare(32, 48, true);
compare(64, 48, true);
}

/// Early exits and forward skips retain their own continuation tags; group
Expand Down
Loading