From 548a5909bb1214c5827cd4b3fa5f795a3ae3b3c0 Mon Sep 17 00:00:00 2001 From: John Reed <87283488+JohnReedV@users.noreply.github.com> Date: Thu, 26 Nov 2026 14:55:31 -0800 Subject: [PATCH 1/7] docs(todo): claim pipeline worker stack overflow --- TODO.md | 1 + 1 file changed, 1 insertion(+) diff --git a/TODO.md b/TODO.md index 0a40a61d0..19ab01441 100644 --- a/TODO.md +++ b/TODO.md @@ -47,6 +47,7 @@ The goal: a console-like experience on PC. The game starts straight into play, h | S-1 | One device loss with indirect draw windows on (`LEONIDA_INDIRECT_WINDOW=1`), 44 s into the world. Cause not found. Don't combine it with `LEONIDA_CARD_FETCH_INFLIGHT=1`. | `leonida-gpu` | game, GPU | | S-2 | A session past the first rooms lost the device in the open world with no driver entry ("device removed"). | `leonida-gpu` | game, GPU | | S-3 | Menu frame pacing drifts on one screen in release builds. | `leonida-gpu` | game, GPU | +| S-5 | Pipeline workers overflow their 2 MiB thread stacks while the first world loads (four workers in each of two Linux runs). Find the cause and keep pipeline compilation running. | `leonida-gpu` | game, GPU | ## Audio, input and system services From 289507014eda7a0f5b64205f591056cc483d59b6 Mon Sep 17 00:00:00 2001 From: John Reed <87283488+JohnReedV@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:02:12 -0800 Subject: [PATCH 2/7] fix(gpu): give pipeline workers enough stack --- crates/leonida-gpu/src/pipeline/make.rs | 31 +++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/crates/leonida-gpu/src/pipeline/make.rs b/crates/leonida-gpu/src/pipeline/make.rs index 40e82143f..4c41e14ab 100644 --- a/crates/leonida-gpu/src/pipeline/make.rs +++ b/crates/leonida-gpu/src/pipeline/make.rs @@ -542,11 +542,21 @@ fn workers() -> bool { }) } +/// Shader translation and the host compiler exhausted the default 2 MiB +/// thread stack during the first world load. Reserve more stack only for +/// these workers; Windows commits the pages as they are used. +const PIPELINE_WORKER_STACK: usize = 8 * 1024 * 1024; + +fn worker_builder(slot: usize) -> std::thread::Builder { + std::thread::Builder::new() + .name(format!("leonida-pipelines-{slot}")) + .stack_size(PIPELINE_WORKER_STACK) +} + /// Starts one pipeline worker. fn spawn_worker() -> bool { let slot = NEXT_SLOT.fetch_add(1, Ordering::Relaxed); - let spawned = std::thread::Builder::new() - .name(format!("leonida-pipelines-{slot}")) + let spawned = worker_builder(slot) .spawn(move || { WORKER_SLOT.set(slot); // Below the title's own threads (loading, recording). @@ -600,6 +610,23 @@ fn drained() { mod tests { use super::*; + /// Ask Windows for the stack it actually gave a pipeline worker. The + /// default 2 MiB stack is too small for some world pipelines. + #[test] + fn pipeline_worker_has_room_for_large_compiles() { + use windows::Win32::System::Threading::GetCurrentThreadStackLimits; + + let worker = worker_builder(999) + .spawn(|| { + let (mut low, mut high) = (0usize, 0usize); + // SAFETY: both outputs live for the duration of this call. + unsafe { GetCurrentThreadStackLimits(&mut low, &mut high) }; + high - low + }) + .unwrap(); + assert!(worker.join().unwrap() >= 8 * 1024 * 1024); + } + /// A first use queues the pipeline and, within the budget, gets the /// worker's answer (here: no host pipeline for no shaders). #[test] From 03f72cdc72a21dbe19d7095ee1812715c6ab8ee1 Mon Sep 17 00:00:00 2001 From: John Reed <87283488+JohnReedV@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:14:44 -0800 Subject: [PATCH 3/7] Revert "fix(gpu): give pipeline workers enough stack" This reverts commit 289507014eda7a0f5b64205f591056cc483d59b6. --- crates/leonida-gpu/src/pipeline/make.rs | 31 ++----------------------- 1 file changed, 2 insertions(+), 29 deletions(-) diff --git a/crates/leonida-gpu/src/pipeline/make.rs b/crates/leonida-gpu/src/pipeline/make.rs index 4c41e14ab..40e82143f 100644 --- a/crates/leonida-gpu/src/pipeline/make.rs +++ b/crates/leonida-gpu/src/pipeline/make.rs @@ -542,21 +542,11 @@ fn workers() -> bool { }) } -/// Shader translation and the host compiler exhausted the default 2 MiB -/// thread stack during the first world load. Reserve more stack only for -/// these workers; Windows commits the pages as they are used. -const PIPELINE_WORKER_STACK: usize = 8 * 1024 * 1024; - -fn worker_builder(slot: usize) -> std::thread::Builder { - std::thread::Builder::new() - .name(format!("leonida-pipelines-{slot}")) - .stack_size(PIPELINE_WORKER_STACK) -} - /// Starts one pipeline worker. fn spawn_worker() -> bool { let slot = NEXT_SLOT.fetch_add(1, Ordering::Relaxed); - let spawned = worker_builder(slot) + let spawned = std::thread::Builder::new() + .name(format!("leonida-pipelines-{slot}")) .spawn(move || { WORKER_SLOT.set(slot); // Below the title's own threads (loading, recording). @@ -610,23 +600,6 @@ fn drained() { mod tests { use super::*; - /// Ask Windows for the stack it actually gave a pipeline worker. The - /// default 2 MiB stack is too small for some world pipelines. - #[test] - fn pipeline_worker_has_room_for_large_compiles() { - use windows::Win32::System::Threading::GetCurrentThreadStackLimits; - - let worker = worker_builder(999) - .spawn(|| { - let (mut low, mut high) = (0usize, 0usize); - // SAFETY: both outputs live for the duration of this call. - unsafe { GetCurrentThreadStackLimits(&mut low, &mut high) }; - high - low - }) - .unwrap(); - assert!(worker.join().unwrap() >= 8 * 1024 * 1024); - } - /// A first use queues the pipeline and, within the budget, gets the /// worker's answer (here: no host pipeline for no shaders). #[test] From bbb1556a30b1819d6770f02d67dd291aaf33de1a Mon Sep 17 00:00:00 2001 From: John Reed <87283488+JohnReedV@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:15:00 -0800 Subject: [PATCH 4/7] docs(todo): identify S-5 shader control flow cause --- TODO.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/TODO.md b/TODO.md index 19ab01441..0718de3b8 100644 --- a/TODO.md +++ b/TODO.md @@ -47,7 +47,7 @@ The goal: a console-like experience on PC. The game starts straight into play, h | S-1 | One device loss with indirect draw windows on (`LEONIDA_INDIRECT_WINDOW=1`), 44 s into the world. Cause not found. Don't combine it with `LEONIDA_CARD_FETCH_INFLIGHT=1`. | `leonida-gpu` | game, GPU | | S-2 | A session past the first rooms lost the device in the open world with no driver entry ("device removed"). | `leonida-gpu` | game, GPU | | S-3 | Menu frame pacing drifts on one screen in release builds. | `leonida-gpu` | game, GPU | -| S-5 | Pipeline workers overflow their 2 MiB thread stacks while the first world loads (four workers in each of two Linux runs). Find the cause and keep pipeline compilation running. | `leonida-gpu` | game, GPU | +| S-5 | DXIL conversion can recurse without end when a generated loop has more than one back edge per block or header; pipeline workers overflow their stacks and leave pipelines unfinished. Normalize those back edges before writing DXIL. | `leonida-shader` | game, GPU | ## Audio, input and system services From e1bc7555b5a0f3f62dd0ddffa04cc19efd51a652 Mon Sep 17 00:00:00 2001 From: powplusplus <222417016+powplusplus@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:16:54 -0800 Subject: [PATCH 5/7] fix(shader): give each loop header one back edge MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Port of upstream VIctory 364c1bc45c4510d0d07a1e58efaff8644165ded2, itself cherry-picked from d48ec767ba89d27090f6f61d3a9ebfd9f5374def. Reuses Leonida’s nonallocating successors helper. --- crates/leonida-shader/src/emit/bitcode.rs | 112 +++++++++++++++++++++- crates/leonida-shader/src/emit/shader.rs | 1 + 2 files changed, 112 insertions(+), 1 deletion(-) diff --git a/crates/leonida-shader/src/emit/bitcode.rs b/crates/leonida-shader/src/emit/bitcode.rs index 9702cb827..97d289925 100644 --- a/crates/leonida-shader/src/emit/bitcode.rs +++ b/crates/leonida-shader/src/emit/bitcode.rs @@ -5,7 +5,7 @@ //! it is written: functions, then constants (all at module level), then the //! instructions of `main` in block order. -use std::collections::HashMap; +use std::collections::{BTreeMap, HashMap}; pub mod census; pub mod opt; @@ -549,6 +549,75 @@ impl Module { live } + /// Gives every loop header one back edge, as DXC's code has: + /// vkd3d-proton's DXIL conversion keeps one per header, takes any other + /// for a forward edge and then recurses without end over the cycle that + /// makes (in programs with wave shuffles). The back edges of a header + /// with several go through a new block that joins their phi values. + pub fn single_latches(&mut self) { + let n = self.blocks.len(); + if n == 0 { + return; + } + // Depth-first from the entry: an edge to a block still on the stack + // is a back edge (the control flow is reducible). + let mut state = vec![0u8; n]; + let mut stack = vec![(0usize, 0usize)]; + state[0] = 1; + let mut latches: BTreeMap> = BTreeMap::new(); + while let Some(top) = stack.last_mut() { + let (b, k) = *top; + let succ = successors(self.blocks[b].term); + if k < succ.len() { + top.1 += 1; + let t = succ[k]; + match state[t] { + 0 => { + state[t] = 1; + stack.push((t, 0)); + } + 1 => latches.entry(t).or_default().push(b), + _ => {} + } + } else { + state[b] = 2; + stack.pop(); + } + } + for (header, mut from) in latches { + from.sort_unstable(); + from.dedup(); + if from.len() < 2 { + continue; + } + let latch = self.new_block(); + for &b in &from { + let to = |t: usize| if t == header { latch } else { t }; + self.blocks[b].term = match self.blocks[b].term { + Some(Term::Br(t)) => Some(Term::Br(to(t))), + Some(Term::CondBr(c, t, f)) => Some(Term::CondBr(c, to(t), to(f))), + other => other, + }; + } + self.blocks[latch].term = Some(Term::Br(header)); + for id in self.blocks[header].phis.clone() { + let Op::Phi(incoming) = self.insts[id as usize].op.clone() else { + continue; + }; + let ty = self.insts[id as usize].ty; + let (back, mut rest): (Vec<_>, Vec<_>) = + incoming.into_iter().partition(|(_, b)| from.contains(b)); + if back.is_empty() { + continue; + } + let joined = self.phi(latch, ty); + self.set_phi(joined, back); + rest.push((joined, latch)); + self.insts[id as usize].op = Op::Phi(rest); + } + } + } + pub fn write(&self) -> Vec { let mut w = Writer::default(); w.bytes(b"BC\xC0\xDE"); @@ -1204,6 +1273,47 @@ mod tests { assert_eq!(&*successors(Some(Term::CondBr(V::Const(0), 3, 5))), &[3, 5]); } + /// A loop header with two back edges gets one, through a new block that + /// joins what each brings (vkd3d-proton keeps one per header). + #[test] + fn a_header_with_two_back_edges_gets_one() { + let mut m = Module::default(); + let i32t = m.int(32); + let void = m.void(); + let main_ty = m.func_ty(void, vec![]); + m.function("main", main_ty, None, true); + let [entry, head, body, mid, exit] = [(); 5].map(|()| m.new_block()); + let (zero, one, two) = (m.i32(0), m.i32(1), m.i32(2)); + m.terminate(entry, Term::Br(head)); + let p = m.phi(head, i32t); + m.terminate(head, Term::Br(body)); + let x = m.bin(body, Bin::Add, p, one); + let c = m.cmp(body, pred::IULT, x, two); + m.terminate(body, Term::CondBr(c, head, mid)); + let y = m.bin(mid, Bin::Add, x, one); + let d = m.cmp(mid, pred::IULT, y, two); + m.terminate(mid, Term::CondBr(d, head, exit)); + m.terminate(exit, Term::Ret); + m.set_phi(p, vec![(zero, entry), (x, body), (y, mid)]); + m.single_latches(); + let latch = m.blocks.len() - 1; + assert_eq!(&*successors(m.blocks[body].term), &[latch, mid]); + assert_eq!(&*successors(m.blocks[mid].term), &[latch, exit]); + assert_eq!(&*successors(m.blocks[latch].term), &[head]); + let phi = |m: &Module, v: V| match v { + V::Inst(id) => match &m.insts[id as usize].op { + Op::Phi(incoming) => incoming.clone(), + op => panic!("{op:?}"), + }, + v => panic!("{v:?}"), + }; + let incoming = phi(&m, p); + assert_eq!(incoming[0], (zero, entry)); + assert_eq!(incoming[1].1, latch); + assert_eq!(phi(&m, incoming[1].0), [(x, body), (y, mid)]); + assert!(!m.write().is_empty()); + } + /// The written bytes are pinned to what the writer produced before the /// worklist and the reused record buffers. #[test] diff --git a/crates/leonida-shader/src/emit/shader.rs b/crates/leonida-shader/src/emit/shader.rs index e970e6dd6..f3b5ec23d 100644 --- a/crates/leonida-shader/src/emit/shader.rs +++ b/crates/leonida-shader/src/emit/shader.rs @@ -766,6 +766,7 @@ impl Shader { self.m.named_md("dx.shaderModel", vec![sm]); self.m.named_md("dx.entryPoints", vec![entry]); + self.m.single_latches(); let bitcode = self.m.write(); super::bitcode::census::note(&self.m, &bitcode); let mut dxil = Vec::with_capacity(24 + bitcode.len()); From 37cdd20db5bea4f1b350d5a9065aabc906b925aa Mon Sep 17 00:00:00 2001 From: desp Date: Thu, 26 Nov 2026 15:19:30 -0800 Subject: [PATCH 6/7] fix(shader): split competing loop back edges Port of upstream VIctory 91e3bdfd8f57b2917311583a99d676cc56b0c807 by desplmfao. Keeps one back edge per block and prevents empty-latch folding from undoing the split. Co-authored-by: Claude Opus 5.5 --- crates/leonida-shader/src/emit/bitcode.rs | 145 +++++++++++++++++++++- 1 file changed, 139 insertions(+), 6 deletions(-) diff --git a/crates/leonida-shader/src/emit/bitcode.rs b/crates/leonida-shader/src/emit/bitcode.rs index 97d289925..807715d31 100644 --- a/crates/leonida-shader/src/emit/bitcode.rs +++ b/crates/leonida-shader/src/emit/bitcode.rs @@ -554,6 +554,13 @@ impl Module { /// for a forward edge and then recurses without end over the cycle that /// makes (in programs with wave shuffles). The back edges of a header /// with several go through a new block that joins their phi values. + /// + /// It also keeps one back edge per block. A block that branches back to + /// two headers (an inner loop's latch that leaves straight to the outer + /// loop's header, as the console flow's loops do) has its edge to the + /// outer header go through a new block of its own; otherwise dxil-spirv + /// takes that edge for a forward one, and its loop-exit search recurses + /// over the cycle until the process dies. pub fn single_latches(&mut self) { let n = self.blocks.len(); if n == 0 { @@ -564,6 +571,10 @@ impl Module { let mut state = vec![0u8; n]; let mut stack = vec![(0usize, 0usize)]; state[0] = 1; + // When each block was reached: an outer loop's header before its + // inner loops' headers. + let mut reached = vec![0; n]; + let mut next = 1; let mut latches: BTreeMap> = BTreeMap::new(); while let Some(top) = stack.last_mut() { let (b, k) = *top; @@ -574,6 +585,8 @@ impl Module { match state[t] { 0 => { state[t] = 1; + reached[t] = next; + next += 1; stack.push((t, 0)); } 1 => latches.entry(t).or_default().push(b), @@ -584,20 +597,20 @@ impl Module { stack.pop(); } } + // Back edges left as they are: (latch, header). + let mut kept = Vec::new(); for (header, mut from) in latches { from.sort_unstable(); from.dedup(); + if let [b] = from[..] { + kept.push((b, reached[header], header)); + } if from.len() < 2 { continue; } let latch = self.new_block(); for &b in &from { - let to = |t: usize| if t == header { latch } else { t }; - self.blocks[b].term = match self.blocks[b].term { - Some(Term::Br(t)) => Some(Term::Br(to(t))), - Some(Term::CondBr(c, t, f)) => Some(Term::CondBr(c, to(t), to(f))), - other => other, - }; + self.redirect(b, header, latch); } self.blocks[latch].term = Some(Term::Br(header)); for id in self.blocks[header].phis.clone() { @@ -616,6 +629,39 @@ impl Module { self.insts[id as usize].op = Op::Phi(rest); } } + // A block has two successors, so at most one pair per block. The + // edge to the outer header (reached first) is the one moved: the + // block stays the inner loop's latch, the exiting block as in DXC's + // loops. + kept.sort_unstable(); + for pair in kept.windows(2) { + let [(b, _, header), (also, ..)] = *pair else { + unreachable!() + }; + if b != also { + continue; + } + let latch = self.new_block(); + self.redirect(b, header, latch); + self.blocks[latch].term = Some(Term::Br(header)); + for &id in &self.blocks[header].phis { + if let Op::Phi(incoming) = &mut self.insts[id as usize].op { + for (_, from) in incoming.iter_mut().filter(|(_, from)| *from == b) { + *from = latch; + } + } + } + } + } + + /// Makes `b`'s edges to `from` go to `to`. + fn redirect(&mut self, b: usize, from: usize, to: usize) { + let to = |t: usize| if t == from { to } else { t }; + self.blocks[b].term = match self.blocks[b].term { + Some(Term::Br(t)) => Some(Term::Br(to(t))), + Some(Term::CondBr(c, t, f)) => Some(Term::CondBr(c, to(t), to(f))), + other => other, + }; } pub fn write(&self) -> Vec { @@ -785,10 +831,14 @@ impl Module { // An empty latch (only a branch back to its loop header) is folded // into its one predecessor, so the exiting block is the latch as in // DXC's loops; the AMD driver hangs on divergent loops otherwise. + // Not into a block that already branches back: that would undo the + // one back edge per block of `single_latches`. let mut preds = vec![Vec::new(); self.blocks.len()]; + let mut branches_back = vec![false; self.blocks.len()]; for &b in &post { for &s in succs(b).iter() { preds[s].push(b); + branches_back[b] |= pos[s] <= pos[b]; } } let mut fold = vec![None; self.blocks.len()]; @@ -800,8 +850,10 @@ impl Module { &preds[b][..], ) && pos[h] < pos[b] && !succs(*p).contains(&h) + && !branches_back[*p] { fold[b] = Some((*p, h)); + branches_back[*p] = true; } } let layout: Vec = post.into_iter().filter(|&b| fold[b].is_none()).collect(); @@ -1314,6 +1366,87 @@ mod tests { assert!(!m.write().is_empty()); } + /// An inner loop's latch that leaves straight to the outer loop's header + /// branches back to two headers; the edge to the outer one goes through + /// a block of its own (vkd3d-proton keeps one back edge per block). + #[test] + fn a_block_branching_back_to_two_headers_gets_one_back_edge() { + let mut m = Module::default(); + let i32t = m.int(32); + let void = m.void(); + let main_ty = m.func_ty(void, vec![]); + m.function("main", main_ty, None, true); + let [entry, outer, inner, body, exit] = [(); 5].map(|()| m.new_block()); + let (zero, one, two) = (m.i32(0), m.i32(1), m.i32(2)); + m.terminate(entry, Term::Br(outer)); + let o = m.phi(outer, i32t); + let c = m.cmp(outer, pred::IULT, o, two); + m.terminate(outer, Term::CondBr(c, inner, exit)); + let i = m.phi(inner, i32t); + m.terminate(inner, Term::Br(body)); + let x = m.bin(body, Bin::Add, i, one); + let d = m.cmp(body, pred::IULT, x, two); + m.terminate(body, Term::CondBr(d, inner, outer)); + m.terminate(exit, Term::Ret); + m.set_phi(o, vec![(zero, entry), (x, body)]); + m.set_phi(i, vec![(o, outer), (x, body)]); + m.single_latches(); + let latch = m.blocks.len() - 1; + assert_eq!(&*successors(m.blocks[body].term), &[inner, latch]); + assert_eq!(&*successors(m.blocks[latch].term), &[outer]); + let incoming = |v: V| match v { + V::Inst(id) => match &m.insts[id as usize].op { + Op::Phi(incoming) => incoming.clone(), + op => panic!("{op:?}"), + }, + v => panic!("{v:?}"), + }; + assert_eq!(incoming(o), [(zero, entry), (x, latch)]); + assert_eq!(incoming(i), [(o, outer), (x, body)]); + assert!(!m.write().is_empty()); + } + + /// An empty latch is not folded into a block that already branches + /// back: two empty latches after one block, to two headers, keep one. + #[test] + fn empty_latches_to_two_headers_fold_once() { + // `latches`: the inner and outer back edges each through an empty + // block; otherwise only the inner one, the outer one direct. + let build = |latches: bool| { + let mut m = Module::default(); + let i32t = m.int(32); + let void = m.void(); + let fty = m.func_ty(i32t, vec![i32t]); + let f = m.function("source", fty, Some(Attr::NoUnwind), false); + let main_ty = m.func_ty(void, vec![]); + m.function("main", main_ty, None, true); + let [entry, outer, inner, body, exit] = [(); 5].map(|()| m.new_block()); + let two = m.i32(2); + let x = m.call(entry, f, vec![two]); + m.terminate(entry, Term::Br(outer)); + let c = m.cmp(outer, pred::IULT, x, two); + m.terminate(outer, Term::CondBr(c, inner, exit)); + m.terminate(inner, Term::Br(body)); + let d = m.cmp(body, pred::IULT, x, two); + let to_inner = m.new_block(); + m.terminate(to_inner, Term::Br(inner)); + let to_outer = if latches { + let l = m.new_block(); + m.terminate(l, Term::Br(outer)); + l + } else { + outer + }; + m.terminate(body, Term::CondBr(d, to_inner, to_outer)); + m.terminate(exit, Term::Ret); + m.write() + }; + // Folding both would give `body` both back edges. The outer latch + // (first in reverse postorder) folds and the inner one stays, as + // when `body` branches back to `outer` itself. + assert_eq!(build(true), build(false)); + } + /// The written bytes are pinned to what the writer produced before the /// worklist and the reused record buffers. #[test] From 7f45cc2e012f052f8a85f61fb7e7ec044a63c9de Mon Sep 17 00:00:00 2001 From: John Reed <87283488+JohnReedV@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:40:32 -0800 Subject: [PATCH 7/7] docs(todo): complete S-5 shader loop fix --- TODO.md | 1 - 1 file changed, 1 deletion(-) diff --git a/TODO.md b/TODO.md index 0718de3b8..0a40a61d0 100644 --- a/TODO.md +++ b/TODO.md @@ -47,7 +47,6 @@ The goal: a console-like experience on PC. The game starts straight into play, h | S-1 | One device loss with indirect draw windows on (`LEONIDA_INDIRECT_WINDOW=1`), 44 s into the world. Cause not found. Don't combine it with `LEONIDA_CARD_FETCH_INFLIGHT=1`. | `leonida-gpu` | game, GPU | | S-2 | A session past the first rooms lost the device in the open world with no driver entry ("device removed"). | `leonida-gpu` | game, GPU | | S-3 | Menu frame pacing drifts on one screen in release builds. | `leonida-gpu` | game, GPU | -| S-5 | DXIL conversion can recurse without end when a generated loop has more than one back edge per block or header; pipeline workers overflow their stacks and leave pipelines unfinished. Normalize those back edges before writing DXIL. | `leonida-shader` | game, GPU | ## Audio, input and system services