Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
63f8eaa
xshader: accept inline accumulators for unsigned MAD
smith-3 Nov 25, 2026
1c0fd26
xshader: saturate packed integer conversions
smith-3 Nov 25, 2026
4a02f49
xshader: implement signed integer clamp controls
smith-3 Nov 25, 2026
c59e0a5
xshader: preserve carry flags and handle discarded carry outputs
smith-3 Nov 25, 2026
e06222c
xshader: handle unsigned no-carry saturation
smith-3 Nov 25, 2026
7f1fa7b
xshader: saturate 24-bit products after accumulation
smith-3 Nov 25, 2026
6f97e34
xshader: handle readfirstlane with an empty execution mask
smith-3 Nov 25, 2026
bde2fbf
xshader: validate scalar selectors for partial-wave lane reads
smith-3 Nov 25, 2026
259f3fd
xshader: recognize commuted descriptor stride setup
smith-3 Nov 25, 2026
96947c5
xshader: resolve corroborated UAV stores beyond SRV tables
smith-3 Nov 25, 2026
b2ebf74
d3d12: respect pipeline root overrides on embedded mesh roots
smith-3 Nov 25, 2026
e0f3e07
xshader: translate subword ALU and 24-bit products in ray continuations
smith-3 Nov 25, 2026
69ef67a
xshader: preserve full-range float-to-integer conversion semantics
smith-3 Nov 25, 2026
f76fd34
xshader: round midpoints toward positive infinity for RPI
smith-3 Nov 25, 2026
8bff734
xshader: honor guest modes for fractional and half operations
smith-3 Nov 25, 2026
d2857d9
xshader: track floating-point mode and conversion exceptions
smith-3 Nov 25, 2026
3a2f553
xshader: apply SDWA source and result controls before packing
smith-3 Nov 25, 2026
e1c3d80
xshader: permute the first source of DPP16 subtraction
smith-3 Nov 25, 2026
523b484
xshader: lower quad exchanges for integer and floating-point operations
smith-3 Nov 25, 2026
68d2e7c
xshader: honor source and destination masks for DPP row operations
smith-3 Nov 25, 2026
b456d1a
xshader: track execution-mask snapshots across lane elections
smith-3 Nov 25, 2026
16effc0
xshader: reconcile shared half constants and masked quad writes
smith-3 Nov 25, 2026
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
72 changes: 70 additions & 2 deletions runtime/d3d12/src/device/shader_cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,64 @@ fn with_root(shader: &[u8], root: &[u8]) -> Option<Vec<u8>> {
Some(input)
}

fn replace_mesh_root(
shader: &[u8],
root: &[u8],
dxbc: &tuxbox_dxbc::Dxbc,
embedded: &tuxbox_dxbc::Chunk,
) -> Option<Vec<u8>> {
// Shift subsequent parts by a multiple of four, even for unaligned payload lengths.
let padding = (embedded.size % 4 + 4 - root.len() % 4) % 4;
let span = root.len().checked_add(padding)?;
let size = (shader.len() - embedded.size).checked_add(span)?;
if size > MAX_BYTES || root.is_empty() { return None; }
let mut input = Vec::with_capacity(size);
input.extend_from_slice(&shader[..embedded.offset - 4]);
input[4..20].fill(0);
input[24..28].copy_from_slice(&(size as u32).to_le_bytes());
for (index, part) in dxbc.chunks.iter().enumerate() {
if part.offset > embedded.offset {
let offset = part.offset - 8 - embedded.size + span;
input[32 + 4 * index..36 + 4 * index].copy_from_slice(&(offset as u32).to_le_bytes());
}
}
input.extend_from_slice(&(root.len() as u32).to_le_bytes());
input.extend_from_slice(root);
input.resize(embedded.offset + span, 0);
input.extend_from_slice(&shader[embedded.offset + embedded.size..]);
Some(input)
}

#[cfg(test)]
#[test]
fn replacing_a_mesh_root_preserves_the_other_parts_and_the_directory_order() {
use tuxbox_dxbc::Dxbc;
fn words(values: &[u32]) -> Vec<u8> {
values.iter().flat_map(|v| v.to_le_bytes()).collect()
}
let empty = words(&[1, 0, 0, 0, 0, 0]);
let constants = words(&[1, 1, 24, 0, 0, 0, 1, 7, 36, 1, 0, 4]);
// The root is first on disk and last in the directory.
let mut shader = Vec::from(*b"DXBC");
shader.extend_from_slice(&[1; 16]);
shader.extend(words(&[1, 84, 2, 72, 40]));
shader.extend_from_slice(b"RTS0");
shader.extend(words(&[24]));
shader.extend_from_slice(&empty);
shader.extend_from_slice(b"DXIL");
shader.extend(words(&[4, 0xd0065]));
for expected in [&constants, &empty] {
let dxbc = Dxbc::parse(&shader).unwrap();
shader = replace_mesh_root(&shader, expected, &dxbc, dxbc.chunk(b"RTS0").unwrap()).unwrap();
let parsed = Dxbc::parse(&shader).unwrap();
assert_eq!(parsed.digest, [0; 16]);
let [code, root] = parsed.chunks.as_slice() else { panic!("expected two parts") };
assert_eq!((code.fourcc, root.fourcc), (*b"DXIL", *b"RTS0"));
assert_eq!(&shader[code.offset..code.offset + code.size], 0xd0065u32.to_le_bytes());
assert_eq!(&shader[root.offset..root.offset + root.size], expected);
}
}

/// Console mesh stages always use a DXIL container. Resolve stripped programs
/// before the host call and require portable replacements to match the stage.
pub(super) fn mesh_stage(
Expand All @@ -354,10 +412,19 @@ pub(super) fn mesh_stage(
match shader_code(shader) {
Some((stage, ShaderCode::Portable)) if stage == expected => Ok(None),
Some((stage, ShaderCode::Xbox)) if stage == expected => {
let rooted = root.and_then(|root| with_root(shader, root));
let Some(rooted) = rooted else {
let Some(root) = root else {
return translate(shader, stage).map(Some).ok_or(E_NOTIMPL);
};
let dxbc = tuxbox_dxbc::Dxbc::parse(shader).map_err(|_| E_INVALIDARG)?;
if let Some(embedded) = dxbc.chunk(b"RTS0") {
if &shader[embedded.offset..embedded.offset + embedded.size] == root {
return translate(shader, stage).map(Some).ok_or(E_NOTIMPL);
}
// A PSO root overrides the embedded layout. A replacement keyed only
// by the original shader would resolve registers against the wrong root.
let variant = replace_mesh_root(shader, root, &dxbc, embedded).ok_or(E_INVALIDARG)?;
return translate(&variant, stage).map(Some).ok_or(E_NOTIMPL);
}
// Preserve explicit precompiled replacements indexed by the
// original bytecode. On-demand answers include the pipeline root.
if let Some(source) = source_digest(shader)
Expand All @@ -366,6 +433,7 @@ pub(super) fn mesh_stage(
stage.report(&source, true);
return Ok(Some(compiled));
}
let rooted = with_root(shader, root).ok_or(E_INVALIDARG)?;
translate(&rooted, stage).map(Some).ok_or(E_NOTIMPL)
}
_ => Err(E_INVALIDARG),
Expand Down
73 changes: 73 additions & 0 deletions tests/test_float_to_integer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import os
from pathlib import Path
import re
import shutil
import struct
import subprocess
from tempfile import TemporaryDirectory
import unittest

from tools.reference.scarlett_worker_fixture import container, pack


def native_shader(code):
shader = container(code, resources=[(7, 0, 0, 0)])
# Extend the fixture's two-chunk directory with a root table for UAV u0.
root = b"RTS0" + pack([64, 1, 1, 24, 0, 0, 0, 0, 0, 36, 1, 44, 1, 1, 0, 0, 0])
first, second = struct.unpack_from("<II", shader, 32)
root_at = len(shader) + 4
directory = pack([root_at + len(root), 3, first + 4, second + 4, root_at])
return shader[:24] + directory + shader[first:] + root


class FloatToIntegerTests(unittest.TestCase):
def test_rounding_at_half_and_integral_boundaries(self):
self.check_conversion(0x7e0818ff, [
(0x3effffff, 0), (0x3f000000, 1), (0xbf000000, 0),
(0xbf000001, -1), (0xbfc00000, -1), (0x40200000, 3),
(0x4b000001, 8388609), (0xcb000001, -8388609),
])

def test_saturating_signed_and_unsigned_conversion(self):
# gfx1030 V_CVT_I32_F32 and V_CVT_U32_F32. The expected bits include
# the largest representable f32 below each positive integer boundary.
cases = [
(0x4effffff, 0x7fffff80, 0x7fffff80),
(0x4f000000, 0x7fffffff, 0x80000000),
(0x4f7fffff, 0x7fffffff, 0xffffff00),
(0x4f800000, 0x7fffffff, 0xffffffff),
(0xcf000001, 0x80000000, 0),
(0x7f800000, 0x7fffffff, 0xffffffff),
(0xff800000, 0x80000000, 0),
(0x7fc00001, 0, 0), (0xff800001, 0, 0),
(0xbfffffff, -1, 0), (0x3fffffff, 1, 1),
]
self.check_conversion(0x7e0810ff, [(bits, s) for bits, s, _ in cases])
self.check_conversion(0x7e080eff, [(bits, u) for bits, _, u in cases])

def check_conversion(self, instruction, cases):
xshader = os.environ.get("TUXBOX_XSHADER") or shutil.which("xshader")
dxc = os.environ.get("DXC") or shutil.which("dxc")
if not (xshader and dxc):
self.skipTest("set TUXBOX_XSHADER and DXC to run the native rounding check")

# gfx1030: load the UAV descriptor, convert a literal, store v4 at lane * 4.
load = [0xf4080402, 0xfa000000, 0xbf8cc07f]
store = [0x340a0082, 0xe0701000, 0x80040405, 0xbf810000]
with TemporaryDirectory() as directory:
trial = Path(directory)
for bits, expected in cases:
with self.subTest(instruction=hex(instruction), bits=hex(bits)):
code = load + [instruction, bits] + store
(trial / "native.dxbc").write_bytes(native_shader(code))
for command in (
[xshader, trial / "native.dxbc", "--hlsl-out", trial / "shader.hlsl"],
[dxc, "-T", "cs_6_0", "-E", "main", "-Fc", trial / "shader.ll",
"-Fo", trial / "shader.cso", trial / "shader.hlsl"],
):
result = subprocess.run(command, capture_output=True, text=True, timeout=30)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
# DXC folds the conversion before the shader writes its only output.
ir = (trial / "shader.ll").read_text()
values = re.findall(r"call void @dx\.op\.bufferStore\.i32\([^\n]+?, i32 undef, i32 (-?\d+),", ir)
self.assertEqual([int(value) & 0xffffffff for value in values], [expected & 0xffffffff])
49 changes: 49 additions & 0 deletions tests/test_fp16_overflow.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
"""Check the final register values of synthetic V_CVT_F16_F32 programs."""
import os
from pathlib import Path
import shutil
import subprocess
from tempfile import TemporaryDirectory
import unittest

from tools.check_packed_integer_cpu import parse_stores
from tools.reference.scarlett_worker_fixture import container


class HalfOverflowTests(unittest.TestCase):
def test_finite_overflow_and_infinity(self):
compiler = os.environ.get("TUXBOX_XSHADER") or shutil.which("xshader")
dxc = os.environ.get("DXC") or shutil.which("dxc")
if not (compiler and dxc):
self.skipTest("set TUXBOX_XSHADER and DXC to compile the synthetic shader")

cases = [
(0, 0x47800000, 0x7c00), # 65536
(1, 0x47800000, 0x7bff),
(1, 0xc7800000, 0xfbff),
(1, 0x7f800000, 0x7c00), # infinity
(1, 0xff800000, 0xfc00),
(1, 0x477ff000, 0x7bff), # exact nearest-even overflow threshold
(0, 0x477ff000, 0x7c00),
]
code, stores, expected = [], [], []
for index, (flag, source, half) in enumerate(cases):
dest = (index + 4) << 17
tag = (0xab00 + index) << 16
# Set MODE.FP16_OVFL, seed the destination and convert a literal.
code.extend([0xba8005c1, flag, 0x7e0002ff | dest, tag,
0x7e0014ff | dest, source])
stores.append(f"observed[{index}] = v{index + 4};")
expected.append(tag | half)

with TemporaryDirectory() as name:
directory = Path(name)
shader, hlsl, listing = (directory / f for f in ("input.dxbc", "shader.hlsl", "shader.ll"))
shader.write_bytes(container(code + [0xbf810000]))
subprocess.run([compiler, shader, "--hlsl-out", hlsl], check=True, timeout=30)
body = hlsl.read_text().rstrip().removesuffix("}")
hlsl.write_text("RWStructuredBuffer<uint> observed : register(u0);\n"
+ body + "\n" + "\n".join(stores) + "\n}\n")
subprocess.run([dxc, "-E", "main", "-T", "cs_6_0", "-Fc", listing,
"-Fo", directory / "shader.cso", hlsl], check=True, timeout=30)
self.assertEqual(parse_stores(listing.read_text(), len(cases)), expected)
40 changes: 40 additions & 0 deletions tests/test_fract_f32.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import os
from pathlib import Path
import re
import shutil
import subprocess
from tempfile import TemporaryDirectory
import unittest


class FractF32Tests(unittest.TestCase):
def test_tiny_inputs_and_guest_denormal_modes(self):
dxc = os.environ.get("DXC") or shutil.which("dxc")
if not dxc:
self.skipTest("DXC is required for the HLSL numerical regression")
cases = [
# Input bits, MODE register, expected result bits.
(0xb3000000, 0, 0x3f7fffff), (0xb2ffffff, 0, 0x3f7fffff),
(0xb4000000, 0, 0x3f7ffffe), (0x33000000, 0, 0x33000000),
(0xbfa00000, 0, 0x3f400000), (0x80000000, 0, 0),
(0x80000001, 0, 0), (0x80000001, 0x10, 0x3f7fffff),
(0x80000001, 0x20, 0), (0x80000001, 0x30, 0x3f7fffff),
(1, 0x10, 0), (1, 0x20, 0), (1, 0x30, 1),
]
helpers = Path(__file__).resolve().parents[1] / "tools/shader-compiler/src"
with TemporaryDirectory() as directory:
shader = Path(directory) / "test.hlsl"
code = ['#include "fract_f32.hlsl"', 'uint main() : SV_Target { uint result = 0u;']
for i, (bits, mode, expected) in enumerate(cases):
code.append(f"result |= uint(asuint(tb_fract_f32(asfloat({bits:#x}u), {mode}u))"
f" == {expected:#x}u) << {i};")
shader.write_text("\n".join([*code, "return result; }"]))
ir = shader.with_suffix(".ll")
process = subprocess.run([dxc, "-T", "ps_6_0", "-E", "main", "-I", helpers,
"-Fo", shader.with_suffix(".cso"), "-Fc", ir, shader],
capture_output=True, text=True, timeout=30)
self.assertEqual(process.returncode, 0, process.stderr)
output = re.search(r"call void @dx\.op\.storeOutput\.i32\([^\n]+i32 (\d+)\)", ir.read_text())
self.assertIsNotNone(output, "expected one constant pixel output")
mask = int(output.group(1))
self.assertEqual([case for i, case in enumerate(cases) if not mask & (1 << i)], [])
Loading
Loading