From f296ca8ff351e425d084c312c7eef86c57878c0a Mon Sep 17 00:00:00 2001 From: Zondy <292338413+zondy1i@users.noreply.github.com> Date: Wed, 25 Nov 2026 18:21:56 +0800 Subject: [PATCH] dxil: fix alloca align=0, live double/TGSM metadata, and heap raw buffer flag (#1894) --- crates/xcl/src/gpu/dxil/graphics.rs | 2 +- crates/xcl/src/gpu/dxil/graphics_tests.rs | 45 +++++++++++ crates/xcl/src/gpu/dxil/module.rs | 98 ++++++++++++++--------- crates/xcl/src/gpu/dxil/shader.rs | 1 - crates/xcl/src/gpu/dxil/tests.rs | 72 +++++++++++++++++ 5 files changed, 180 insertions(+), 38 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/graphics.rs b/crates/xcl/src/gpu/dxil/graphics.rs index 2856283962..0e7c77c59e 100644 --- a/crates/xcl/src/gpu/dxil/graphics.rs +++ b/crates/xcl/src/gpu/dxil/graphics.rs @@ -1152,7 +1152,7 @@ impl Shader { as u8; } StageInfo::Mesh { max_vertices, max_primitives, topology, payload_bytes, .. } => { - let groupshared_bytes = self.m.global_bytes_layout(3, native16) as u32; + let groupshared_bytes = self.m.live_global_bytes_layout(3, native16) as u32; stage_info[0..4].copy_from_slice(&groupshared_bytes.to_le_bytes()); stage_info[8..12].copy_from_slice(&payload_bytes.to_le_bytes()); stage_info[12..14].copy_from_slice(&(max_vertices as u16).to_le_bytes()); diff --git a/crates/xcl/src/gpu/dxil/graphics_tests.rs b/crates/xcl/src/gpu/dxil/graphics_tests.rs index c8f3802053..5a08301f34 100644 --- a/crates/xcl/src/gpu/dxil/graphics_tests.rs +++ b/crates/xcl/src/gpu/dxil/graphics_tests.rs @@ -1146,6 +1146,51 @@ fn groupshared_bytes_follow_the_16bit_layout() { assert_eq!(s.m.global_bytes(3), 36); } +/// Stripped (unreferenced) TGSM globals must not be counted in a mesh shader's PSV0 +/// `groupshared_bytes` field. +#[test] +fn mesh_psv0_excludes_stripped_groupshared_globals() { + let mut s = Shader::new(Stage::Mesh, (6, 6)); + let mut io = GraphicsIo::new(Stage::Mesh); + let pos = io.output(SigElement::new("SV_Position", 0, SemKind::Position, CompType::F32, 4)); + let i32 = s.m.i32(); + let live_ty = s.m.array(4, i32); // 16 B + let dead_ty = s.m.array(16, i32); // 64 B (never referenced -> stripped from bitcode) + let live_g = s.m.global("live_tgsm", live_ty, 3, None, false, 4); + let _dead_g = s.m.global("dead_tgsm", dead_ty, 3, None, false, 4); + let tid = s.thread_id_in_group(0); + let zero = s.m.i32c(0); + let one = s.m.i32c(1); + let two = s.m.i32c(2); + let three = s.m.i32c(3); + io.set_mesh_output_counts(&mut s, three, one); + let p = s.m.gep_fields(live_g, &[zero, tid]); + s.m.store(p, tid, 4); + let v = s.m.load(p, 4); + let f32 = s.m.f32(); + let vf = s.m.cast(crate::gpu::dxil::module::CastOp::SIToFP, v, f32); + let f1 = s.m.f32c(1.0f32.to_bits()); + for (c, val) in [vf, vf, vf, f1].into_iter().enumerate() { + io.store_vertex_output(&mut s, pos, 0, c as u8, val, tid); + } + let first = s.m.cmp(Pred::Eq, tid, zero); + let (bp, end) = (s.m.new_block(), s.m.new_block()); + s.m.cond_br(first, bp, end); + s.m.set_block(bp); + io.emit_indices(&mut s, zero, &[zero, one, two]); + s.m.br(end); + s.m.set_block(end); + assert_eq!(s.m.global_bytes(3), 80); + assert_eq!(s.m.live_global_bytes_layout(3, false), 16); + + let info = StageInfo::Mesh { numthreads: [3, 1, 1], max_vertices: 3, max_primitives: 1, topology: Topology::Triangle, payload_bytes: 0 }; + let c = s.finish_graphics(io, info); + assert_valid(&c); + let psv = part(&c, b"PSV0").unwrap(); + let groupshared_bytes = u32::from_le_bytes(psv[4..8].try_into().unwrap()); + assert_eq!(groupshared_bytes, 16); +} + const DXC_CS_RESOURCES: &[u8] = include_bytes!("../../../../../tests/data/dxil/dxc_cs_resources.dxil"); const DXC_PS_RESOURCES: &[u8] = include_bytes!("../../../../../tests/data/dxil/dxc_ps_resources.dxil"); diff --git a/crates/xcl/src/gpu/dxil/module.rs b/crates/xcl/src/gpu/dxil/module.rs index f2930cd7e0..b94adc115a 100644 --- a/crates/xcl/src/gpu/dxil/module.rs +++ b/crates/xcl/src/gpu/dxil/module.rs @@ -817,34 +817,7 @@ impl Module { // Global variables nothing references (e.g. an exchange array the code never // needed) are left out: the validator rejects unused internal declarations. // Likewise declarations of functions no longer called (after `optimize`). - let mut gused = vec![false; self.globals.len()]; - let mut fused: Vec = self.funcs.iter().map(|f| f.defined).collect(); - { - let mut mark = |v: Value| match v { - Value::Global(g) => gused[g as usize] = true, - Value::Func(f) => fused[f as usize] = true, - _ => {} - }; - for &b in &order { - for &i in &self.blocks[b] { - let op = &self.insts[i as usize].op; - if let Op::Call(f, _) = op { - mark(Value::Func(*f)); - } - op.for_each_operand(&mut mark); - } - } - for c in &self.consts { - if let ConstDef::Aggregate(_, e) = c { - e.iter().copied().for_each(&mut mark); - } - } - for m in &self.md { - if let MdDef::Val(_, v) = m { - mark(*v); - } - } - } + let (gused, fused) = self.live_decls(&order); let mut gmap: Vec> = vec![None; self.globals.len()]; let mut n_globals = 0u64; for (g, used) in gused.iter().enumerate() { @@ -1073,6 +1046,9 @@ impl Module { /// block's position in it (`None`: unreachable, not written). fn block_layout(&self) -> (Vec, Vec>) { let n = self.blocks.len(); + if n == 0 { + return (Vec::new(), Vec::new()); + } let mut seen = vec![false; n]; let mut post = Vec::with_capacity(n); // Iterative DFS; successors pushed so that earlier-created ones are visited @@ -1237,7 +1213,7 @@ impl Module { Op::Alloca(t, n, align) => { // [instty, opty, size (absolute value id), align record (log2 + 1 | explicit type)] let i32t = self.value_ty(*n); - let a = align.trailing_zeros() as u64 + 1; + let a = if *align == 0 { 0 } else { align.trailing_zeros() as u64 + 1 }; w.record(FUNC_CODE_INST_ALLOCA, &[t.0 as u64, i32t.0 as u64, abs(*n), a | 1 << 6]) } Op::Br(b) => w.record(FUNC_CODE_INST_BR, &[bb(*b)]), @@ -1403,15 +1379,20 @@ impl Module { /// integers (DXC's shader-flag rules; `Fma` is flagged by its helper). pub fn uses_double_extensions(&self) -> bool { let Some(f64) = self.type_ids.get(&TypeDef::Double).copied() else { return false }; - self.insts.iter().any(|d| match &d.op { - Op::Bin(BinOp::UDiv | BinOp::SDiv, ..) => d.ty == f64, - Op::Cast(CastOp::FPToUI | CastOp::FPToSI, v, _) => self.value_ty(*v) == f64, - Op::Cast(CastOp::UIToFP | CastOp::SIToFP, _, t) => *t == f64, - _ => false, + let (order, _) = self.block_layout(); + order.into_iter().flat_map(|b| self.blocks[b].iter()).any(|&i| { + let d = &self.insts[i as usize]; + match &d.op { + Op::Bin(BinOp::UDiv | BinOp::SDiv, ..) => d.ty == f64, + Op::Cast(CastOp::FPToUI | CastOp::FPToSI, v, _) => self.value_ty(*v) == f64, + Op::Cast(CastOp::UIToFP | CastOp::SIToFP, _, t) => *t == f64, + _ => false, + } }) } pub fn insts_use_type(&self, t: Ty) -> bool { - self.blocks.iter().flatten().any(|&i| { + let (order, _) = self.block_layout(); + order.into_iter().flat_map(|b| self.blocks[b].iter()).any(|&i| { let d = &self.insts[i as usize]; if d.ty == t { return true; @@ -1429,7 +1410,8 @@ impl Module { } /// True if any surviving `dx.op.annotateHandle` call carries the `IsROV` flag (`0x2000`). pub fn has_rov_handle(&self) -> bool { - self.blocks.iter().flatten().any(|&i| { + let (order, _) = self.block_layout(); + order.into_iter().flat_map(|b| self.blocks[b].iter()).any(|&i| { let Op::Call(f, args) = &self.insts[i as usize].op else { return false }; if self.funcs[*f as usize].name != "dx.op.annotateHandle" || args.len() < 3 { return false; @@ -1514,6 +1496,38 @@ impl Module { _ => (0, 1), } } + /// Which globals and functions are referenced by reachable instructions, constants, or + /// metadata (the exact set emitted into bitcode). + fn live_decls(&self, order: &[usize]) -> (Vec, Vec) { + let mut gused = vec![false; self.globals.len()]; + let mut fused: Vec = self.funcs.iter().map(|f| f.defined).collect(); + let mut mark = |v: Value| match v { + Value::Global(g) => gused[g as usize] = true, + Value::Func(f) => fused[f as usize] = true, + _ => {} + }; + for &b in order { + for &i in &self.blocks[b] { + let op = &self.insts[i as usize].op; + if let Op::Call(f, _) = op { + mark(Value::Func(*f)); + } + op.for_each_operand(&mut mark); + } + } + for c in &self.consts { + if let ConstDef::Aggregate(_, e) = c { + e.iter().copied().for_each(&mut mark); + } + } + for m in &self.md { + if let MdDef::Val(_, v) = m { + mark(*v); + } + } + (gused, fused) + } + /// Total allocation size of the global variables in `addrspace` /// (3: thread-group shared memory). pub fn global_bytes(&self, addrspace: u32) -> u64 { @@ -1523,4 +1537,16 @@ impl Module { pub fn global_bytes_layout(&self, addrspace: u32, native16: bool) -> u64 { self.globals.iter().filter(|g| g.addrspace == addrspace).map(|g| self.alloc_size_layout(g.ty, native16)).sum() } + /// Like [`Module::global_bytes_layout`], counting only globals referenced by reachable code + /// (matching the globals actually emitted into bitcode). + pub fn live_global_bytes_layout(&self, addrspace: u32, native16: bool) -> u64 { + let (order, _) = self.block_layout(); + let (gused, _) = self.live_decls(&order); + self.globals + .iter() + .enumerate() + .filter(|(i, g)| gused[*i] && g.addrspace == addrspace) + .map(|(_, g)| self.alloc_size_layout(g.ty, native16)) + .sum() + } } diff --git a/crates/xcl/src/gpu/dxil/shader.rs b/crates/xcl/src/gpu/dxil/shader.rs index 35f36c319d..de5a1b6a6f 100644 --- a/crates/xcl/src/gpu/dxil/shader.rs +++ b/crates/xcl/src/gpu/dxil/shader.rs @@ -317,7 +317,6 @@ impl Shader { /// A `RWByteAddressBuffer` from `ResourceDescriptorHeap[NonUniformResourceIndex(index)]`, /// `globallycoherent` if `coherent` (the heap memory windows). pub fn heap_raw_buffer_uav(&mut self, index: Value, coherent: bool) -> RawUav { - self.require(Feature::RawAndStructuredBuffers); let h = self.handle_from_heap(index, false, true); // resource properties: IsUAV (bit 12) | IsGloballyCoherent (bit 14) let handle = self.annotate(h, kind::RAW_BUFFER | 0x1000 | if coherent { 0x4000 } else { 0 }, 0); diff --git a/crates/xcl/src/gpu/dxil/tests.rs b/crates/xcl/src/gpu/dxil/tests.rs index af8d2e960e..a23b5744f8 100644 --- a/crates/xcl/src/gpu/dxil/tests.rs +++ b/crates/xcl/src/gpu/dxil/tests.rs @@ -216,3 +216,75 @@ fn batched_replacements_match_one_at_a_time() { panic!("validator rejected the kernel:\n{e}"); } } + +/// Dead or unreachable f64 extension ops must not leave `Feature::DoubleExtensions` set +/// after `optimize()`, or the DXIL validator rejects the mismatched shader flags. +#[test] +fn dead_double_extension_does_not_set_feature_flag() { + let mut s = Shader::new(Stage::Compute, (6, 6)); + let res = s.raw_uav(0, 0); + let lane = s.thread_id_in_group(0); + let f64 = s.m.f64(); + // Dead cast in the entry block (eliminated by DCE). + let _dead = s.m.cast(super::module::CastOp::UIToFP, lane, f64); + let two = s.m.i32c(2); + let off = s.m.bin(BinOp::Shl, lane, two); + s.raw_store(res, off, &[lane]); + s.m.ret(); + // Unreachable block with an f64 division (dropped by `block_layout`). + let unreach = s.m.new_block(); + s.m.set_block(unreach); + let d1 = s.m.cast(super::module::CastOp::UIToFP, lane, f64); + let _div = s.m.bin(BinOp::SDiv, d1, d1); + s.m.ret(); + + let c = s.finish([64, 1, 1], None); + if validate::validator_supported() { + validate::validate(&c).unwrap_or_else(|e| panic!("validator rejected dead f64 shader:\n{e}")); + } +} + +/// `Op::Alloca` with `align == 0` encodes default alignment (0), never `inalloca` (bit 5). +#[test] +fn alloca_with_default_align_zero_validates_without_inalloca() { + let mut s = Shader::new(Stage::Compute, (6, 6)); + let res = s.raw_uav(0, 0); + let lane = s.thread_id_in_group(0); + let i32 = s.m.i32(); + let slot = s.m.alloca(i32, 0); + s.m.store(slot, lane, 0); + let v = s.m.load(slot, 0); + let two = s.m.i32c(2); + let off = s.m.bin(BinOp::Shl, lane, two); + s.raw_store(res, off, &[v]); + + let c = s.finish([64, 1, 1], None); + if validate::validator_supported() { + validate::validate(&c).unwrap_or_else(|e| panic!("validator rejected align=0 alloca:\n{e}")); + } + if let Ok(dis) = validate::disassemble(&c) { + assert!(!dis.contains("inalloca"), "align=0 alloca set inalloca bit:\n{dis}"); + assert!(dis.contains("alloca i32"), "expected alloca i32 in disassembly:\n{dis}"); + } +} + +/// Heap-indexed raw buffers (`createHandleFromHeap` + `annotateHandle`) do not set the bound +/// `Feature::RawAndStructuredBuffers` flag; setting it on a shader with no bound raw/structured +/// resources makes the DXIL validator reject mismatched flags. +#[test] +fn heap_raw_buffer_uav_does_not_set_spurious_raw_buffer_flag() { + for use_uav_helper in [false, true] { + let mut s = Shader::new(Stage::Compute, (6, 6)); + let zero = s.m.i32c(0); + let buf = if use_uav_helper { s.heap_raw_buffer_uav(zero, false) } else { s.heap_raw_buffer(zero, true, false) }; + let lane = s.thread_id_in_group(0); + let two = s.m.i32c(2); + let off = s.m.bin(BinOp::Shl, lane, two); + s.raw_store(buf, off, &[lane]); + + let c = s.finish([64, 1, 1], None); + if validate::validator_supported() { + validate::validate(&c).unwrap_or_else(|e| panic!("validator rejected heap raw buffer (uav_helper={use_uav_helper}):\n{e}")); + } + } +}