From 5055432943a3e8d43e261136b0f17132bc98ac4d Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Thu, 26 Nov 2026 20:24:59 +0000 Subject: [PATCH 01/11] startup: lower the FP32 box case of image_bvh_intersect_ray --- .../experiments/startup-gfx2hlsl-bvh-box32.md | 61 +++ .../python-linux/startup_gfx2hlsl_bvh.txt | 1 + tests/cmake/startup_gfx2hlsl_bvh.cmake | 14 + tests/startup_gfx2hlsl_bvh_check.py | 374 ++++++++++++++++++ tools/startup/gfx2hlsl.py | 212 +++++++++- 5 files changed, 660 insertions(+), 2 deletions(-) create mode 100644 docs/experiments/startup-gfx2hlsl-bvh-box32.md create mode 100644 tests/checks/python-linux/startup_gfx2hlsl_bvh.txt create mode 100644 tests/cmake/startup_gfx2hlsl_bvh.cmake create mode 100644 tests/startup_gfx2hlsl_bvh_check.py diff --git a/docs/experiments/startup-gfx2hlsl-bvh-box32.md b/docs/experiments/startup-gfx2hlsl-bvh-box32.md new file mode 100644 index 0000000000..928459f57f --- /dev/null +++ b/docs/experiments/startup-gfx2hlsl-bvh-box32.md @@ -0,0 +1,61 @@ +# First `image_bvh_intersect_ray` slice: FP32 box nodes + +`tools/startup/gfx2hlsl.py` now lowers the 32-bit `image_bvh_intersect_ray` (RDNA 2 MIMG opcode 230) for +one node form: the 128-byte FP32 box node, kind 5. The result is four child pointers, with `0xffffffff` for a +disabled child or a missed box. The helper performs the four slab tests, clips against `ray_extent`, and sorts +hits by entry distance only when bit 31 of the BVH T# is set. With sorting disabled it compacts hits in child +order, which is the order a traversal consumes the four results. + +The node layout is the one in Mesa 25.1.0 `src/amd/vulkan/bvh/bvh.h` (MIT): `children[4]` at bytes 0..15, +`coords[4][2][3]` at 16..111, and four reserved words at 112..127. The slab test follows Mesa +`radv_nir_rt_common.c` (MIT): inverse direction clamped to finite extremes, `tmin`/`tmax` from the three axes, +an inactive box whose `min.x` is NaN, `tmax >= max(0, tmin)`, `tmin < ray_extent`, and the five compare-exchange +stages that sort the four children. A child word of `0xffffffff` is a miss even when its stored box would hit. +The BVH T# fields are RDNA 2 ISA Table 49: base 39:0 (256-byte aligned), reserved 54:40, box growing 62:55, +box sorting 63, size 105:64, triangle return mode 120, big page 123 and type 8 at 127:124. + +## Accepted slice + +- compute stage only; +- `image_bvh_intersect_ray v[4], v[11], s[4]` with the packed address form (the disassembler prints `v[16:31]` + for the eleven consumed dwords); +- a constant inline T# built by four SGPR constants, type 8, base nonzero and 256-byte aligned, box growing zero, + size at least one 64-byte unit and below 4 GiB, and the node inside that size; +- a constant node pointer whose low three bits are 5, 128-byte aligned and inside the same 4 GiB address window; +- either value of the sort bit. + +The manifest names the node allocation with `srv bvh base 0x size 0x`. The host must bind a raw +`ByteAddressBuffer` at the base covering `(size + 1) * 64` bytes. That host binding is not part of this change. + +## Refused by name + +Triangle nodes (kind 0), 16-bit box nodes (kind 4), every other node kind, `image_bvh64_intersect_ray`, A16, +non-sequential addresses, a pixel or vertex stage, a node pointer that is not a straight-line constant, a T# +loaded at run time, a type other than 8, nonzero box growing, a misaligned base, an absolute base, a size that +does not cover the node, size bits above 4 GiB, and every reserved T# field. The checks assert that a refusal +emits no helper call and no destination VGPR assignment. + +## Evidence + +```text +python -B tests/startup_gfx2hlsl_bvh_check.py +``` + +The check compares the CPU box reference with the fixture in `tests/gfx1030_bvh_box/check.py` for five rays, +compares the emitted sort network with the same reference, checks the sort-bit negative control (word 0 changes +from `0x1d` to `0x25`), translates a synthetic constant-T# program and checks the four child results and the +manifest, and checks every refusal above. It also compiles the translated compute shader with DXC when one is +available; without DXC it prints `dxc compile: skip` and does not count that as a pass. + +```text +python -B tests/startup_gfx2hlsl_bvh_check.py dispatch warp +``` + +The dispatch mode compiles the same helper with a `RWByteAddressBuffer` in place of the bound +`ByteAddressBuffer`, writes the two synthetic nodes and five rays, and compares all twenty result words on a +Microsoft Basic Render Driver (`1414:008c`, driver `10.0.26100.10068`). It also dispatches a mutant that leaves +missed child words in place; the case 2 word 0 must stop being `0xffffffff`. That control caught the first version +of this helper, which sorted the keys correctly but returned the original child pointer for a miss. + +This is a translator slice. It does not execute the native gfx1030 probe, does not bind the node buffer on a +D3D12 device, and does not establish any title behavior. diff --git a/tests/checks/python-linux/startup_gfx2hlsl_bvh.txt b/tests/checks/python-linux/startup_gfx2hlsl_bvh.txt new file mode 100644 index 0000000000..26480c9d8e --- /dev/null +++ b/tests/checks/python-linux/startup_gfx2hlsl_bvh.txt @@ -0,0 +1 @@ +tests/startup_gfx2hlsl_bvh_check.py diff --git a/tests/cmake/startup_gfx2hlsl_bvh.cmake b/tests/cmake/startup_gfx2hlsl_bvh.cmake new file mode 100644 index 0000000000..aaf68adc60 --- /dev/null +++ b/tests/cmake/startup_gfx2hlsl_bvh.cmake @@ -0,0 +1,14 @@ +# gfx2hlsl image_bvh_intersect_ray FP32 box-node slice: translator controls, a DXC compile when +# one is available, and a WARP/hardware dispatch when offscreen_check is built. +if(EXISTS "${INTAKE_PYTHON}") + add_test(NAME startup_gfx2hlsl_bvh COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_bvh_check.py") +endif() +if(EXISTS "${INTAKE_PYTHON}" AND TARGET offscreen_check) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_bvh_dispatch_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_bvh_check.py" dispatch "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_gfx2hlsl_bvh_dispatch_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/startup_gfx2hlsl_bvh_check.py b/tests/startup_gfx2hlsl_bvh_check.py new file mode 100644 index 0000000000..cc40ed6667 --- /dev/null +++ b/tests/startup_gfx2hlsl_bvh_check.py @@ -0,0 +1,374 @@ +"""image_bvh_intersect_ray: the FP32 box-node (kind 5) translation slice. + +The instruction is RDNA 2 MIMG opcode 230. This check covers the translator path and the +box model only: a constant inline BVH T#[12:15], an 11-dword packed address, a constant +node base whose low three bits are 5, and the four child results. Triangle nodes, 16-bit +box nodes, the 64-bit form, A16, NSA and every dynamic descriptor or node base are refused +by name before any HLSL is emitted. The CPU box reference is the one in +tests/gfx1030_bvh_box/check.py; the sort network is the five compare-exchange stages of +Mesa 25.1.0 radv_nir_rt_common.c (MIT). +""" +import math +import os +from pathlib import Path +import shutil +import struct +import subprocess +import sys +import tempfile + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parent +sys.path.insert(0, str(ROOT / "tools")) +sys.path.insert(0, str(ROOT / "tools" / "startup")) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +import startup_gfx2hlsl_compute_check as C # noqa: E402 + +INVALID = 0xffffffff +SORT_ENABLE = 1 << 31 +RESOURCE_TYPE = 1 << 31 +MASK = 0xffffffff +FLT_MAX = 3.4028234663852886e38 + + +def box(child, depth, x=-8): + return child, (x, -8, depth), (x + 16, 8, depth + 0.5) + + +NODES = { + 0: (box(0x25, 4), box(0x1d, 1), box(0x2d, 2, x=32), box(INVALID, 3)), + 256: (box(0x45, 7), box(0x3d, 5), box(0x35, 3), box(0x0d, 1)), +} +ORIGIN = (0.5, -0.5, -1.0) +FORWARD = (0.25, -0.125, 0.5) +RAYS = ( + ("sorted", 0, 19.0, ORIGIN, FORWARD, (0x1d, 0x25, INVALID, INVALID)), + ("clipped", 0, 6.0, ORIGIN, FORWARD, (0x1d, INVALID, INVALID, INVALID)), + ("all_miss", 0, 2.0, ORIGIN, FORWARD, (INVALID,) * 4), + ("all_four", 256, 19.0, ORIGIN, FORWARD, (0x0d, 0x35, 0x3d, 0x45)), + ("reverse", 0, 21.0, (0.0, 0.0, 10.0), (0.25, -0.125, -0.5), (0x25, 0x1d, INVALID, INVALID)), +) + +failures = [] + + +def check(label, ok, detail=""): + print("%s: %s" % (label, "ok" if ok else "MISMATCH"), flush=True) + if not ok: + failures.append(label) + if detail: + print(" " + detail) + + +def reference(nodes, extent, origin, direction, sort_boxes): + """The fixture reference: slab test, extent clip, compact misses, sort only when asked.""" + hits = [] + for child, lo, hi in nodes: + if child == INVALID: + continue + near, far = 0.0, extent + for lower, upper, start, step in zip(lo, hi, origin, direction, strict=True): + first, second = (lower - start) / step, (upper - start) / step + near, far = max(near, min(first, second)), min(far, max(first, second)) + if near <= far and near < extent: + hits.append((near, child)) + if sort_boxes: + hits.sort() + result = tuple(child for _, child in hits) + return result + (INVALID,) * (4 - len(result)) + + +def model(nodes, extent, origin, direction, sort_boxes): + """The emitted HLSL helper, transcribed: four slabs, keys, five compare-exchange stages.""" + inv = [max(-FLT_MAX, min(1.0 / c, FLT_MAX)) for c in direction] + items = [] + for child, lo, hi in nodes: + if child == INVALID: + items.append([INVALID, FLT_MAX]) + continue + bound0 = [(lo[i] - origin[i]) * inv[i] for i in range(3)] + bound1 = [(hi[i] - origin[i]) * inv[i] for i in range(3)] + tmin = max(min(bound0[i], bound1[i]) for i in range(3)) + tmax = min(max(bound0[i], bound1[i]) for i in range(3)) + hit = not math.isnan(lo[0]) and tmax >= max(0.0, tmin) and tmin < extent + if hit: + items.append([child, tmin if sort_boxes else 0.0]) + else: + items.append([INVALID, FLT_MAX]) + for a, b in ((0, 1), (2, 3), (0, 2), (1, 3), (1, 2)): + if items[b][1] < items[a][1]: + items[a], items[b] = items[b], items[a] + return tuple(item[0] for item in items) + + +def translate_program(*, node=0x05, sort_boxes=True, word0=0x00100000, word1=None, word2=0x0b, + word3=RESOURCE_TYPE, loaded_descriptor=False, modifier="", opcode="image_bvh_intersect_ray", + constant_node=True, stage_kind="cs"): + """A straight-line compute program with a constant inline T# and a constant node pointer.""" + if word1 is None: + word1 = SORT_ENABLE if sort_boxes else 0 + if stage_kind != "cs": + class Probe: + kind = stage_kind + try: + G.Stage.op_image_bvh_intersect_ray(Probe(), ("v[32:35]", "v[16:31]", "s[12:15]"), []) + except G.Unsupported as error: + return None, None, [str(error)] + return None, None, ["accepted outside compute"] + decoded = [] + at = 0 + + def add(name, asm, length=8): + nonlocal at + decoded.append((at, length, name, asm)) + at += length + + if loaded_descriptor: + add("s_mov_b32", "s_mov_b32 s10, s6") + add("s_mov_b32", "s_mov_b32 s11, 0") + add("s_load_dwordx4", "s_load_dwordx4 s[12:15], s[10:11], 0x0", 16) + add("s_waitcnt", "s_waitcnt lgkmcnt(0)", 4) + else: + for reg, word in ((12, word0), (13, word1), (14, word2), (15, word3)): + add("s_mov_b32", "s_mov_b32 s%d, 0x%08x" % (reg, word)) + for reg, word in ((16, node), (17, 0x41a00000), (18, 0x3f000000), (19, 0xbf000000), + (20, 0xbf800000), (21, 0x3e800000), (22, 0xbe000000), (23, 0x3f000000), + (24, 0x40800000), (25, 0xc1000000), (26, 0x40000000)): + source = "s4" if reg == 16 and not constant_node else "0x%08x" % word + add("v_mov_b32", "v_mov_b32 v%d, %s" % (reg, source)) + add(opcode, "%s v[32:35], v[16:31], s[12:15]%s" % (opcode, (" " + modifier) if modifier else "")) + add("s_endpgm", "s_endpgm", 4) + refusals = [] + pipe = G.ComputePipeline(b"", C.root_blob(), C.USER7, (1, 1, 1), refusals=refusals, decoded=decoded) + return pipe, pipe.hlsl_cs(), [reason for reason, _kind in refusals] + + +def controls(): + bad = None + for name, offset, extent, origin, direction, expected in RAYS: + actual = reference(NODES[offset], extent, origin, direction, True) + if actual != expected: + bad = (name, actual, expected) + break + check("CPU reference matches the gfx1030 box fixture", bad is None, str(bad)) + + bad = None + for name, offset, extent, origin, direction, expected in RAYS: + actual = model(NODES[offset], extent, origin, direction, True) + if actual != expected: + bad = (name, actual, expected) + break + check("emitted sort network matches the CPU reference", bad is None, str(bad)) + + # Negative control: sort disabled keeps child order. The sorted ray's first word changes. + unsorted = reference(NODES[0], 19.0, ORIGIN, FORWARD, False) + sorted_result = reference(NODES[0], 19.0, ORIGIN, FORWARD, True) + check("sort bit negative control changes word 0", + unsorted[0] == 0x25 and sorted_result[0] == 0x1d, str((unsorted, sorted_result))) + check("model without the sort bit matches the unsorted reference", + model(NODES[0], 19.0, ORIGIN, FORWARD, False) == unsorted, + str((model(NODES[0], 19.0, ORIGIN, FORWARD, False), unsorted))) + check("all-miss result is four 0xffffffff words", + reference(NODES[0], 2.0, ORIGIN, FORWARD, True) == (INVALID,) * 4, "") + + pipe, hlsl, refusals = translate_program() + check("constant box32 program translates", pipe is not None and not refusals, str(refusals)) + if pipe is not None: + manifest = pipe.manifest() + check("manifest names the node allocation", "srv 0 bvh base 0x100000 size 0xb" in manifest, manifest) + check("HLSL declares the node buffer", "ByteAddressBuffer r0 : register(t0);" in hlsl, "") + check("HLSL contains the four-result helper", + "uint4 x2w_bvh_intersect_box32" in hlsl and "x2w_bvh_box32_slot" in hlsl, "") + check("the call carries the sort-enabled T# word and four child results", + "0x80000000u" in hlsl and all("v%d = bt" % reg in hlsl for reg in range(32, 36)), + "") + call_line = next(line for line in hlsl.splitlines() if "x2w_bvh_intersect_box32(r0" in line) + check("constant T# passes literals, not descriptor SGPRs", + "s12" not in call_line and "s13" not in call_line, call_line) + + pipe, hlsl, refusals = translate_program(sort_boxes=False) + check("sort-disabled program translates", pipe is not None and not refusals, str(refusals)) + if pipe is not None: + check("sort-disabled call uses a zero sort word", "0x00000000u" in hlsl, "") + + # Every refusal must happen before a helper call or a result VGPR is emitted. + cases = [ + ("triangle node", dict(node=0x00), "triangle node (kind 0)"), + ("16-bit box node", dict(node=0x04), "16-bit box node (kind 4)"), + ("unknown node kind", dict(node=0x06), "node kind 6"), + ("unaligned node", dict(node=0x0d), "not an aligned 128-byte node"), + ("non-constant node", dict(constant_node=False), "non-constant node base"), + ("64-bit form", dict(opcode="image_bvh64_intersect_ray"), "image_bvh64_intersect_ray"), + ("A16", dict(modifier="a16"), "modifier a16"), + ("NSA address", dict(modifier=""), "non-sequential"), + ("loaded descriptor", dict(loaded_descriptor=True), "loaded at run time"), + ("descriptor type", dict(word3=0x60000000), "descriptor type 6 is not 8"), + ("box growing", dict(word1=SORT_ENABLE | (2 << 23)), "box growing amount 2"), + ("base alignment", dict(word0=0x00100008), "not 256-byte aligned"), + ("size zero", dict(word2=0), "does not cover a 128-byte node"), + ("node outside size", dict(node=0x25, word2=3), "outside descriptor size"), + ("absolute base", dict(word0=0, word1=0), "absolute node base"), + ("size high bits", dict(word3=RESOURCE_TYPE | 0x100), "size above 4 GiB"), + ] + for label, kwargs, reason in cases: + if label == "NSA address": + # A non-sequential address is a text form the packed decoder never prints. + pipe, hlsl, refusals = None, None, [] + try: + G.Stage.op_image_bvh_intersect_ray( + type("P", (), {"kind": "cs", "const_u32": lambda self, tok: 5})(), + ("v[32:35]", "[v0, v2, v4, v6, v8, v10, v12, v14, v16, v18, v20]", "s[12:15]"), []) + except G.Unsupported as error: + refusals = [str(error)] + else: + pipe, hlsl, refusals = translate_program(**kwargs) + ok = len(refusals) == 1 and reason in refusals[0] + check("refuses %s" % label, ok, str(refusals)) + if hlsl is not None: + check(" no partial output for %s" % label, + "uint4 bt" not in hlsl and "x2w_bvh_intersect_box32(r" not in hlsl, "") + + pipe, hlsl, refusals = translate_program(stage_kind="ps") + check("refuses a pixel stage", len(refusals) == 1 and "outside a compute stage" in refusals[0], str(refusals)) + + +def find_dxc(): + named = os.environ.get("X2W_DXC") + if named and Path(named).is_file(): + return str(Path(named)) + found = shutil.which("dxc") + if found: + return found + kits = os.environ.get("ProgramFiles(x86)", "") + if kits: + candidates = sorted((Path(kits) / "Windows Kits" / "10" / "bin").glob("*/x64/dxc.exe"), reverse=True) + if candidates: + return str(candidates[0]) + return None + + +def compile_check(hlsl): + dxc = find_dxc() + if dxc is None: + print("dxc compile: skip (no dxc on this host)") + return None + with tempfile.TemporaryDirectory(dir=ROOT / "out" if (ROOT / "out").is_dir() else None) as temporary: + source = Path(temporary) / "bvh_box32.hlsl" + source.write_text(hlsl, encoding="ascii") + result = subprocess.run([dxc, "-T", "cs_6_0", "-E", "main", "-Fo", str(source.with_suffix(".cso")), str(source)], + capture_output=True, text=True) + if result.returncode or result.stderr: + check("dxc compiles the translated helper", False, result.stderr or "exit %d" % result.returncode) + return False + print("dxc compile: ok (%s)" % dxc) + return True + + + + +def ffloat(value): + return "asfloat(0x%08xu)" % struct.unpack("> 3) | 5, ffloat(extent), ffloat(origin[0]), ffloat(origin[1]), + ffloat(origin[2]), ffloat(inv[0]), ffloat(inv[1]), ffloat(inv[2]))) + for word in range(4): + lines.append(" data.Store(%du, r%d.%s);" % (512 + 16 * case + 4 * word, case, "xyzw"[word])) + lines.append("}") + return "\n".join(lines) + "\n" + + +def run_dispatch(dxc, runner, adapter, directory, mutate=False): + name = "bvh_dispatch_mut" if mutate else "bvh_dispatch" + source = directory / (name + ".hlsl") + cso = directory / (name + ".cso") + output = directory / (name + ".bin") + source.write_text(dispatch_hlsl(mutate), encoding="ascii") + compiled = subprocess.run([dxc, "-T", "cs_6_0", "-E", "main", "-Fo", str(cso), str(source)], + capture_output=True, text=True) + if compiled.returncode or compiled.stderr: + raise AssertionError(compiled.stderr or "dxc exited with %d" % compiled.returncode) + result = subprocess.run([runner, adapter, "--raw-uav-dump", str(cso), "1", "592", str(output)], + capture_output=True, text=True) + print(result.stdout, end="") + if result.returncode == 77: + return 77, None + if result.returncode or result.stderr: + raise AssertionError(result.stderr or "offscreen_check exited with %d" % result.returncode) + data = output.read_bytes() + return 0, struct.unpack("<%dI" % (len(data) // 4), data) + + +def check_dispatch(dxc, runner, adapter): + controls() + if not dxc or not runner: + print("dispatch: skip (no dxc or offscreen_check)") + return 77 + out = ROOT / "out" + out.mkdir(exist_ok=True) + with tempfile.TemporaryDirectory(dir=out) as temporary: + directory = Path(temporary) + status, words = run_dispatch(dxc, runner, adapter, directory) + if status == 77: + print("dispatch: skip (adapter unavailable)") + return 77 + for case, (_name, _offset, _extent, _origin, _direction, expected) in enumerate(RAYS): + got = tuple(words[128 + 4 * case:132 + 4 * case]) + check("dispatch case %d %s" % (case, _name), got == expected, + "got %s expected %s" % (["%08x" % w for w in got], ["%08x" % w for w in expected])) + status, mutant = run_dispatch(dxc, runner, adapter, directory, mutate=True) + if status == 77: + print("dispatch control: skip (adapter unavailable)") + return 77 + changed = mutant[128:132] + check("dispatch miss-fill control decays case 2", tuple(changed) != (INVALID,) * 4, + "got %s" % ["%08x" % w for w in changed]) + if failures: + print("FAILED: %s" % ", ".join(failures)) + return 1 + print("dispatch: all ok on %s" % adapter) + return 0 + +def main(): + if len(sys.argv) == 5 and sys.argv[1] == "dispatch": + return check_dispatch(sys.argv[2], sys.argv[3], sys.argv[4]) + if len(sys.argv) != 1: + sys.exit(__doc__) + controls() + pipe, hlsl, refusals = translate_program() + assert not refusals, refusals + compile_check(hlsl) + if failures: + print("FAILED: %s" % ", ".join(failures)) + return 1 + print("startup gfx2hlsl bvh box32: all ok") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 489148b039..3e1db887b5 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -2293,6 +2293,7 @@ def __init__(self, pipe, kind, code, refusals=None, decoded=None): first_refusal = len(refusals) if refusals is not None else 0 while True: self.lines = [] # body statements (per block) + self.vconst = {} # VGPR -> literal 32-bit value while the program is straight-line self.sym = {} # scalar register -> symbolic value self.used_s, self.used_v = set(), set() self.used_atomic = set() @@ -2697,6 +2698,13 @@ def set_v(self, n, expr, *, low16_only=False, align4=False): else: self.align4_v.discard(n) self.last_v = (n, expr) + vconst = getattr(self, 'vconst', None) + if isinstance(vconst, dict): + literal = re.fullmatch(r'0x([0-9a-fA-F]{8})u', expr) + if literal: + vconst[n] = int(literal.group(1), 16) + else: + vconst.pop(n, None) if low16_only: if not isinstance(self.low16_only_v, set): self.low16_only_v = set() @@ -3523,6 +3531,7 @@ def translate(self): self.address_carry_reader = None uniform_vcc_compares = set() self.lines = [] + self.vconst = {} self.blocks = [] # (offset, [lines], terminator) self.sym = dict(init_sym) self.exec_known = init_exec_known @@ -7497,6 +7506,115 @@ def fixed_table_image(self, operand, name): raise Unsupported('%s through a modified image descriptor' % name) return self.descriptor(operand) + def bvh_descriptor(self, tok): + """The binding key and literal words of an inline constant BVH T#. + + The table-name form and the run-time descriptor are deliberately outside this first slice: the + host binding for a T# read from a descriptor heap is not part of this change, and passing the + four words as uninitialized SGPRs would read address zero. A constant T# built by four s_mov_b32 + instructions is fully proved here, so the emitted helper receives literals and the manifest can + name the node allocation by its base and size. + """ + name = 'image_bvh_intersect_ray' + r = reg_range(tok) + if not r or r[0] != 's' or r[2] - r[1] != 3: + raise Unsupported('%s descriptor %s is not four consecutive SGPRs' % (name, tok)) + values = [self.is_const(n) for n in range(r[1], r[2] + 1)] + if any(value is None for value in values): + first = self.sym.get(r[1]) + if first and first[0] == 'desc': + raise Unsupported('%s descriptor %s is loaded at run time: only a constant inline T# is ' + 'lowered in this slice' % (name, tok)) + raise Unsupported('%s descriptor %s is not four constant SGPRs' % (name, tok)) + words = ['0x%08xu' % (value & 0xffffffff) for value in values] + base = ((values[1] & 0xff) << 32) | values[0] + return (('bvhbase', base, values[2]), None), words, values + + def op_image_bvh_intersect_ray(self, ops, mods): + """Ray/box intersection for the 128-byte FP32 box node (kind 5). + + RDNA 2 ISA section 8.2.10 and Table 48: VDATA is four result dwords, VADDR is 11 dwords + (node pointer, extent, origin xyz, direction xyz, inverse direction xyz) and SRSRC is the + four-word BVH T# of Table 49. This first slice accepts only a straight-line compute program + with a constant node base, a constant inline T# and a node whose kind bits are 5. + The descriptor base binds a ByteAddressBuffer at the 256-byte-aligned allocation; the node + pointer is an offset in 8-byte units from that base. The emitted helper performs the four + slab tests, clips against extent, compacts misses to 0xffffffff, and sorts by entry distance + only when the descriptor's box-sorting enable bit is set. Triangle nodes, 16-bit box nodes, + the 64-bit form, A16, non-sequential addresses and every other node kind are refused by name. + """ + name = 'image_bvh_intersect_ray' + if self.kind != 'cs': + raise Unsupported('%s outside a compute stage' % name) + if mods: + raise Unsupported('%s modifier %s' % (name, ' '.join(mods))) + if len(ops) != 3: + raise Unsupported('%s with %d operands, expected 3' % (name, len(ops))) + dst = reg_range(ops[0]) + if not dst or dst[0] != 'v' or dst[2] - dst[1] != 3 or dst[2] > 255: + raise Unsupported('%s destination %s is not four consecutive VGPRs' % (name, ops[0])) + if ops[1].startswith('['): + raise Unsupported('%s non-sequential address %s is not lowered' % (name, ops[1])) + addr = reg_range(ops[1]) + if not addr or addr[0] != 'v' or addr[2] > 255 or addr[2] - addr[1] + 1 not in (11, 16): + raise Unsupported('%s address %s is not an 11-dword VGPR range' % (name, ops[1])) + cs = ['v%d' % n for n in range(addr[1], addr[1] + 11)] + node = self.const_u32(cs[0]) + node_reg = reg_range(cs[0]) + if node is None and node_reg and node_reg[0] == 'v' and not getattr(self, 'has_branches', True): + node = getattr(self, 'vconst', {}).get(node_reg[1]) + if node is None: + raise Unsupported('%s non-constant node base %s' % (name, cs[0])) + kind = node & 7 + if kind == 4: + raise Unsupported('%s 16-bit box node (kind 4) is not lowered' % name) + if kind == 0: + raise Unsupported('%s triangle node (kind 0) is not lowered' % name) + if kind != 5: + raise Unsupported('%s node kind %d is not lowered' % (name, kind)) + node_offset = (node & 0xfffffff8) << 3 + if node_offset > 0xffffff80 or node_offset & 0x7f: + raise Unsupported('%s node base %#x is not an aligned 128-byte node' % (name, node_offset)) + key, words, vals = self.bvh_descriptor(ops[2]) + if vals[0] is not None and vals[0] & 0xff: + raise Unsupported('%s descriptor base is not 256-byte aligned' % name) + if vals[1] is not None: + if vals[1] & 0x7f800000: + raise Unsupported('%s box growing amount %d is not lowered' % (name, (vals[1] >> 23) & 0xff)) + if vals[1] & 0x007fff00: + raise Unsupported('%s descriptor reserved word 1 %#x' % (name, vals[1])) + if vals[3] is not None: + if (vals[3] >> 28) & 0xf != 8: + raise Unsupported('%s descriptor type %d is not 8' % (name, (vals[3] >> 28) & 0xf)) + if vals[3] & 0x0fffffff: + raise Unsupported('%s descriptor size above 4 GiB or reserved word 3 %#x' % (name, vals[3])) + if vals[0] is not None and vals[1] is not None and ((vals[1] & 0xff) << 32 | vals[0]) == 0: + raise Unsupported('%s absolute node base is not lowered' % name) + if vals[2] is not None: + if vals[2] < 1 or vals[2] >= 0x04000000: + raise Unsupported('%s descriptor size %d does not cover a 128-byte node' % (name, vals[2])) + if (node_offset >> 6) + 1 > vals[2]: + raise Unsupported('%s node base %#x is outside descriptor size %d' % (name, node_offset, vals[2])) + extent = self.f(cs[1]) + origin = [self.f(cs[2 + i]) for i in range(3)] + [self.f(cs[5 + i]) for i in range(3)] # the instruction consumes ray_dir; the helper uses inv_dir + inv_dir = [self.f(cs[8 + i]) for i in range(3)] + if vals[1] is not None: + sort = '0x80000000u' if vals[1] & 0x80000000 else '0x00000000u' + else: + sort = '(%s & 0x80000000u)' % words[1] + res = self.pipe.resource(key, 'bvh') + self.pipe.uses_bvh = True + call = 'x2w_bvh_intersect_box32(%s, 0x%08xu, %s, %s, %s, %s, %s, float3(%s, %s, %s), float3(%s, %s, %s))' % ( + res, node, words[0], sort, words[2], words[3], extent, + origin[0], origin[1], origin[2], inv_dir[0], inv_dir[1], inv_dir[2]) + self.emit('uint4 bt%x = %s;' % (self.pc or 0, call)) + for i in range(4): + self.set_v(dst[1] + i, 'bt%x.%s' % (self.pc or 0, 'xyzw'[i])) + + def op_image_bvh64_intersect_ray(self, ops, mods): + raise Unsupported('image_bvh64_intersect_ray: only the 32-bit image_bvh_intersect_ray is lowered') + def op_image_store(self, ops, mods): """Write a full 2D texel or, for compute, a full 2D-array texel. @@ -10167,9 +10285,92 @@ def read(fmt, data, offset): VERIFIED_SINT_RTVS = frozenset((4, 14, 18, 32, 38, 43, 52, 59, 64)) +BVH_HELPERS = ( + 'static const uint X2W_BVH_MISS = 0xffffffffu;', + # The 128-bit BVH T# (RDNA 2 ISA Table 49): base 39:0, box growing 62:55, sort enable 63, + # size 105:64 and type 8 at 127:124. This slice binds a ByteAddressBuffer at the base and + # keeps the descriptor in a 32-bit address window, so the size-high ten bits and every + # reserved field must be zero. A zero base selects the absolute pointer form, which this + # slice does not bind, so it is refused here as a miss rather than read at address zero. + 'bool x2w_bvh_descriptor_ok(uint word0, uint word1, uint word2, uint word3) {', + ' return (word0 & 0x000000ffu) == 0u && (word1 & 0x7fffff00u) == 0u &&', + ' word3 == 0x80000000u && word2 >= 1u && word2 < 0x04000000u &&', + ' (word0 != 0u || (word1 & 0x000000ffu) != 0u);', + '}', + # One FP32 box from a radv_bvh_box32_node (Mesa 25.1.0 bvh/bvh.h, MIT): children[4] at + # bytes 0..15, coords[4][2][3] at 16..111 (lo then hi per child) and reserved at 112..127. + 'float x2w_bvh_box32_slot(ByteAddressBuffer nodes, uint node_offset, uint index, float extent,', + ' float3 origin, float3 inv_dir, out bool hit) {', + ' uint at = node_offset + 16u + 24u * index;', + ' float3 lo = float3(asfloat(nodes.Load(at)), asfloat(nodes.Load(at + 4u)),', + ' asfloat(nodes.Load(at + 8u)));', + ' float3 hi = float3(asfloat(nodes.Load(at + 12u)), asfloat(nodes.Load(at + 16u)),', + ' asfloat(nodes.Load(at + 20u)));', + ' float3 bound0 = (lo - origin) * inv_dir;', + ' float3 bound1 = (hi - origin) * inv_dir;', + ' float tmin = max(max(min(bound0.x, bound1.x), min(bound0.y, bound1.y)),', + ' min(bound0.z, bound1.z));', + ' float tmax = min(min(max(bound0.x, bound1.x), max(bound0.y, bound1.y)),', + ' max(bound0.z, bound1.z));', + # A NaN in min.x marks an inactive box (Vulkan inactive primitive rule; Mesa tests NaN != NaN). + ' bool active = (asuint(lo.x) & 0x7fffffffu) <= 0x7f800000u;', + ' hit = active && tmax >= max(0.0, tmin) && tmin < extent;', + ' return hit ? tmin : 3.402823466e+38;', + '}', + # The five compare-exchange stages of Mesa radv_nir_rt_common.c: equal keys do not swap, + # so misses (key +inf) sink to the end and unsorted hits keep their child order. + 'void x2w_bvh_sort_pair(inout uint ia, inout uint ib, inout float ka, inout float kb) {', + ' if (kb < ka) { uint ti = ia; ia = ib; ib = ti; float tk = ka; ka = kb; kb = tk; }', + '}', + 'uint4 x2w_bvh_intersect_box32(ByteAddressBuffer nodes, uint node, uint word0, uint word1,', + ' uint word2, uint word3, float extent, float3 origin,', + ' float3 inv_dir) {', + ' uint4 miss = uint4(X2W_BVH_MISS, X2W_BVH_MISS, X2W_BVH_MISS, X2W_BVH_MISS);', + ' if ((node & 7u) != 5u || !x2w_bvh_descriptor_ok(word0, word1, word2, word3)) return miss;', + ' uint offset = (node & 0xfffffff8u) << 3u;', + ' if ((offset >> 6u) + 1u > word2) return miss;', + # Mesa clamps the inverse direction so a zero direction component cannot turn 0 * inf + # into NaN. The box test then follows the software reference exactly. + ' inv_dir = clamp(inv_dir, -3.402823466e+38, 3.402823466e+38);', + ' bool h0, h1, h2, h3;', + ' float d0 = x2w_bvh_box32_slot(nodes, offset, 0u, extent, origin, inv_dir, h0);', + ' float d1 = x2w_bvh_box32_slot(nodes, offset, 1u, extent, origin, inv_dir, h1);', + ' float d2 = x2w_bvh_box32_slot(nodes, offset, 2u, extent, origin, inv_dir, h2);', + ' float d3 = x2w_bvh_box32_slot(nodes, offset, 3u, extent, origin, inv_dir, h3);', + ' bool sort_boxes = (word1 & 0x80000000u) != 0u;', + ' uint c0 = nodes.Load(offset);', + ' uint c1 = nodes.Load(offset + 4u);', + ' uint c2 = nodes.Load(offset + 8u);', + ' uint c3 = nodes.Load(offset + 12u);', + # A disabled child stores 0xffffffff and must not enter the hit list even if its box is valid. + ' h0 = h0 && c0 != X2W_BVH_MISS;', + ' h1 = h1 && c1 != X2W_BVH_MISS;', + ' h2 = h2 && c2 != X2W_BVH_MISS;', + ' h3 = h3 && c3 != X2W_BVH_MISS;', + ' c0 = h0 ? c0 : X2W_BVH_MISS;', + ' c1 = h1 ? c1 : X2W_BVH_MISS;', + ' c2 = h2 ? c2 : X2W_BVH_MISS;', + ' c3 = h3 ? c3 : X2W_BVH_MISS;', + # A disabled sort uses one key for every hit: the network then only compacts misses, + # while an enabled sort orders the hits by entry distance. + ' float k0 = h0 ? (sort_boxes ? d0 : 0.0) : 3.402823466e+38;', + ' float k1 = h1 ? (sort_boxes ? d1 : 0.0) : 3.402823466e+38;', + ' float k2 = h2 ? (sort_boxes ? d2 : 0.0) : 3.402823466e+38;', + ' float k3 = h3 ? (sort_boxes ? d3 : 0.0) : 3.402823466e+38;', + ' x2w_bvh_sort_pair(c0, c1, k0, k1);', + ' x2w_bvh_sort_pair(c2, c3, k2, k3);', + ' x2w_bvh_sort_pair(c0, c2, k0, k2);', + ' x2w_bvh_sort_pair(c1, c3, k1, k3);', + ' x2w_bvh_sort_pair(c1, c2, k1, k2);', + ' return uint4(c0, c1, c2, c3);', + '}', +) + + class Pipeline: vertex_kind = 'vs' uses_pack16_rne = False + uses_bvh = False uses_gather_2d_lod = False uses_store_d16_x = False uses_sad = () @@ -10208,6 +10409,7 @@ def _init_pixel_context(self, root_blob, sampler_heap=None, rtv_formats=(), ps_h self.sampler_heap = os.environ.get('X2W_SAMPLER_HEAP') == '1' if sampler_heap is None else sampler_heap self.uses_sampler_heap = False self.uses_pack16_rne = False + self.uses_bvh = False self.uses_gather_2d_lod = False self.uses_store_d16_x = False self.uses_sad = set() @@ -10427,8 +10629,10 @@ def common(self): 'uint ldu(ByteAddressBuffer b, uint a) { uint k = (a & 3) * 8, lo = b.Load(a & ~3u); if (k == 0) return lo; ' 'return (lo >> k) | (b.Load((a & ~3u) + 4) << (32 - k)); }', 'cbuffer entry : register(b0) { %s };' % ' '.join('uint ud%d;' % i for i in range(len(self.uds)))] + if self.uses_bvh: + out.extend(BVH_HELPERS) for key, r in sorted(self.resources.items(), key=lambda kv: kv[1]['index']): - out.append('%s r%d : register(t%d);' % ({'buf': 'ByteAddressBuffer', 'tex1d': 'Texture1D', 'tex2d': 'Texture2D', 'tex2da': 'Texture2DArray', 'tex3d': 'Texture3D'}[r['kind']], r['index'], r['index'])) + out.append('%s r%d : register(t%d);' % ({'buf': 'ByteAddressBuffer', 'bvh': 'ByteAddressBuffer', 'tex1d': 'Texture1D', 'tex2d': 'Texture2D', 'tex2da': 'Texture2DArray', 'tex3d': 'Texture3D'}[r['kind']], r['index'], r['index'])) for key, r in sorted(self.stored_images().items(), key=lambda kv: kv[1]['index']): out.append('%s %s%d : register(u%d);' % ({'tex2d': 'RWTexture2D', 'tex2da': 'RWTexture2DArray', 'raw': 'RWByteAddressBuffer'}[r['kind']], 'u' if r['kind'] == 'raw' else 'w', r['index'], r['index'])) for key, i in self.samplers.items(): @@ -10754,6 +10958,7 @@ def manifest(self): for key, r in sorted(self.resources.items(), key=lambda kv: kv[1]['index']): source, off = key where = {'table': 'table %d %d' % (source[1] if len(source) > 1 else 0, off or 0), 'vbtab': 'vb %d' % ((off or 0) // 16), + 'bvhbase': 'base 0x%x size 0x%x' % (source[1], source[2]), 'root': 'root %d' % (source[1] if len(source) > 1 else 0)}.get(source[0]) if where is None: raise Unsupported('resource through %s' % (source,)) @@ -10805,6 +11010,7 @@ def __init__(self, cs_code, root_blob, rsrc2, group, sampler_heap=None, refusals self.uses_sampler_heap = False self.uses_gather_2d_lod = False self.uses_store_d16_x = False + self.uses_bvh = False self.uses_sad = set() self.resources, self.uavs, self.samplers, self.uds = {}, {}, {}, [] self.notes, self.modified, self.other_modified = set(), set(), set() # other: unproved descriptor writes @@ -10848,7 +11054,9 @@ def manifest(self): lines = ['x2w-manifest 2', 'stage cs', 'group %d %d %d' % self.group, 'ud %d' % len(self.uds)] lines += ['udsrc %d %s' % (i, ' '.join(str(x) for x in source)) for i, source in enumerate(self.uds)] for (source, off), r in sorted(self.resources.items(), key=lambda kv: kv[1]['index']): - if source[0] == 'table': + if source[0] == 'bvhbase': + where = 'base 0x%x size 0x%x' % (source[1], source[2]) + elif source[0] == 'table': where = 'table %d %d' % (source[1], off or 0) elif source[0] == 'root': where = 'root %d' % source[1] From 2ec454f9ea80d5d22366692da0302f7af5dba834 Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Thu, 26 Nov 2026 20:39:24 +0000 Subject: [PATCH 02/11] startup: keep non-BVH resource manifests from reading a third field --- tools/startup/gfx2hlsl.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 3e1db887b5..eae274393b 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -10957,9 +10957,12 @@ def manifest(self): lines.append('udsrc %d %s' % (i, ' '.join(str(x) for x in source))) for key, r in sorted(self.resources.items(), key=lambda kv: kv[1]['index']): source, off = key - where = {'table': 'table %d %d' % (source[1] if len(source) > 1 else 0, off or 0), 'vbtab': 'vb %d' % ((off or 0) // 16), - 'bvhbase': 'base 0x%x size 0x%x' % (source[1], source[2]), - 'root': 'root %d' % (source[1] if len(source) > 1 else 0)}.get(source[0]) + if source[0] == 'bvhbase': + where = 'base 0x%x size 0x%x' % (source[1], source[2]) + else: + where = {'table': 'table %d %d' % (source[1] if len(source) > 1 else 0, off or 0), + 'vbtab': 'vb %d' % ((off or 0) // 16), + 'root': 'root %d' % (source[1] if len(source) > 1 else 0)}.get(source[0]) if where is None: raise Unsupported('resource through %s' % (source,)) lines.append('srv %d %s %s' % (r['index'], r['kind'], where)) From 34a2c5c17db50be0f66f33595e5ab54ad058517a Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Thu, 26 Nov 2026 21:38:05 +0000 Subject: [PATCH 03/11] startup: lower binary16 box nodes in image_bvh_intersect_ray --- .../experiments/startup-gfx2hlsl-bvh-box32.md | 31 +++++--- tests/startup_gfx2hlsl_bvh_check.py | 39 ++++++++-- tools/startup/gfx2hlsl.py | 74 ++++++++++++++++--- 3 files changed, 115 insertions(+), 29 deletions(-) diff --git a/docs/experiments/startup-gfx2hlsl-bvh-box32.md b/docs/experiments/startup-gfx2hlsl-bvh-box32.md index 928459f57f..0f1bf29eec 100644 --- a/docs/experiments/startup-gfx2hlsl-bvh-box32.md +++ b/docs/experiments/startup-gfx2hlsl-bvh-box32.md @@ -1,10 +1,10 @@ -# First `image_bvh_intersect_ray` slice: FP32 box nodes +# First `image_bvh_intersect_ray` slice: FP32 and binary16 box nodes `tools/startup/gfx2hlsl.py` now lowers the 32-bit `image_bvh_intersect_ray` (RDNA 2 MIMG opcode 230) for -one node form: the 128-byte FP32 box node, kind 5. The result is four child pointers, with `0xffffffff` for a -disabled child or a missed box. The helper performs the four slab tests, clips against `ray_extent`, and sorts -hits by entry distance only when bit 31 of the BVH T# is set. With sorting disabled it compacts hits in child -order, which is the order a traversal consumes the four results. +the two box-node forms: the 128-byte FP32 node (kind 5) and the 64-byte binary16 node (kind 4). The result is +four child pointers, with `0xffffffff` for a disabled child or a missed box. The helper performs the four slab +tests, clips against `ray_extent`, and sorts hits by entry distance only when bit 31 of the BVH T# is set. With +sorting disabled it compacts hits in child order, which is the order a traversal consumes the four results. The node layout is the one in Mesa 25.1.0 `src/amd/vulkan/bvh/bvh.h` (MIT): `children[4]` at bytes 0..15, `coords[4][2][3]` at 16..111, and four reserved words at 112..127. The slab test follows Mesa @@ -14,6 +14,10 @@ stages that sort the four children. A child word of `0xffffffff` is a miss even The BVH T# fields are RDNA 2 ISA Table 49: base 39:0 (256-byte aligned), reserved 54:40, box growing 62:55, box sorting 63, size 105:64, triangle return mode 120, big page 123 and type 8 at 127:124. +The binary16 node has the same four child words at bytes 0..15 and four boxes of six binary16 values at +16..63. `f16tof32` widens each bound exactly before the same slab test. The inactive-box marker is still a NaN +in `min.x`. + ## Accepted slice - compute stage only; @@ -21,15 +25,17 @@ box sorting 63, size 105:64, triangle return mode 120, big page 123 and type 8 a for the eleven consumed dwords); - a constant inline T# built by four SGPR constants, type 8, base nonzero and 256-byte aligned, box growing zero, size at least one 64-byte unit and below 4 GiB, and the node inside that size; -- a constant node pointer whose low three bits are 5, 128-byte aligned and inside the same 4 GiB address window; +- a constant node pointer whose low three bits are 4 (64-byte aligned) or 5 (128-byte aligned) and inside the + same 4 GiB address window; - either value of the sort bit. -The manifest names the node allocation with `srv bvh base 0x size 0x`. The host must bind a raw -`ByteAddressBuffer` at the base covering `(size + 1) * 64` bytes. That host binding is not part of this change. +The manifest names the node allocation with `srv bvh base 0x size 0x`. The size is in 64-byte +units; a binary16 node covers one unit and an FP32 node two. The host must bind a raw `ByteAddressBuffer` at +the base covering `size * 64` bytes. That host binding is not part of this change. ## Refused by name -Triangle nodes (kind 0), 16-bit box nodes (kind 4), every other node kind, `image_bvh64_intersect_ray`, A16, +Triangle nodes (kinds 0..3), every other node kind, `image_bvh64_intersect_ray`, A16, non-sequential addresses, a pixel or vertex stage, a node pointer that is not a straight-line constant, a T# loaded at run time, a type other than 8, nonzero box growing, a misaligned base, an absolute base, a size that does not cover the node, size bits above 4 GiB, and every reserved T# field. The checks assert that a refusal @@ -43,9 +49,10 @@ python -B tests/startup_gfx2hlsl_bvh_check.py The check compares the CPU box reference with the fixture in `tests/gfx1030_bvh_box/check.py` for five rays, compares the emitted sort network with the same reference, checks the sort-bit negative control (word 0 changes -from `0x1d` to `0x25`), translates a synthetic constant-T# program and checks the four child results and the -manifest, and checks every refusal above. It also compiles the translated compute shader with DXC when one is -available; without DXC it prints `dxc compile: skip` and does not count that as a pass. +from `0x1d` to `0x25`), rounds the bounds to binary16 and checks the same box result, translates a synthetic +constant-T# program for each node kind and checks the four child results and the manifest, and checks every +refusal above. It also compiles the translated compute shader with DXC when one is available; without DXC it +prints `dxc compile: skip` and does not count that as a pass. ```text python -B tests/startup_gfx2hlsl_bvh_check.py dispatch warp diff --git a/tests/startup_gfx2hlsl_bvh_check.py b/tests/startup_gfx2hlsl_bvh_check.py index cc40ed6667..e72a2be0ac 100644 --- a/tests/startup_gfx2hlsl_bvh_check.py +++ b/tests/startup_gfx2hlsl_bvh_check.py @@ -1,10 +1,10 @@ -"""image_bvh_intersect_ray: the FP32 box-node (kind 5) translation slice. +"""image_bvh_intersect_ray: the FP32 and binary16 box-node translation slice. The instruction is RDNA 2 MIMG opcode 230. This check covers the translator path and the box model only: a constant inline BVH T#[12:15], an 11-dword packed address, a constant -node base whose low three bits are 5, and the four child results. Triangle nodes, 16-bit -box nodes, the 64-bit form, A16, NSA and every dynamic descriptor or node base are refused -by name before any HLSL is emitted. The CPU box reference is the one in +node base whose low three bits are 4 (binary16) or 5 (FP32), and the four child results. +Triangle nodes, the 64-bit form, A16, NSA and every dynamic descriptor or node base are +refused by name before any HLSL is emitted. The CPU box reference is the one in tests/gfx1030_bvh_box/check.py; the sort network is the five compare-exchange stages of Mesa 25.1.0 radv_nir_rt_common.c (MIT). """ @@ -102,6 +102,16 @@ def model(nodes, extent, origin, direction, sort_boxes): return tuple(item[0] for item in items) +def half_nodes(nodes): + """The same nodes with every bound rounded to binary16 before the box test.""" + quantized = [] + for child, lo, hi in nodes: + def q(value): + return struct.unpack(" 0xffffff80 or node_offset & 0x7f: - raise Unsupported('%s node base %#x is not an aligned 128-byte node' % (name, node_offset)) + if node_offset > (0xffffffc0 if half_box else 0xffffff80) or node_offset & (0x3f if half_box else 0x7f): + raise Unsupported('%s node base %#x is not an aligned %u-byte node' % (name, node_offset, node_bytes)) key, words, vals = self.bvh_descriptor(ops[2]) if vals[0] is not None and vals[0] & 0xff: raise Unsupported('%s descriptor base is not 256-byte aligned' % name) @@ -7592,7 +7592,7 @@ def op_image_bvh_intersect_ray(self, ops, mods): raise Unsupported('%s absolute node base is not lowered' % name) if vals[2] is not None: if vals[2] < 1 or vals[2] >= 0x04000000: - raise Unsupported('%s descriptor size %d does not cover a 128-byte node' % (name, vals[2])) + raise Unsupported('%s descriptor size %d does not cover the node' % (name, vals[2])) if (node_offset >> 6) + 1 > vals[2]: raise Unsupported('%s node base %#x is outside descriptor size %d' % (name, node_offset, vals[2])) extent = self.f(cs[1]) @@ -7605,7 +7605,8 @@ def op_image_bvh_intersect_ray(self, ops, mods): sort = '(%s & 0x80000000u)' % words[1] res = self.pipe.resource(key, 'bvh') self.pipe.uses_bvh = True - call = 'x2w_bvh_intersect_box32(%s, 0x%08xu, %s, %s, %s, %s, %s, float3(%s, %s, %s), float3(%s, %s, %s))' % ( + call = '%s(%s, 0x%08xu, %s, %s, %s, %s, %s, float3(%s, %s, %s), float3(%s, %s, %s))' % ( + 'x2w_bvh_intersect_box16' if half_box else 'x2w_bvh_intersect_box32', res, node, words[0], sort, words[2], words[3], extent, origin[0], origin[1], origin[2], inv_dir[0], inv_dir[1], inv_dir[2]) self.emit('uint4 bt%x = %s;' % (self.pc or 0, call)) @@ -10317,6 +10318,24 @@ def read(fmt, data, offset): ' hit = active && tmax >= max(0.0, tmin) && tmin < extent;', ' return hit ? tmin : 3.402823466e+38;', '}', + # One binary16 box from a radv_bvh_box16_node: children[4] at 0..15, coords[4][2][3] at + # 16..63, six binary16 values per child. The half values widen exactly to binary32. + 'float x2w_bvh_box16_slot(ByteAddressBuffer nodes, uint node_offset, uint index, float extent,', + ' float3 origin, float3 inv_dir, out bool hit) {', + ' uint at = node_offset + 16u + 12u * index;', + ' uint h0 = nodes.Load(at), h1 = nodes.Load(at + 4u), h2 = nodes.Load(at + 8u);', + ' float3 lo = float3(f16tof32(h0), f16tof32(h0 >> 16u), f16tof32(h1));', + ' float3 hi = float3(f16tof32(h1 >> 16u), f16tof32(h2), f16tof32(h2 >> 16u));', + ' float3 bound0 = (lo - origin) * inv_dir;', + ' float3 bound1 = (hi - origin) * inv_dir;', + ' float tmin = max(max(min(bound0.x, bound1.x), min(bound0.y, bound1.y)),', + ' min(bound0.z, bound1.z));', + ' float tmax = min(min(max(bound0.x, bound1.x), max(bound0.y, bound1.y)),', + ' max(bound0.z, bound1.z));', + ' bool active = (asuint(lo.x) & 0x7fffffffu) <= 0x7f800000u;', + ' hit = active && tmax >= max(0.0, tmin) && tmin < extent;', + ' return hit ? tmin : 3.402823466e+38;', + '}', # The five compare-exchange stages of Mesa radv_nir_rt_common.c: equal keys do not swap, # so misses (key +inf) sink to the end and unsorted hits keep their child order. 'void x2w_bvh_sort_pair(inout uint ia, inout uint ib, inout float ka, inout float kb) {', @@ -10364,6 +10383,43 @@ def read(fmt, data, offset): ' x2w_bvh_sort_pair(c1, c2, k1, k2);', ' return uint4(c0, c1, c2, c3);', '}', + 'uint4 x2w_bvh_intersect_box16(ByteAddressBuffer nodes, uint node, uint word0, uint word1,', + ' uint word2, uint word3, float extent, float3 origin,', + ' float3 inv_dir) {', + ' uint4 miss = uint4(X2W_BVH_MISS, X2W_BVH_MISS, X2W_BVH_MISS, X2W_BVH_MISS);', + ' if ((node & 7u) != 4u || !x2w_bvh_descriptor_ok(word0, word1, word2, word3)) return miss;', + ' uint offset = (node & 0xfffffff8u) << 3u;', + ' if ((offset >> 6u) + 1u > word2) return miss;', + ' inv_dir = clamp(inv_dir, -3.402823466e+38, 3.402823466e+38);', + ' bool h0, h1, h2, h3;', + ' float d0 = x2w_bvh_box16_slot(nodes, offset, 0u, extent, origin, inv_dir, h0);', + ' float d1 = x2w_bvh_box16_slot(nodes, offset, 1u, extent, origin, inv_dir, h1);', + ' float d2 = x2w_bvh_box16_slot(nodes, offset, 2u, extent, origin, inv_dir, h2);', + ' float d3 = x2w_bvh_box16_slot(nodes, offset, 3u, extent, origin, inv_dir, h3);', + ' bool sort_boxes = (word1 & 0x80000000u) != 0u;', + ' uint c0 = nodes.Load(offset);', + ' uint c1 = nodes.Load(offset + 4u);', + ' uint c2 = nodes.Load(offset + 8u);', + ' uint c3 = nodes.Load(offset + 12u);', + ' h0 = h0 && c0 != X2W_BVH_MISS;', + ' h1 = h1 && c1 != X2W_BVH_MISS;', + ' h2 = h2 && c2 != X2W_BVH_MISS;', + ' h3 = h3 && c3 != X2W_BVH_MISS;', + ' c0 = h0 ? c0 : X2W_BVH_MISS;', + ' c1 = h1 ? c1 : X2W_BVH_MISS;', + ' c2 = h2 ? c2 : X2W_BVH_MISS;', + ' c3 = h3 ? c3 : X2W_BVH_MISS;', + ' float k0 = h0 ? (sort_boxes ? d0 : 0.0) : 3.402823466e+38;', + ' float k1 = h1 ? (sort_boxes ? d1 : 0.0) : 3.402823466e+38;', + ' float k2 = h2 ? (sort_boxes ? d2 : 0.0) : 3.402823466e+38;', + ' float k3 = h3 ? (sort_boxes ? d3 : 0.0) : 3.402823466e+38;', + ' x2w_bvh_sort_pair(c0, c1, k0, k1);', + ' x2w_bvh_sort_pair(c2, c3, k2, k3);', + ' x2w_bvh_sort_pair(c0, c2, k0, k2);', + ' x2w_bvh_sort_pair(c1, c3, k1, k3);', + ' x2w_bvh_sort_pair(c1, c2, k1, k2);', + ' return uint4(c0, c1, c2, c3);', + '}', ) From c47f5987b5da21794e977d52b798c95b70a455f3 Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Thu, 26 Nov 2026 21:39:29 +0000 Subject: [PATCH 04/11] tests: compile the binary16 BVH helper with DXC --- tests/startup_gfx2hlsl_bvh_check.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/startup_gfx2hlsl_bvh_check.py b/tests/startup_gfx2hlsl_bvh_check.py index e72a2be0ac..d35c62ab70 100644 --- a/tests/startup_gfx2hlsl_bvh_check.py +++ b/tests/startup_gfx2hlsl_bvh_check.py @@ -386,6 +386,9 @@ def main(): pipe, hlsl, refusals = translate_program() assert not refusals, refusals compile_check(hlsl) + pipe, hlsl, refusals = translate_program(node=0x04) + assert not refusals, refusals + compile_check(hlsl) if failures: print("FAILED: %s" % ", ".join(failures)) return 1 From 1fd5475daedf183cf5a1fcecfb709f4414e5e40b Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Thu, 26 Nov 2026 21:41:07 +0000 Subject: [PATCH 05/11] tests: dispatch the binary16 BVH helper on WARP --- .../experiments/startup-gfx2hlsl-bvh-box32.md | 11 +++--- tests/startup_gfx2hlsl_bvh_check.py | 34 ++++++++++++++++--- 2 files changed, 36 insertions(+), 9 deletions(-) diff --git a/docs/experiments/startup-gfx2hlsl-bvh-box32.md b/docs/experiments/startup-gfx2hlsl-bvh-box32.md index 0f1bf29eec..3268e4e5ec 100644 --- a/docs/experiments/startup-gfx2hlsl-bvh-box32.md +++ b/docs/experiments/startup-gfx2hlsl-bvh-box32.md @@ -58,11 +58,12 @@ prints `dxc compile: skip` and does not count that as a pass. python -B tests/startup_gfx2hlsl_bvh_check.py dispatch warp ``` -The dispatch mode compiles the same helper with a `RWByteAddressBuffer` in place of the bound -`ByteAddressBuffer`, writes the two synthetic nodes and five rays, and compares all twenty result words on a -Microsoft Basic Render Driver (`1414:008c`, driver `10.0.26100.10068`). It also dispatches a mutant that leaves -missed child words in place; the case 2 word 0 must stop being `0xffffffff`. That control caught the first version -of this helper, which sorted the keys correctly but returned the original child pointer for a miss. +The dispatch mode compiles the helpers with a `RWByteAddressBuffer` in place of the bound +`ByteAddressBuffer`, writes the two FP32 nodes, one binary16 node and ten rays, and compares all forty result +words on a Microsoft Basic Render Driver (`1414:008c`, driver `10.0.26100.10068`). All five FP32 and all five +binary16 cases pass on WARP. It also dispatches a mutant that leaves missed child words in place; the case 2 word 0 +must stop being `0xffffffff`. That control caught the first version of this helper, which sorted the keys +correctly but returned the original child pointer for a miss. This is a translator slice. It does not execute the native gfx1030 probe, does not bind the node buffer on a D3D12 device, and does not establish any title behavior. diff --git a/tests/startup_gfx2hlsl_bvh_check.py b/tests/startup_gfx2hlsl_bvh_check.py index d35c62ab70..0894cae07e 100644 --- a/tests/startup_gfx2hlsl_bvh_check.py +++ b/tests/startup_gfx2hlsl_bvh_check.py @@ -112,6 +112,14 @@ def q(value): return quantized +HALF_BASE = 512 +HALF_NODES = half_nodes(NODES[0]) +HALF_RAYS = tuple( + (name, HALF_BASE, extent, origin, direction, reference(HALF_NODES, extent, origin, direction, True)) + for name, _offset, extent, origin, direction, _expected in RAYS +) + + def translate_program(*, node=0x05, sort_boxes=True, word0=0x00100000, word1=None, word2=0x0b, word3=RESOURCE_TYPE, loaded_descriptor=False, modifier="", opcode="image_bvh_intersect_ray", constant_node=True, stage_kind="cs"): @@ -312,6 +320,11 @@ def dispatch_hlsl(mutate_miss=False): lines.append(" data.Store(%du, %s);" % (base_offset + 16 + 24 * i + 12 + 4 * j, fbits(hi[j]))) for i in range(4): lines.append(" data.Store(%du, 0u);" % (base_offset + 112 + 4 * i)) + for i, (child, lo, hi) in enumerate(HALF_NODES): + lines.append(" data.Store(%du, 0x%08xu);" % (HALF_BASE + 4 * i, child)) + packed = struct.unpack("<3I", struct.pack("<6e", *lo, *hi)) + for j, word in enumerate(packed): + lines.append(" data.Store(%du, 0x%08xu);" % (HALF_BASE + 16 + 12 * i + 4 * j, word)) lines.append(" DeviceMemoryBarrierWithGroupSync();") for case, (_name, offset, extent, origin, direction, _expected) in enumerate(RAYS): inv = tuple(1.0 / c for c in direction) @@ -321,7 +334,16 @@ def dispatch_hlsl(mutate_miss=False): case, (offset >> 3) | 5, ffloat(extent), ffloat(origin[0]), ffloat(origin[1]), ffloat(origin[2]), ffloat(inv[0]), ffloat(inv[1]), ffloat(inv[2]))) for word in range(4): - lines.append(" data.Store(%du, r%d.%s);" % (512 + 16 * case + 4 * word, case, "xyzw"[word])) + lines.append(" data.Store(%du, r%d.%s);" % (576 + 16 * case + 4 * word, case, "xyzw"[word])) + for case, (_name, offset, extent, origin, direction, _expected) in enumerate(HALF_RAYS): + inv = tuple(1.0 / c for c in direction) + lines.append( + " uint4 h%d = x2w_bvh_intersect_box16(data, 0x%08xu, 0x00100000u, 0x80000000u, " + "0x00000040u, 0x80000000u, %s, float3(%s, %s, %s), float3(%s, %s, %s));" % ( + case, (offset >> 3) | 4, ffloat(extent), ffloat(origin[0]), ffloat(origin[1]), + ffloat(origin[2]), ffloat(inv[0]), ffloat(inv[1]), ffloat(inv[2]))) + for word in range(4): + lines.append(" data.Store(%du, h%d.%s);" % (672 + 16 * case + 4 * word, case, "xyzw"[word])) lines.append("}") return "\n".join(lines) + "\n" @@ -336,7 +358,7 @@ def run_dispatch(dxc, runner, adapter, directory, mutate=False): capture_output=True, text=True) if compiled.returncode or compiled.stderr: raise AssertionError(compiled.stderr or "dxc exited with %d" % compiled.returncode) - result = subprocess.run([runner, adapter, "--raw-uav-dump", str(cso), "1", "592", str(output)], + result = subprocess.run([runner, adapter, "--raw-uav-dump", str(cso), "1", "768", str(output)], capture_output=True, text=True) print(result.stdout, end="") if result.returncode == 77: @@ -361,14 +383,18 @@ def check_dispatch(dxc, runner, adapter): print("dispatch: skip (adapter unavailable)") return 77 for case, (_name, _offset, _extent, _origin, _direction, expected) in enumerate(RAYS): - got = tuple(words[128 + 4 * case:132 + 4 * case]) + got = tuple(words[144 + 4 * case:148 + 4 * case]) check("dispatch case %d %s" % (case, _name), got == expected, "got %s expected %s" % (["%08x" % w for w in got], ["%08x" % w for w in expected])) + for case, (_name, _offset, _extent, _origin, _direction, expected) in enumerate(HALF_RAYS): + got = tuple(words[168 + 4 * case:172 + 4 * case]) + check("dispatch box16 case %d %s" % (case, _name), got == expected, + "got %s expected %s" % (["%08x" % w for w in got], ["%08x" % w for w in expected])) status, mutant = run_dispatch(dxc, runner, adapter, directory, mutate=True) if status == 77: print("dispatch control: skip (adapter unavailable)") return 77 - changed = mutant[128:132] + changed = mutant[144:148] check("dispatch miss-fill control decays case 2", tuple(changed) != (INVALID,) * 4, "got %s" % ["%08x" % w for w in changed]) if failures: From 94e90292e73a4eff8375d292e0453834e76a8092 Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Fri, 27 Nov 2026 08:53:51 +0000 Subject: [PATCH 06/11] startup: keep unsorted BVH hits in child order --- .../experiments/startup-gfx2hlsl-bvh-box32.md | 20 +++++++------ tests/startup_gfx2hlsl_bvh_check.py | 30 +++++++++++++++---- tools/startup/gfx2hlsl.py | 22 ++++++++++---- 3 files changed, 52 insertions(+), 20 deletions(-) diff --git a/docs/experiments/startup-gfx2hlsl-bvh-box32.md b/docs/experiments/startup-gfx2hlsl-bvh-box32.md index 928459f57f..8e9521be92 100644 --- a/docs/experiments/startup-gfx2hlsl-bvh-box32.md +++ b/docs/experiments/startup-gfx2hlsl-bvh-box32.md @@ -41,21 +41,23 @@ emits no helper call and no destination VGPR assignment. python -B tests/startup_gfx2hlsl_bvh_check.py ``` -The check compares the CPU box reference with the fixture in `tests/gfx1030_bvh_box/check.py` for five rays, -compares the emitted sort network with the same reference, checks the sort-bit negative control (word 0 changes -from `0x1d` to `0x25`), translates a synthetic constant-T# program and checks the four child results and the -manifest, and checks every refusal above. It also compiles the translated compute shader with DXC when one is -available; without DXC it prints `dxc compile: skip` and does not count that as a pass. +The check compares the CPU box reference with the fixture in `tests/gfx1030_bvh_box/check.py` for six rays, +compares the emitted helper with the same reference, checks the sort-bit negative control (word 0 changes from +`0x1d` to `0x25`), checks the three-hit sort-disabled case whose equal keys must stay in child order +(`0x25, 0x2d, 0x35, 0xffffffff`), translates a synthetic constant-T# program and checks the four child results +and the manifest, and checks every refusal above. It also compiles the translated compute shader with DXC when +one is available; without DXC it prints `dxc compile: skip` and does not count that as a pass. ```text python -B tests/startup_gfx2hlsl_bvh_check.py dispatch warp ``` The dispatch mode compiles the same helper with a `RWByteAddressBuffer` in place of the bound -`ByteAddressBuffer`, writes the two synthetic nodes and five rays, and compares all twenty result words on a -Microsoft Basic Render Driver (`1414:008c`, driver `10.0.26100.10068`). It also dispatches a mutant that leaves -missed child words in place; the case 2 word 0 must stop being `0xffffffff`. That control caught the first version -of this helper, which sorted the keys correctly but returned the original child pointer for a miss. +`ByteAddressBuffer`, writes the three synthetic nodes and six rays, and compares all twenty-four result words on +a Microsoft Basic Render Driver (`1414:008c`, driver `10.0.26100.10068`). It also dispatches a mutant that +leaves missed child words in place; the all-miss case 2 word 0 at words 136..139 must stop being +`0xffffffff`. That control caught the first version of this helper, which sorted the keys correctly but +returned the original child pointer for a miss. This is a translator slice. It does not execute the native gfx1030 probe, does not bind the node buffer on a D3D12 device, and does not establish any title behavior. diff --git a/tests/startup_gfx2hlsl_bvh_check.py b/tests/startup_gfx2hlsl_bvh_check.py index cc40ed6667..35cecf48d9 100644 --- a/tests/startup_gfx2hlsl_bvh_check.py +++ b/tests/startup_gfx2hlsl_bvh_check.py @@ -39,6 +39,7 @@ def box(child, depth, x=-8): NODES = { 0: (box(0x25, 4), box(0x1d, 1), box(0x2d, 2, x=32), box(INVALID, 3)), 256: (box(0x45, 7), box(0x3d, 5), box(0x35, 3), box(0x0d, 1)), + 384: (box(0x25, 4), box(INVALID, 1), box(0x2d, 2), box(0x35, 3)), } ORIGIN = (0.5, -0.5, -1.0) FORWARD = (0.25, -0.125, 0.5) @@ -49,6 +50,9 @@ def box(child, depth, x=-8): ("all_four", 256, 19.0, ORIGIN, FORWARD, (0x0d, 0x35, 0x3d, 0x45)), ("reverse", 0, 21.0, (0.0, 0.0, 10.0), (0.25, -0.125, -0.5), (0x25, 0x1d, INVALID, INVALID)), ) +UNSORTED_RAYS = ( + ("unsorted_three_hits", 384, 19.0, ORIGIN, FORWARD, (0x25, 0x2d, 0x35, INVALID)), +) failures = [] @@ -96,6 +100,9 @@ def model(nodes, extent, origin, direction, sort_boxes): items.append([child, tmin if sort_boxes else 0.0]) else: items.append([INVALID, FLT_MAX]) + if not sort_boxes: + ordered = [child for child, _key in items if child != INVALID] + return tuple(ordered) + (INVALID,) * (4 - len(ordered)) for a, b in ((0, 1), (2, 3), (0, 2), (1, 3), (1, 2)): if items[b][1] < items[a][1]: items[a], items[b] = items[b], items[a] @@ -169,6 +176,13 @@ def controls(): check("model without the sort bit matches the unsorted reference", model(NODES[0], 19.0, ORIGIN, FORWARD, False) == unsorted, str((model(NODES[0], 19.0, ORIGIN, FORWARD, False), unsorted))) + for name, offset, extent, origin, direction, expected in UNSORTED_RAYS: + actual = reference(NODES[offset], extent, origin, direction, False) + check("CPU reference keeps child order with the sort bit clear (%s)" % name, actual == expected, + str((actual, expected))) + actual = model(NODES[offset], extent, origin, direction, False) + check("helper keeps child order with the sort bit clear (%s)" % name, actual == expected, + str((actual, expected))) check("all-miss result is four 0xffffffff words", reference(NODES[0], 2.0, ORIGIN, FORWARD, True) == (INVALID,) * 4, "") @@ -290,12 +304,13 @@ def dispatch_hlsl(mutate_miss=False): for i in range(4): lines.append(" data.Store(%du, 0u);" % (base_offset + 112 + 4 * i)) lines.append(" DeviceMemoryBarrierWithGroupSync();") - for case, (_name, offset, extent, origin, direction, _expected) in enumerate(RAYS): + for case, (_name, offset, extent, origin, direction, _expected) in enumerate(RAYS + UNSORTED_RAYS): inv = tuple(1.0 / c for c in direction) + sort_word = "0x80000000u" if case < len(RAYS) else "0x00000000u" lines.append( - " uint4 r%d = x2w_bvh_intersect_box32(data, 0x%08xu, 0x00100000u, 0x80000000u, " + " uint4 r%d = x2w_bvh_intersect_box32(data, 0x%08xu, 0x00100000u, %s, " "0x0000000bu, 0x80000000u, %s, float3(%s, %s, %s), float3(%s, %s, %s));" % ( - case, (offset >> 3) | 5, ffloat(extent), ffloat(origin[0]), ffloat(origin[1]), + case, (offset >> 3) | 5, sort_word, ffloat(extent), ffloat(origin[0]), ffloat(origin[1]), ffloat(origin[2]), ffloat(inv[0]), ffloat(inv[1]), ffloat(inv[2]))) for word in range(4): lines.append(" data.Store(%du, r%d.%s);" % (512 + 16 * case + 4 * word, case, "xyzw"[word])) @@ -313,7 +328,7 @@ def run_dispatch(dxc, runner, adapter, directory, mutate=False): capture_output=True, text=True) if compiled.returncode or compiled.stderr: raise AssertionError(compiled.stderr or "dxc exited with %d" % compiled.returncode) - result = subprocess.run([runner, adapter, "--raw-uav-dump", str(cso), "1", "592", str(output)], + result = subprocess.run([runner, adapter, "--raw-uav-dump", str(cso), "1", "608", str(output)], capture_output=True, text=True) print(result.stdout, end="") if result.returncode == 77: @@ -341,11 +356,16 @@ def check_dispatch(dxc, runner, adapter): got = tuple(words[128 + 4 * case:132 + 4 * case]) check("dispatch case %d %s" % (case, _name), got == expected, "got %s expected %s" % (["%08x" % w for w in got], ["%08x" % w for w in expected])) + for extra, (_name, _offset, _extent, _origin, _direction, expected) in enumerate(UNSORTED_RAYS): + case = len(RAYS) + extra + got = tuple(words[128 + 4 * case:132 + 4 * case]) + check("dispatch case %d %s" % (case, _name), got == expected, + "got %s expected %s" % (["%08x" % w for w in got], ["%08x" % w for w in expected])) status, mutant = run_dispatch(dxc, runner, adapter, directory, mutate=True) if status == 77: print("dispatch control: skip (adapter unavailable)") return 77 - changed = mutant[128:132] + changed = mutant[136:140] check("dispatch miss-fill control decays case 2", tuple(changed) != (INVALID,) * 4, "got %s" % ["%08x" % w for w in changed]) if failures: diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index e168f447ff..6912c58f1a 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -10785,12 +10785,22 @@ def read(fmt, data, offset): ' c1 = h1 ? c1 : X2W_BVH_MISS;', ' c2 = h2 ? c2 : X2W_BVH_MISS;', ' c3 = h3 ? c3 : X2W_BVH_MISS;', - # A disabled sort uses one key for every hit: the network then only compacts misses, - # while an enabled sort orders the hits by entry distance. - ' float k0 = h0 ? (sort_boxes ? d0 : 0.0) : 3.402823466e+38;', - ' float k1 = h1 ? (sort_boxes ? d1 : 0.0) : 3.402823466e+38;', - ' float k2 = h2 ? (sort_boxes ? d2 : 0.0) : 3.402823466e+38;', - ' float k3 = h3 ? (sort_boxes ? d3 : 0.0) : 3.402823466e+38;', + # Sorting disabled keeps the children in their original order. Do not reuse the sort network: + # its nonadjacent compare-exchange stages move a later hit into an earlier position while + # compacting the miss between them, which reorders equal keys. + ' if (!sort_boxes) {', + ' uint4 ordered = miss;', + ' uint n = 0u;', + ' if (h0) ordered[n++] = c0;', + ' if (h1) ordered[n++] = c1;', + ' if (h2) ordered[n++] = c2;', + ' if (h3) ordered[n++] = c3;', + ' return ordered;', + ' }', + ' float k0 = h0 ? d0 : 3.402823466e+38;', + ' float k1 = h1 ? d1 : 3.402823466e+38;', + ' float k2 = h2 ? d2 : 3.402823466e+38;', + ' float k3 = h3 ? d3 : 3.402823466e+38;', ' x2w_bvh_sort_pair(c0, c1, k0, k1);', ' x2w_bvh_sort_pair(c2, c3, k2, k3);', ' x2w_bvh_sort_pair(c0, c2, k0, k2);', From b7117d4646a94ad6e4a55d8b3f1357bdb5398b27 Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Fri, 27 Nov 2026 14:05:36 +0000 Subject: [PATCH 07/11] docs: correct the binary16 node count in the BVH receipt --- docs/experiments/startup-gfx2hlsl-bvh-box32.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/experiments/startup-gfx2hlsl-bvh-box32.md b/docs/experiments/startup-gfx2hlsl-bvh-box32.md index 29581cb27d..e598f60279 100644 --- a/docs/experiments/startup-gfx2hlsl-bvh-box32.md +++ b/docs/experiments/startup-gfx2hlsl-bvh-box32.md @@ -71,7 +71,7 @@ python -B tests/startup_gfx2hlsl_bvh_check.py dispatch w ``` The dispatch mode compiles both helpers with a `RWByteAddressBuffer` in place of the bound -`ByteAddressBuffer`, writes four FP32 nodes, three binary16 nodes and twenty-one rays, and compares the +`ByteAddressBuffer`, writes four FP32 nodes, four binary16 nodes and twenty-one rays, and compares the four result DWORDs for every case (1232-byte readback). All eight sorted FP32 cases, three unsorted FP32 cases, eight sorted binary16 cases (including the rounded bound and both encoded bases) and two unsorted binary16 cases pass on a Microsoft Basic Render Driver (`1414:008c`, driver `10.0.26100.10068`) and on an From 5640a90392adf25e2ae3ef29e55245596d844073 Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Fri, 27 Nov 2026 14:51:43 +0000 Subject: [PATCH 08/11] startup: lower triangle nodes in image_bvh_intersect_ray Accept the 64-byte triangle node forms (kinds 0..3), decode their four ID maps and base vertex triples, and emit a watertight ray/triangle helper for return mode 1. The helper returns {t, det, v, w} and keeps the 48-bit descriptor rules. 119 CPU witnesses pass bit-for-bit on WARP and the RX 9060 XT in dev and release, with four negative mutations; the existing box tests remain green. --- .../startup-gfx2hlsl-bvh-triangle.md | 75 +++++ .../cmake/startup_gfx2hlsl_bvh_triangle.cmake | 15 + tests/startup_gfx2hlsl_bvh_check.py | 11 +- tests/startup_gfx2hlsl_bvh_triangle_check.py | 311 ++++++++++++++++++ tools/startup/gfx2hlsl.py | 117 ++++++- 5 files changed, 507 insertions(+), 22 deletions(-) create mode 100644 docs/experiments/startup-gfx2hlsl-bvh-triangle.md create mode 100644 tests/cmake/startup_gfx2hlsl_bvh_triangle.cmake create mode 100644 tests/startup_gfx2hlsl_bvh_triangle_check.py diff --git a/docs/experiments/startup-gfx2hlsl-bvh-triangle.md b/docs/experiments/startup-gfx2hlsl-bvh-triangle.md new file mode 100644 index 0000000000..c5b8691f6e --- /dev/null +++ b/docs/experiments/startup-gfx2hlsl-bvh-triangle.md @@ -0,0 +1,75 @@ +# `image_bvh_intersect_ray` triangle nodes + +`tools/startup/gfx2hlsl.py` now lowers the 64-byte triangle node forms (kinds 0..3) of the 32-bit +`image_bvh_intersect_ray` (RDNA 2 MIMG opcode 230), in addition to the FP32 and binary16 box nodes. + +## Node and test + +A triangle node is 64 bytes: five `float3` vertices at bytes 0..59 and one ID dword at byte 60. The +kind selects one of the four 8-bit maps in the ID dword. Each map holds `i` in two bits and `j` in +two bits; the third index is `(3 - i - j) & 3`. The kind also selects the base vertex triple, which +is the table in Mesa 25.1.0 RADV's `radv_bvh_triangle_node` (MIT): + +```text +kind 0: 0 1 2 +kind 1: 1 3 2 +kind 2: 2 3 4 +kind 3: 2 4 0 +``` + +The test is the watertight ray/triangle formulation from Woop, Benthin and Wald, as RADV uses it. +The helper projects the vertices onto the dominant ray axis, shears them, computes the three +barycentric numerators `u`, `v` and `w`, the determinant `u + (v + w)` and +`t = u*az + v*bz + w*cz` in binary32. A hit requires all three barycentrics to share a sign and +`t` to have the matching sign. The instruction does not test `ray_extent` for triangles. + +## Return and descriptor + +Triangle return mode 1 (bit 120 of the BVH T#, bit 24 of descriptor DWORD 3) returns the four words +`{t, determinant, v, w}` as float bit patterns. A miss is `{+inf, 1.0, 0, 0}`. Return mode 0 and +every other reserved word-3 bit are refused by name before any HLSL is emitted. + +The accepted slice uses: + +- compute stage only; +- `image_bvh_intersect_ray v[4], v[11], s[4]` with the packed address form; +- a constant inline T# built by four SGPR constants, type 8, nonzero encoded base, box growing zero, + size at least one 64-byte unit and below 4 GiB; +- a constant node pointer whose low three bits are 0..3 and whose address is inside the descriptor + size and the 48-bit absolute address space; +- either value of the sort bit; it is ignored for triangles. + +The manifest still names the allocation with `srv bvh base 0x size 0x`, using the +decoded byte address for `base`. The host binding of that line remains outside this change. + +## Refused by name + +Return mode 0, every node kind other than 0..3, `image_bvh64_intersect_ray`, A16, non-sequential +addresses, a pixel or vertex stage, a node pointer that is not a straight-line constant, a T# loaded +at run time, a type other than 8, nonzero box growing, an absolute (zero) base, a size that does not +cover the node, size bits above 4 GiB, a 48-bit node wrap, and every reserved T# field. The checks +assert that a refusal emits no helper call and no destination VGPR assignment. + +## Evidence + +```sh +python3 -B tests/startup_gfx2hlsl_bvh_triangle_check.py +python3 -B tests/startup_gfx2hlsl_bvh_triangle_check.py dispatch warp +``` + +The check reuses the 119 triangle witnesses in `tests/gfx1030_bvh_box/check.py` and the independent +model in `tests/gfx1030_bvh_box/bvh_model.py`. It covers all four kinds, every ID map byte, edge and +vertex hits, outside and behind rays, zero direction and negative zero, `t = 0`, `extent = 0`, +1024x scaling in both directions, degenerate and malformed nodes, and the box kinds 6 and 7. + +The dispatch writes 71 unique triangle images at 64-byte offsets, runs the emitted helper for all +119 witnesses, and compares all 476 result words. It passes on WARP (`1414:008c`, driver +`10.0.26100.10068`) and on an AMD Radeon RX 9060 XT (`1002:7590`, driver `32.0.32029.2010`), in +both the dev and release presets, with `dxc -Gis` matching the runtime's strict-IEEE compile. Four +mutants change the determinant sign, the ID shift, the `u` term and the miss words; each must change +at least one witness. The existing box32/box16 tests still pass 6/6 in both presets. + +This is a translator slice. It does not bind the node buffer on a D3D12 device, does not execute the +native gfx1030 probe, and does not establish title behavior. The runtime manifest loader does not yet +consume the `bvhbase` line, so a real dispatch is refused rather than bound at a wrong address. + diff --git a/tests/cmake/startup_gfx2hlsl_bvh_triangle.cmake b/tests/cmake/startup_gfx2hlsl_bvh_triangle.cmake new file mode 100644 index 0000000000..db06bf7e60 --- /dev/null +++ b/tests/cmake/startup_gfx2hlsl_bvh_triangle.cmake @@ -0,0 +1,15 @@ +# gfx2hlsl image_bvh_intersect_ray triangle-node slice: translator controls, a DXC compile when +# one is available, and a WARP/hardware dispatch when offscreen_check is built. +if(EXISTS "${INTAKE_PYTHON}") + add_test(NAME startup_gfx2hlsl_bvh_triangle COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_bvh_triangle_check.py") +endif() +if(EXISTS "${INTAKE_PYTHON}" AND TARGET offscreen_check) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_bvh_triangle_dispatch_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_bvh_triangle_check.py" dispatch "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_gfx2hlsl_bvh_triangle_dispatch_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() +endif() + diff --git a/tests/startup_gfx2hlsl_bvh_check.py b/tests/startup_gfx2hlsl_bvh_check.py index 5e7cfbdd40..36b9fa1842 100644 --- a/tests/startup_gfx2hlsl_bvh_check.py +++ b/tests/startup_gfx2hlsl_bvh_check.py @@ -3,8 +3,8 @@ The instruction is RDNA 2 MIMG opcode 230. This check covers the translator path and the box model only: a constant inline BVH T#[12:15], an 11-dword packed address, a constant node base whose low three bits are 4 (binary16) or 5 (FP32), and the four child results. -Triangle nodes, the 64-bit form, A16, NSA and every dynamic descriptor or node base are -refused by name before any HLSL is emitted. The independent CPU box reference is +The triangle kinds have a dedicated check. The 64-bit form, A16, NSA and every dynamic +descriptor or node base are refused by name before any HLSL is emitted. The independent CPU box reference is tests/gfx1030_bvh_box/bvh_model.py; the Windows dispatch exercises both emitted helpers. """ import math @@ -407,7 +407,6 @@ def controls(): # Every refusal must happen before a helper call or a result VGPR is emitted. cases = [ - ("triangle node", dict(node=0x00), "triangle node (kind 0)"), ("unknown node kind", dict(node=0x06), "node kind 6"), ("unaligned node", dict(node=0x0d), "not an aligned 128-byte node"), ("non-constant node", dict(constant_node=False), "non-constant node base"), @@ -422,7 +421,7 @@ def controls(): ("node outside size", dict(node=0x25, word2=3), "outside descriptor size"), ("box16 node outside size", dict(node=0x54, word2=10), "outside descriptor size"), ("absolute base", dict(word0=0, word1=0), "absolute node base"), - ("size high bits", dict(word3=RESOURCE_TYPE | 0x100), "size above 4 GiB"), + ("size high bits", dict(word3=RESOURCE_TYPE | 0x100), "does not match node kind 5"), ] for label, kwargs, reason in cases: if label == "NSA address": @@ -470,7 +469,7 @@ def compile_check(hlsl): with tempfile.TemporaryDirectory(dir=ROOT / "out" if (ROOT / "out").is_dir() else None) as temporary: source = Path(temporary) / "bvh_box.hlsl" source.write_text(hlsl, encoding="ascii") - result = subprocess.run([dxc, "-T", "cs_6_0", "-E", "main", "-Fo", str(source.with_suffix(".cso")), str(source)], + result = subprocess.run([dxc, "-Gis", "-T", "cs_6_0", "-E", "main", "-Fo", str(source.with_suffix(".cso")), str(source)], capture_output=True, text=True) if result.returncode or result.stderr: check("dxc compiles the translated helper", False, result.stderr or "exit %d" % result.returncode) @@ -550,7 +549,7 @@ def run_dispatch(dxc, runner, adapter, directory, mutation=None): cso = directory / (name + ".cso") output = directory / (name + ".bin") source.write_text(dispatch_hlsl(mutation), encoding="ascii") - compiled = subprocess.run([dxc, "-T", "cs_6_0", "-E", "main", "-Fo", str(cso), str(source)], + compiled = subprocess.run([dxc, "-Gis", "-T", "cs_6_0", "-E", "main", "-Fo", str(cso), str(source)], capture_output=True, text=True) if compiled.returncode or compiled.stderr: raise AssertionError(compiled.stderr or "dxc exited with %d" % compiled.returncode) diff --git a/tests/startup_gfx2hlsl_bvh_triangle_check.py b/tests/startup_gfx2hlsl_bvh_triangle_check.py new file mode 100644 index 0000000000..a2c749f9f4 --- /dev/null +++ b/tests/startup_gfx2hlsl_bvh_triangle_check.py @@ -0,0 +1,311 @@ +"""image_bvh_intersect_ray: the triangle-node (kinds 0..3) translation slice. + +The instruction is RDNA 2 MIMG opcode 230. A triangle node is 64 bytes: five float3 vertices +and one ID dword. This check covers the translator, the watertight ray/triangle test and the +four-word return `{t, determinant, v, w}` for triangle return mode 1. The independent model is +tests/gfx1030_bvh_box/bvh_model.py; the dispatch runs the emitted helper on WARP or hardware. +""" +import math +import os +from pathlib import Path +import shutil +import struct +import subprocess +import sys +import tempfile + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parent +sys.path.insert(0, str(ROOT / "tools")) +sys.path.insert(0, str(ROOT / "tools" / "startup")) +sys.path.insert(0, str(HERE)) +sys.path.insert(0, str(HERE / "gfx1030_bvh_box")) +import gfx2hlsl as G # noqa: E402 +import startup_gfx2hlsl_bvh_check as BOX # noqa: E402 +import check as F # noqa: E402 +from gfx1030_bvh_box import bvh_model as B # noqa: E402 + +SORT_ENABLE = 1 << 31 +RESOURCE_TYPE = 1 << 31 +TRIANGLE_MODE = 1 << 24 +TRIANGLES = tuple(case for case in F.WITNESSES if case.name.startswith("tri/") and not case.wide) + +failures = [] + + +def check(label, ok, detail=""): + print("%s: %s" % (label, "ok" if ok else "MISMATCH"), flush=True) + if not ok: + failures.append(label) + if detail: + print(" " + detail) + + +def translate_triangle(node, **kwargs): + kwargs.setdefault("word3", RESOURCE_TYPE | TRIANGLE_MODE) + return BOX.translate_program(node=node, **kwargs) + + +def controls(): + bad = None + for case in TRIANGLES: + origin, direction, inverse, extent = case.ray + actual = tuple(B.intersect( + bytearray(case.image), B.descriptor(0, sort=True), case.pointer, + origin=origin, direction=direction, inverse=inverse, extent=extent)) + if actual != case.expected: + bad = (case.name, actual, case.expected) + break + check("independent model matches every triangle fixture", bad is None, str(bad)) + + for kind in range(4): + pipe, hlsl, refusals = translate_triangle(kind) + check("triangle kind %d translates" % kind, pipe is not None and not refusals, str(refusals)) + if pipe is None: + continue + manifest = pipe.manifest() + check("triangle kind %d manifest names the node allocation" % kind, + "srv 0 bvh base 0x100000 size 0xb" in manifest, manifest) + check("triangle kind %d HLSL contains the helper" % kind, + "uint4 x2w_bvh_intersect_triangle" in hlsl and "x2w_bvh_triangle_vertex" in hlsl + and "x2w_bvh_shear" in hlsl, "") + call_line = next((line for line in hlsl.splitlines() if "x2w_bvh_intersect_triangle(r0" in line), "") + check("triangle kind %d call carries all four descriptor DWORDs" % kind, + "0x00001000u, 0x80000000u, 0x0000000bu, 0x81000000u" in call_line, call_line) + check("triangle kind %d call carries the node and four results" % kind, + "0x0000000%du" % kind in call_line + and all("v%d = bt" % reg in hlsl for reg in range(32, 36)), call_line) + + pipe, hlsl, refusals = translate_triangle(0x00, sort_boxes=False) + check("sort-disabled triangle translates", pipe is not None and not refusals, str(refusals)) + if pipe is not None: + call = next((line for line in hlsl.splitlines() if "x2w_bvh_intersect_triangle(r0" in line), "") + check("sort-disabled triangle call keeps the zero sort word", + "0x00001000u, 0x00000000u, 0x0000000bu, 0x81000000u" in call, call) + + helpers = "\n".join(G.BVH_HELPERS) + check("translated triangle shader embeds the dispatch-tested helpers", + hlsl is not None and helpers in hlsl, "") + + cases = [ + ("triangle return mode 0", dict(node=0x00, word3=RESOURCE_TYPE), "does not match node kind 0"), + ("box return mode 1", dict(node=0x05, word3=RESOURCE_TYPE | TRIANGLE_MODE), "does not match node kind 5"), + ("unknown node kind", dict(node=0x06), "node kind 6"), + ("size zero", dict(node=0x00, word2=0), "does not cover the node"), + ("node outside size", dict(node=0x20, word2=4), "outside descriptor size"), + ("absolute base", dict(node=0x00, word0=0, word1=0), "absolute node base"), + ("loaded descriptor", dict(node=0x00, loaded_descriptor=True), "loaded at run time"), + ("descriptor type", dict(node=0x00, word3=0x60000000), "descriptor type 6 is not 8"), + ("box growing", dict(node=0x00, word1=SORT_ENABLE | (2 << 23)), "box growing amount 2"), + ("reserved word 1", dict(node=0x00, word1=SORT_ENABLE | 0x100), "reserved word 1"), + ("8-bit return mode extra bit", dict(node=0x00, word3=RESOURCE_TYPE | TRIANGLE_MODE | 0x100), + "does not match node kind 0"), + ("64-bit form", dict(node=0x00, opcode="image_bvh64_intersect_ray"), "image_bvh64_intersect_ray"), + ("A16", dict(node=0x00, modifier="a16"), "modifier a16"), + ("unaligned box32 node", dict(node=0x0d), "not an aligned 128-byte node"), + ] + for label, kwargs, reason in cases: + if label == "NSA address": + pipe, hlsl, refusals = None, None, [] + try: + G.Stage.op_image_bvh_intersect_ray( + type("P", (), {"kind": "cs", "const_u32": lambda self, tok: 0})(), + ("v[32:35]", "[v0, v2, v4, v6, v8, v10, v12, v14, v16, v18, v20]", "s[12:15]"), []) + except G.Unsupported as error: + refusals = [str(error)] + else: + pipe, hlsl, refusals = translate_triangle(**kwargs) + ok = len(refusals) == 1 and reason in refusals[0] + check("refuses %s" % label, ok, str(refusals)) + if hlsl is not None: + check(" no partial output for %s" % label, + "uint4 bt" not in hlsl and "x2w_bvh_intersect_triangle(r" not in hlsl, "") + + words = (0xffffffff, SORT_ENABLE | 0xff, 0x0b, RESOURCE_TYPE | TRIANGLE_MODE) + pipe, boundary_hlsl, refusals = translate_triangle(0x10, word0=words[0], word1=words[1]) + check("triangle node ending exactly at the 48-bit boundary translates", + pipe is not None and not refusals, str(refusals)) + pipe, wrap_hlsl, refusals = translate_triangle(0x20, word0=words[0], word1=words[1]) + check("refuses a triangle 48-bit wrap before resource binding", + refusals == ["image_bvh_intersect_ray node address wraps the 48-bit address space"] + and " bvh base " not in pipe.manifest() + and "x2w_bvh_intersect_triangle" not in wrap_hlsl and "uint4 bt" not in wrap_hlsl, str(refusals)) + + pipe, hlsl, refusals = translate_triangle(0x00, stage_kind="ps") + check("refuses a triangle pixel stage", len(refusals) == 1 and "outside a compute stage" in refusals[0], str(refusals)) + + +def find_dxc(): + named = os.environ.get("X2W_DXC") + if named and Path(named).is_file(): + return str(Path(named)) + found = shutil.which("dxc") + if found: + return found + kits = os.environ.get("ProgramFiles(x86)", "") + if kits: + candidates = sorted((Path(kits) / "Windows Kits" / "10" / "bin").glob("*/x64/dxc.exe"), reverse=True) + if candidates: + return str(candidates[0]) + return None + + +def compile_check(hlsl): + dxc = find_dxc() + if dxc is None: + print("dxc compile: skip (no dxc on this host)") + return None + with tempfile.TemporaryDirectory(dir=ROOT / "out" if (ROOT / "out").is_dir() else None) as temporary: + source = Path(temporary) / "bvh_triangle.hlsl" + source.write_text(hlsl, encoding="ascii") + result = subprocess.run([dxc, "-Gis", "-T", "cs_6_0", "-E", "main", "-Fo", str(source.with_suffix(".cso")), str(source)], + capture_output=True, text=True) + if result.returncode or result.stderr: + check("dxc compiles the translated triangle helper", False, result.stderr or "exit %d" % result.returncode) + return False + print("dxc compile: ok (%s)" % dxc) + return True + + +def ffloat(value): + return "asfloat(0x%08xu)" % struct.unpack(" 0.0 && t >= 0.0) || (det < 0.0 && t <= 0.0);", + "bool ahead = (det > 0.0 && t >= 0.0) || (det > 0.0 && t <= 0.0);"), + "id_shift": ( + "uint id_byte = (id >> (8u * kind)) & 0xffu;", + "uint id_byte = id & 0xffu;"), + "u_sign": ( + "float u = sc.x * sb.y - sc.y * sb.x;", + "float u = sc.x * sb.y + sc.y * sb.x;"), + "miss_words": ( + "uint4 miss = uint4(0x7f800000u, 0x3f800000u, 0u, 0u);", + "uint4 miss = uint4(0u, 0u, 0u, 0u);"), +} + + +def dispatch_hlsl(mutation=None): + helpers = "\n".join(G.BVH_HELPERS).replace("ByteAddressBuffer", "RWByteAddressBuffer") + if mutation: + old, new = MUTATIONS[mutation] + assert helpers.count(old) == 1, (mutation, old) + helpers = helpers.replace(old, new) + images, offsets, result_offset, _buffer_size = triangle_layout() + lines = [helpers, "RWByteAddressBuffer data : register(u0);", "[numthreads(1, 1, 1)]", "void main() {"] + for image in images: + base = offsets[image] + for i in range(16): + lines.append(" data.Store(%du, 0x%08xu);" % (base + 4 * i, struct.unpack_from("> 3) | witness.pointer + lines.append( + " uint4 r%d = x2w_bvh_intersect_triangle(data, 0x%08xu, 0x1000u, 0x80000000u, " + "0x400u, 0x81000000u, float3(%s, %s, %s), float3(%s, %s, %s), float3(%s, %s, %s));" % ( + case, pointer, ffloat(origin[0]), ffloat(origin[1]), ffloat(origin[2]), + ffloat(direction[0]), ffloat(direction[1]), ffloat(direction[2]), + ffloat(inverse[0]), ffloat(inverse[1]), ffloat(inverse[2]))) + for word in range(4): + lines.append(" data.Store(%du, r%d.%s);" % (result_offset + 16 * case + 4 * word, case, "xyzw"[word])) + lines.append("}") + return "\n".join(lines) + "\n" + + +def run_dispatch(dxc, runner, adapter, directory, mutation=None): + _images, _offsets, _result_offset, buffer_size = triangle_layout() + name = "bvh_triangle_" + mutation if mutation else "bvh_triangle" + source = directory / (name + ".hlsl") + cso = directory / (name + ".cso") + output = directory / (name + ".bin") + source.write_text(dispatch_hlsl(mutation), encoding="ascii") + compiled = subprocess.run([dxc, "-Gis", "-T", "cs_6_0", "-E", "main", "-Fo", str(cso), str(source)], + capture_output=True, text=True) + if compiled.returncode or compiled.stderr: + raise AssertionError(compiled.stderr or "dxc exited with %d" % compiled.returncode) + result = subprocess.run([runner, adapter, "--raw-uav-dump", str(cso), "1", str(buffer_size), str(output)], + capture_output=True, text=True) + print(result.stdout, end="") + if result.returncode == 77: + return 77, None + if result.returncode or result.stderr: + raise AssertionError(result.stderr or "offscreen_check exited with %d" % result.returncode) + data = output.read_bytes() + assert len(data) == buffer_size, (len(data), buffer_size) + return 0, struct.unpack("<%dI" % (len(data) // 4), data) + + +def check_dispatch(dxc, runner, adapter): + controls() + if failures: + return 1 + if not dxc or not runner: + print("dispatch: skip (no dxc or offscreen_check)") + return 77 + out = ROOT / "out" + out.mkdir(exist_ok=True) + _images, _offsets, result_offset, _buffer_size = triangle_layout() + result_word = result_offset // 4 + with tempfile.TemporaryDirectory(dir=out) as temporary: + directory = Path(temporary) + status, words = run_dispatch(dxc, runner, adapter, directory) + if status == 77: + print("dispatch: skip (adapter unavailable)") + return 77 + for case, witness in enumerate(TRIANGLES): + start = result_word + 4 * case + got = tuple(words[start:start + 4]) + check("dispatch triangle %d %s" % (case, witness.name), got == witness.expected, + "got %s expected %s" % (["%08x" % w for w in got], ["%08x" % w for w in witness.expected])) + for mutation in MUTATIONS: + status, mutant = run_dispatch(dxc, runner, adapter, directory, mutation=mutation) + if status == 77: + print("dispatch control: skip (adapter unavailable)") + return 77 + changed = sum(tuple(mutant[result_word + 4 * case:result_word + 4 * case + 4]) != witness.expected + for case, witness in enumerate(TRIANGLES)) + check("dispatch %s control changes a triangle result" % mutation, changed > 0, str(changed)) + if failures: + print("FAILED: %s" % ", ".join(failures)) + return 1 + print("dispatch: all ok on %s" % adapter) + return 0 + + +def main(): + if len(sys.argv) == 5 and sys.argv[1] == "dispatch": + return check_dispatch(sys.argv[2], sys.argv[3], sys.argv[4]) + if len(sys.argv) != 1: + sys.exit(__doc__) + controls() + pipe, hlsl, refusals = translate_triangle(0x00) + assert not refusals, refusals + compile_check(hlsl) + if failures: + print("FAILED: %s" % ", ".join(failures)) + return 1 + print("startup gfx2hlsl bvh triangle: all ok") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) + diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index a4dc8dc125..2473664beb 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -8051,18 +8051,21 @@ def bvh_descriptor(self, tok): return (('bvhbase', base, values[2]), None), words, values def op_image_bvh_intersect_ray(self, ops, mods): - """Ray/box intersection for the 128-byte FP32 (kind 5) and 64-byte binary16 (kind 4) box nodes. + """Ray/box/triangle intersection for the 64-byte triangle (kinds 0..3), 64-byte binary16 + (kind 4) and 128-byte FP32 (kind 5) nodes. RDNA 2 ISA section 8.2.10 and Table 48: VDATA is four result dwords, VADDR is 11 dwords (node pointer, extent, origin xyz, direction xyz, inverse direction xyz) and SRSRC is the four-word BVH T# of Table 49. This first slice accepts only a straight-line compute program - with a constant node base, a constant inline T# and a node whose kind bits are 4 or 5. + with a constant node base, a constant inline T# and a node whose kind bits are 0..5. The descriptor base encodes address bits 47:8 in 256-byte units and binds a ByteAddressBuffer at that byte address; the node pointer is an offset in 8-byte units from that base. The emitted helper performs the four slab tests, clips against extent, replaces misses with 0xffffffff in their original slots, and sorts by entry distance only when the - descriptor's box-sorting enable bit is set. Triangle nodes, the 64-bit form, A16, - non-sequential addresses and every other node kind are refused by name. + descriptor's box-sorting enable bit is set. Triangle nodes use the watertight test and + return {t, determinant, v, w} for triangle return mode 1; the instruction does not test + ray_extent for them. The 64-bit form, A16, non-sequential addresses and every other node + kind are refused by name. """ name = 'image_bvh_intersect_ray' if self.kind != 'cs': @@ -8087,14 +8090,14 @@ def op_image_bvh_intersect_ray(self, ops, mods): if node is None: raise Unsupported('%s non-constant node base %s' % (name, cs[0])) kind = node & 7 - if 0 <= kind <= 3: - raise Unsupported('%s triangle node (kind %d) is not lowered' % (name, kind)) - if kind not in (4, 5): + if kind not in (0, 1, 2, 3, 4, 5): raise Unsupported('%s node kind %d is not lowered' % (name, kind)) + triangle = kind <= 3 half_box = kind == 4 - node_bytes = 64 if half_box else 128 + node_bytes = 64 if triangle or half_box else 128 node_offset = (node & 0xfffffff8) << 3 - if node_offset > (0xffffffc0 if half_box else 0xffffff80) or node_offset & (0x3f if half_box else 0x7f): + if node_offset > (0xffffffc0 if node_bytes == 64 else 0xffffff80) or \ + node_offset & (0x3f if node_bytes == 64 else 0x7f): raise Unsupported('%s node base %#x is not an aligned %u-byte node' % (name, node_offset, node_bytes)) key, words, vals = self.bvh_descriptor(ops[2]) if vals[1] is not None: @@ -8105,8 +8108,9 @@ def op_image_bvh_intersect_ray(self, ops, mods): if vals[3] is not None: if (vals[3] >> 28) & 0xf != 8: raise Unsupported('%s descriptor type %d is not 8' % (name, (vals[3] >> 28) & 0xf)) - if vals[3] & 0x0fffffff: - raise Unsupported('%s descriptor size above 4 GiB or reserved word 3 %#x' % (name, vals[3])) + expected_mode = 0x01000000 if triangle else 0 + if (vals[3] & 0x0fffffff) != expected_mode: + raise Unsupported('%s descriptor word 3 %#x does not match node kind %d' % (name, vals[3], kind)) base = key[0][1] if base == 0: raise Unsupported('%s absolute node base is not lowered' % name) @@ -8119,14 +8123,21 @@ def op_image_bvh_intersect_ray(self, ops, mods): raise Unsupported('%s node address wraps the 48-bit address space' % name) extent = self.f(cs[1]) origin = [self.f(cs[2 + i]) for i in range(3)] - [self.f(cs[5 + i]) for i in range(3)] # the instruction consumes ray_dir; the helper uses inv_dir + direction = [self.f(cs[5 + i]) for i in range(3)] inv_dir = [self.f(cs[8 + i]) for i in range(3)] res = self.pipe.resource(key, 'bvh') self.pipe.uses_bvh = True - call = '%s(%s, 0x%08xu, %s, %s, %s, %s, %s, float3(%s, %s, %s), float3(%s, %s, %s))' % ( - 'x2w_bvh_intersect_box16' if half_box else 'x2w_bvh_intersect_box32', - res, node, words[0], words[1], words[2], words[3], extent, - origin[0], origin[1], origin[2], inv_dir[0], inv_dir[1], inv_dir[2]) + if triangle: + call = ('x2w_bvh_intersect_triangle(%s, 0x%08xu, %s, %s, %s, %s, ' + 'float3(%s, %s, %s), float3(%s, %s, %s), float3(%s, %s, %s))') % ( + res, node, words[0], words[1], words[2], words[3], + origin[0], origin[1], origin[2], direction[0], direction[1], direction[2], + inv_dir[0], inv_dir[1], inv_dir[2]) + else: + call = '%s(%s, 0x%08xu, %s, %s, %s, %s, %s, float3(%s, %s, %s), float3(%s, %s, %s))' % ( + 'x2w_bvh_intersect_box16' if half_box else 'x2w_bvh_intersect_box32', + res, node, words[0], words[1], words[2], words[3], extent, + origin[0], origin[1], origin[2], inv_dir[0], inv_dir[1], inv_dir[2]) self.emit('uint4 bt%x = %s;' % (self.pc or 0, call)) for i in range(4): self.set_v(dst[1] + i, 'bt%x.%s' % (self.pc or 0, 'xyzw'[i])) @@ -11097,6 +11108,80 @@ def read(fmt, data, offset): ' word3 == 0x80000000u && word2 >= 1u && word2 < 0x04000000u &&', ' (word0 != 0u || (word1 & 0x000000ffu) != 0u);', '}', + # A triangle node is 64 bytes: five float3 vertices at 0..59 and one ID dword at 60. + # The kind selects one of four 8-bit maps: two bits for i, two for j, and a base vertex + # triple from RADV's radv_bvh_triangle_node (Mesa 25.1.0 bvh/bvh.h, MIT). + 'float x2w_bvh_component(float3 value, uint axis) {', + ' return axis == 0u ? value.x : (axis == 1u ? value.y : value.z);', + '}', + 'uint x2w_bvh_triangle_index(uint kind, uint slot) {', + ' if (slot == 0u) return kind == 0u ? 0u : (kind == 1u ? 1u : 2u);', + ' if (slot == 1u) return kind == 0u ? 1u : (kind == 1u ? 3u : (kind == 2u ? 3u : 4u));', + ' if (slot == 2u) return kind == 0u ? 2u : (kind == 1u ? 2u : (kind == 2u ? 4u : 0u));', + ' return 0u;', + '}', + 'float3 x2w_bvh_triangle_vertex(ByteAddressBuffer nodes, uint offset, uint kind, uint slot) {', + ' uint at = offset + 12u * x2w_bvh_triangle_index(kind, slot);', + ' return float3(asfloat(nodes.Load(at)), asfloat(nodes.Load(at + 4u)),', + ' asfloat(nodes.Load(at + 8u)));', + '}', + 'float3 x2w_bvh_shear(float3 vertex, float3 origin, float sx, float sy, float sz,', + ' uint kx, uint ky, uint kz) {', + ' float3 rel = vertex - origin;', + ' float rx = x2w_bvh_component(rel, kx);', + ' float ry = x2w_bvh_component(rel, ky);', + ' float rz = x2w_bvh_component(rel, kz);', + ' return float3(rx - sx * rz, ry - sy * rz, sz * rz);', + '}', + # Triangle return mode 1 (bit 120) is the only triangle mode this slice lowers. The box + # return mode is zero and is checked separately by each box helper. + 'bool x2w_bvh_triangle_descriptor_ok(uint word0, uint word1, uint word2, uint word3) {', + ' return (word1 & 0x7fffff00u) == 0u && (word3 & 0x0fffffffu) == 0x01000000u &&', + ' (word3 >> 28u) == 8u && word2 >= 1u && word2 < 0x04000000u &&', + ' (word0 != 0u || (word1 & 0x000000ffu) != 0u);', + '}', + 'uint4 x2w_bvh_intersect_triangle(ByteAddressBuffer nodes, uint node, uint word0, uint word1,', + ' uint word2, uint word3, float3 origin, float3 direction,', + ' float3 inv_dir) {', + ' uint4 miss = uint4(0x7f800000u, 0x3f800000u, 0u, 0u);', + ' uint kind = node & 7u;', + ' if (kind > 3u || !x2w_bvh_triangle_descriptor_ok(word0, word1, word2, word3)) return miss;', + ' uint offset = (node & 0xfffffff8u) << 3u;', + ' if ((offset >> 6u) + 1u > word2) return miss;', + ' uint id = nodes.Load(offset + 60u);', + ' uint id_byte = (id >> (8u * kind)) & 0xffu;', + ' uint i = id_byte & 3u;', + ' uint j = (id_byte >> 2u) & 3u;', + ' uint first = (3u - i - j) & 3u;', + ' float3 a = x2w_bvh_triangle_vertex(nodes, offset, kind, first);', + ' float3 b = x2w_bvh_triangle_vertex(nodes, offset, kind, i);', + ' float3 c = x2w_bvh_triangle_vertex(nodes, offset, kind, j);', + ' float3 ad = abs(direction);', + ' uint kz;', + ' if (ad.x >= ad.y) kz = ad.x >= ad.z ? 0u : 2u;', + ' else kz = ad.y >= ad.z ? 1u : 2u;', + ' uint kx = (kz + 1u) % 3u;', + ' uint ky = (kx + 1u) % 3u;', + ' if (x2w_bvh_component(direction, kz) < 0.0) {', + ' uint swap = kx; kx = ky; ky = swap;', + ' }', + ' float sz = x2w_bvh_component(inv_dir, kz);', + ' float sx = x2w_bvh_component(direction, kx) * sz;', + ' float sy = x2w_bvh_component(direction, ky) * sz;', + ' float3 sa = x2w_bvh_shear(a, origin, sx, sy, sz, kx, ky, kz);', + ' float3 sb = x2w_bvh_shear(b, origin, sx, sy, sz, kx, ky, kz);', + ' float3 sc = x2w_bvh_shear(c, origin, sx, sy, sz, kx, ky, kz);', + ' float u = sc.x * sb.y - sc.y * sb.x;', + ' float v = sa.x * sc.y - sa.y * sc.x;', + ' float w = sb.x * sa.y - sb.y * sa.x;', + ' bool behind = u < 0.0 || v < 0.0 || w < 0.0;', + ' bool before = u > 0.0 || v > 0.0 || w > 0.0;', + ' float det = u + (v + w);', + ' float t = (u * sa.z + v * sb.z) + w * sc.z;', + ' bool ahead = (det > 0.0 && t >= 0.0) || (det < 0.0 && t <= 0.0);', + ' if ((behind && before) || !ahead) return miss;', + ' return uint4(asuint(t), asuint(det), asuint(v), asuint(w));', + '}', # One FP32 box from a radv_bvh_box32_node (Mesa 25.1.0 bvh/bvh.h, MIT): children[4] at # bytes 0..15, coords[4][2][3] at 16..111 (lo then hi per child) and reserved at 112..127. 'float x2w_bvh_box32_slot(ByteAddressBuffer nodes, uint node_offset, uint index, float extent,', From 3ac44c2861b190e6635229a04e4d704872cf8e5e Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Fri, 27 Nov 2026 16:03:48 +0000 Subject: [PATCH 09/11] startup: treat the BVH descriptor size as a count minus one Size 0 is a one-unit span, so a binary16 node at offset zero accepts it and an FP32 node needs size 1 at offset zero. Use the decoded extent in the Python guard and both HLSL helpers, with exact-fit, too-short, upper-bound and boundary-dispatch controls. --- .../experiments/startup-gfx2hlsl-bvh-box32.md | 3 +- tests/startup_gfx2hlsl_bvh_check.py | 102 +++++++++++++++++- tools/startup/gfx2hlsl.py | 11 +- 3 files changed, 106 insertions(+), 10 deletions(-) diff --git a/docs/experiments/startup-gfx2hlsl-bvh-box32.md b/docs/experiments/startup-gfx2hlsl-bvh-box32.md index e598f60279..21acc67961 100644 --- a/docs/experiments/startup-gfx2hlsl-bvh-box32.md +++ b/docs/experiments/startup-gfx2hlsl-bvh-box32.md @@ -25,7 +25,8 @@ in `min.x`. - `image_bvh_intersect_ray v[4], v[11], s[4]` with the packed address form (the disassembler prints `v[16:31]` for the eleven consumed dwords); - a constant inline T# built by four SGPR constants, type 8, nonzero encoded base, box growing zero, - size that covers the node (one 64-byte unit for binary16, two for FP32) and below 4 GiB; + size field (a count minus one in 64-byte units) whose decoded extent covers the node (one unit + for binary16, two for FP32; `size=0` is a one-unit span) and below 4 GiB; - a constant node pointer whose low three bits are 4 (64-byte aligned) or 5 (128-byte aligned) and inside the same 4 GiB relative address window; the entire node must fit within the 48-bit absolute address space; - either value of the sort bit. diff --git a/tests/startup_gfx2hlsl_bvh_check.py b/tests/startup_gfx2hlsl_bvh_check.py index 5e7cfbdd40..9d04c1ef2d 100644 --- a/tests/startup_gfx2hlsl_bvh_check.py +++ b/tests/startup_gfx2hlsl_bvh_check.py @@ -398,10 +398,27 @@ def controls(): and " bvh base " not in pipe.manifest() and "x2w_bvh_intersect_box16" not in wrap_hlsl and "uint4 bt" not in wrap_hlsl, str(refusals)) + # Size is a count minus one in 64-byte units. These are exact fits and one unit short. + for node, word2, label in ((0x04, 0, "box16 at offset zero in a one-unit span"), + (0x05, 1, "box32 at offset zero in a two-unit span"), + (0x0c, 1, "box16 in the last unit of a two-unit span")): + pipe, hlsl, refusals = translate_program(node=node, word2=word2) + check("exact-fit %s translates" % label, pipe is not None and not refusals, str(refusals)) + for node, word2, label in ((0x05, 0, "box32 at offset zero in a one-unit span"), + (0x0c, 0, "box16 in the last unit of a one-unit span")): + pipe, hlsl, refusals = translate_program(node=node, word2=word2) + check("too-short %s refuses" % label, + len(refusals) == 1 and "outside descriptor size" in refusals[0], str(refusals)) + pipe, hlsl, refusals = translate_program(node=0x04, word2=0x03ffffff) + check("largest decoded extent translates", pipe is not None and not refusals, str(refusals)) + pipe, hlsl, refusals = translate_program(node=0x04, word2=0x04000000) + check("extent above 4 GiB refuses", len(refusals) == 1 and "above 4 GiB" in refusals[0], str(refusals)) + # Portable checks ensure the actual emitted helpers and every negative # mutation are present even when a GPU dispatch is unavailable. + pipe, hlsl, refusals = translate_program(node=0x04) helpers = "\n".join(G.BVH_HELPERS) - check("translated shader embeds both dispatch-tested helpers", hlsl is not None and helpers in hlsl, "") + check("translated shader embeds both dispatch-tested helpers", pipe is not None and helpers in hlsl, "") for mutation in MUTATIONS: dispatch_hlsl(mutation) @@ -418,9 +435,9 @@ def controls(): ("descriptor type", dict(word3=0x60000000), "descriptor type 6 is not 8"), ("box growing", dict(word1=SORT_ENABLE | (2 << 23)), "box growing amount 2"), ("reserved word 1", dict(word1=SORT_ENABLE | 0x100), "reserved word 1"), - ("size zero", dict(word2=0), "does not cover the node"), + ("box32 size zero", dict(word2=0), "outside descriptor size"), ("node outside size", dict(node=0x25, word2=3), "outside descriptor size"), - ("box16 node outside size", dict(node=0x54, word2=10), "outside descriptor size"), + ("box16 node outside size", dict(node=0x54, word2=9), "outside descriptor size"), ("absolute base", dict(word0=0, word1=0), "absolute node base"), ("size high bits", dict(word3=RESOURCE_TYPE | 0x100), "size above 4 GiB"), ] @@ -544,13 +561,81 @@ def dispatch_hlsl(mutation=None): return "\n".join(lines) + "\n" +BOUNDARY_BOX32_OFFSET = 128 +BOUNDARY_RESULT_OFFSET = 256 +BOUNDARY_BUFFER_SIZE = 320 + + +def boundary_hlsl(): + helpers = "\n".join(G.BVH_HELPERS).replace("ByteAddressBuffer", "RWByteAddressBuffer") + lines = [helpers, "RWByteAddressBuffer data : register(u0);", "[numthreads(1, 1, 1)]", "void main() {"] + for i, (child, lo, hi) in enumerate(HALF_NODES[0]): + lines.append(" data.Store(%du, 0x%08xu);" % (4 * i, child)) + packed = struct.unpack("<3I", struct.pack("<6e", *lo, *hi)) + for j, word in enumerate(packed): + lines.append(" data.Store(%du, 0x%08xu);" % (16 + 12 * i + 4 * j, word)) + for i, (child, lo, hi) in enumerate(NODES[0]): + base = BOUNDARY_BOX32_OFFSET + lines.append(" data.Store(%du, 0x%08xu);" % (base + 4 * i, child)) + for j in range(3): + lines.append(" data.Store(%du, %s);" % (base + 16 + 24 * i + 4 * j, fbits(lo[j]))) + lines.append(" data.Store(%du, %s);" % (base + 16 + 24 * i + 12 + 4 * j, fbits(hi[j]))) + for j in range(4): + lines.append(" data.Store(%du, 0u);" % (base + 112 + 4 * j)) + lines.append(" DeviceMemoryBarrierWithGroupSync();") + box16_ray = HALF_RAYS[0] + box32_ray = RAYS[0] + cases = ( + (0, "x2w_bvh_intersect_box16", 0x04, 0, box16_ray[2:5], box16_ray[-1]), + (1, "x2w_bvh_intersect_box16", 0x0c, 0, box16_ray[2:5], (INVALID,) * 4), + (2, "x2w_bvh_intersect_box32", 0x15, 3, box32_ray[2:5], box32_ray[-1]), + (3, "x2w_bvh_intersect_box32", 0x15, 2, box32_ray[2:5], (INVALID,) * 4), + ) + expected = [] + for case, helper, pointer, word2, ray, result in cases: + extent, origin, direction = ray + inv = tuple(1.0 / c for c in direction) + lines.append( + " uint4 b%d = %s(data, 0x%08xu, 0x1000u, 0x80000000u, 0x%08xu, 0x80000000u, " + "%s, float3(%s, %s, %s), float3(%s, %s, %s));" % ( + case, helper, pointer, word2, ffloat(extent), ffloat(origin[0]), ffloat(origin[1]), + ffloat(origin[2]), ffloat(inv[0]), ffloat(inv[1]), ffloat(inv[2]))) + for word in range(4): + lines.append(" data.Store(%du, b%d.%s);" % (BOUNDARY_RESULT_OFFSET + 16 * case + 4 * word, case, "xyzw"[word])) + expected.append(result) + lines.append("}") + return "\n".join(lines) + "\n", expected + + +def run_boundary_dispatch(dxc, runner, adapter, directory): + source = directory / "bvh_boundary.hlsl" + cso = directory / "bvh_boundary.cso" + output = directory / "bvh_boundary.bin" + hlsl, expected = boundary_hlsl() + source.write_text(hlsl, encoding="ascii") + compiled = subprocess.run([dxc, "-Gis", "-T", "cs_6_0", "-E", "main", "-Fo", str(cso), str(source)], + capture_output=True, text=True) + if compiled.returncode or compiled.stderr: + raise AssertionError(compiled.stderr or "dxc exited with %d" % compiled.returncode) + result = subprocess.run([runner, adapter, "--raw-uav-dump", str(cso), "1", str(BOUNDARY_BUFFER_SIZE), str(output)], + capture_output=True, text=True) + print(result.stdout, end="") + if result.returncode == 77: + return 77, None, expected + if result.returncode or result.stderr: + raise AssertionError(result.stderr or "offscreen_check exited with %d" % result.returncode) + data = output.read_bytes() + assert len(data) == BOUNDARY_BUFFER_SIZE, (len(data), BOUNDARY_BUFFER_SIZE) + return 0, struct.unpack("<%dI" % (len(data) // 4), data), expected + + def run_dispatch(dxc, runner, adapter, directory, mutation=None): name = "bvh_dispatch_" + mutation if mutation else "bvh_dispatch" source = directory / (name + ".hlsl") cso = directory / (name + ".cso") output = directory / (name + ".bin") source.write_text(dispatch_hlsl(mutation), encoding="ascii") - compiled = subprocess.run([dxc, "-T", "cs_6_0", "-E", "main", "-Fo", str(cso), str(source)], + compiled = subprocess.run([dxc, "-Gis", "-T", "cs_6_0", "-E", "main", "-Fo", str(cso), str(source)], capture_output=True, text=True) if compiled.returncode or compiled.stderr: raise AssertionError(compiled.stderr or "dxc exited with %d" % compiled.returncode) @@ -597,6 +682,15 @@ def check_dispatch(dxc, runner, adapter): changed = tuple(mutant[start:start + 4]) check("dispatch %s control changes %s" % (mutation, witness), changed != cases[case]["expected"], "got %s" % ["%08x" % w for w in changed]) + status, boundary_words, boundary_expected = run_boundary_dispatch(dxc, runner, adapter, directory) + if status == 77: + print("dispatch boundary: skip (adapter unavailable)") + return 77 + for case, wanted in enumerate(boundary_expected): + start = BOUNDARY_RESULT_OFFSET // 4 + 4 * case + got = tuple(boundary_words[start:start + 4]) + check("decoded descriptor extent case %d" % case, got == wanted, + "got %s expected %s" % (["%08x" % w for w in got], ["%08x" % w for w in wanted])) if failures: print("FAILED: %s" % ", ".join(failures)) return 1 diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index a4dc8dc125..543c28952e 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -8111,9 +8111,10 @@ def op_image_bvh_intersect_ray(self, ops, mods): if base == 0: raise Unsupported('%s absolute node base is not lowered' % name) if vals[2] is not None: - if vals[2] < 1 or vals[2] >= 0x04000000: - raise Unsupported('%s descriptor size %d does not cover the node' % (name, vals[2])) - if (node_offset >> 6) + (node_bytes >> 6) > vals[2]: + if vals[2] >= 0x04000000: + raise Unsupported('%s descriptor size %d is above 4 GiB' % (name, vals[2])) + # Size is a count minus one in 64-byte units, so size=0 is a one-unit span. + if (node_offset >> 6) + (node_bytes >> 6) - 1 > vals[2]: raise Unsupported('%s node base %#x is outside descriptor size %d' % (name, node_offset, vals[2])) if base + node_offset + node_bytes > 1 << 48: raise Unsupported('%s node address wraps the 48-bit address space' % name) @@ -11094,7 +11095,7 @@ def read(fmt, data, offset): # slice does not bind, so it is refused here as a miss rather than read at address zero. 'bool x2w_bvh_descriptor_ok(uint word0, uint word1, uint word2, uint word3) {', ' return (word1 & 0x7fffff00u) == 0u &&', - ' word3 == 0x80000000u && word2 >= 1u && word2 < 0x04000000u &&', + ' word3 == 0x80000000u && word2 < 0x04000000u &&', ' (word0 != 0u || (word1 & 0x000000ffu) != 0u);', '}', # One FP32 box from a radv_bvh_box32_node (Mesa 25.1.0 bvh/bvh.h, MIT): children[4] at @@ -11188,7 +11189,7 @@ def read(fmt, data, offset): ' uint4 miss = uint4(X2W_BVH_MISS, X2W_BVH_MISS, X2W_BVH_MISS, X2W_BVH_MISS);', ' if ((node & 7u) != 4u || !x2w_bvh_descriptor_ok(word0, word1, word2, word3)) return miss;', ' uint offset = (node & 0xfffffff8u) << 3u;', - ' if ((offset >> 6u) + 1u > word2) return miss;', + ' if ((offset >> 6u) > word2) return miss;', ' inv_dir = clamp(inv_dir, -3.402823466e+38, 3.402823466e+38);', ' bool h0, h1, h2, h3;', ' float d0 = x2w_bvh_box16_slot(nodes, offset, 0u, extent, origin, inv_dir, h0);', From 070b12de185a426e2ec045b077c0c4a8954139e9 Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Fri, 27 Nov 2026 16:08:26 +0000 Subject: [PATCH 10/11] startup: use the decoded BVH extent for triangle nodes Size is a count minus one in 64-byte units: size 0 covers a triangle at offset zero, while a triangle in the next unit needs size 1. Cover exact fits, a too-short neighbor, the 4 GiB upper bound and the HLSL boundary dispatch on WARP and hardware. --- .../startup-gfx2hlsl-bvh-triangle.md | 6 +- tests/startup_gfx2hlsl_bvh_triangle_check.py | 76 ++++++++++++++++++- tools/startup/gfx2hlsl.py | 4 +- 3 files changed, 80 insertions(+), 6 deletions(-) diff --git a/docs/experiments/startup-gfx2hlsl-bvh-triangle.md b/docs/experiments/startup-gfx2hlsl-bvh-triangle.md index c5b8691f6e..5eeb202be9 100644 --- a/docs/experiments/startup-gfx2hlsl-bvh-triangle.md +++ b/docs/experiments/startup-gfx2hlsl-bvh-triangle.md @@ -34,13 +34,15 @@ The accepted slice uses: - compute stage only; - `image_bvh_intersect_ray v[4], v[11], s[4]` with the packed address form; - a constant inline T# built by four SGPR constants, type 8, nonzero encoded base, box growing zero, - size at least one 64-byte unit and below 4 GiB; + size field (a count minus one in 64-byte units) whose decoded extent covers the node; `size=0` is + a one-unit span, and the field stays below 4 GiB; - a constant node pointer whose low three bits are 0..3 and whose address is inside the descriptor size and the 48-bit absolute address space; - either value of the sort bit; it is ignored for triangles. The manifest still names the allocation with `srv bvh base 0x size 0x`, using the -decoded byte address for `base`. The host binding of that line remains outside this change. +decoded byte address for `base`. The host binds `(size + 1) * 64` bytes. That binding remains +outside this change. ## Refused by name diff --git a/tests/startup_gfx2hlsl_bvh_triangle_check.py b/tests/startup_gfx2hlsl_bvh_triangle_check.py index a2c749f9f4..f2748c502b 100644 --- a/tests/startup_gfx2hlsl_bvh_triangle_check.py +++ b/tests/startup_gfx2hlsl_bvh_triangle_check.py @@ -87,12 +87,24 @@ def controls(): check("translated triangle shader embeds the dispatch-tested helpers", hlsl is not None and helpers in hlsl, "") + # Size is a count minus one in 64-byte units. A triangle uses one unit. + for node, word2, label in ((0x00, 0, "triangle at offset zero in a one-unit span"), + (0x08, 1, "triangle in the last unit of a two-unit span")): + pipe, hlsl, refusals = translate_triangle(node=node, word2=word2) + check("exact-fit %s translates" % label, pipe is not None and not refusals, str(refusals)) + pipe, hlsl, refusals = translate_triangle(0x08, word2=0) + check("too-short triangle in the last unit of a one-unit span refuses", + len(refusals) == 1 and "outside descriptor size" in refusals[0], str(refusals)) + pipe, hlsl, refusals = translate_triangle(0x00, word2=0x03ffffff) + check("largest decoded extent translates", pipe is not None and not refusals, str(refusals)) + pipe, hlsl, refusals = translate_triangle(0x00, word2=0x04000000) + check("extent above 4 GiB refuses", len(refusals) == 1 and "above 4 GiB" in refusals[0], str(refusals)) + cases = [ ("triangle return mode 0", dict(node=0x00, word3=RESOURCE_TYPE), "does not match node kind 0"), ("box return mode 1", dict(node=0x05, word3=RESOURCE_TYPE | TRIANGLE_MODE), "does not match node kind 5"), ("unknown node kind", dict(node=0x06), "node kind 6"), - ("size zero", dict(node=0x00, word2=0), "does not cover the node"), - ("node outside size", dict(node=0x20, word2=4), "outside descriptor size"), + ("node outside size", dict(node=0x20, word2=3), "outside descriptor size"), ("absolute base", dict(node=0x00, word0=0, word1=0), "absolute node base"), ("loaded descriptor", dict(node=0x00, loaded_descriptor=True), "loaded at run time"), ("descriptor type", dict(node=0x00, word3=0x60000000), "descriptor type 6 is not 8"), @@ -230,6 +242,57 @@ def dispatch_hlsl(mutation=None): return "\n".join(lines) + "\n" +TRIANGLE_BOUNDARY_RESULT_OFFSET = 64 +TRIANGLE_BOUNDARY_BUFFER_SIZE = 96 + + +def boundary_hlsl(): + witness = TRIANGLES[0] + helpers = "\n".join(G.BVH_HELPERS).replace("ByteAddressBuffer", "RWByteAddressBuffer") + lines = [helpers, "RWByteAddressBuffer data : register(u0);", "[numthreads(1, 1, 1)]", "void main() {"] + for i in range(16): + lines.append(" data.Store(%du, 0x%08xu);" % (4 * i, struct.unpack_from(" 0, str(changed)) + status, boundary_words, boundary_expected = run_boundary_dispatch(dxc, runner, adapter, directory) + if status == 77: + print("dispatch boundary: skip (adapter unavailable)") + return 77 + for case, wanted in enumerate(boundary_expected): + start = TRIANGLE_BOUNDARY_RESULT_OFFSET // 4 + 4 * case + got = tuple(boundary_words[start:start + 4]) + check("triangle decoded extent case %d" % case, got == wanted, + "got %s expected %s" % (["%08x" % w for w in got], ["%08x" % w for w in wanted])) if failures: print("FAILED: %s" % ", ".join(failures)) return 1 diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 66645699af..c59f66dd0f 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -11138,7 +11138,7 @@ def read(fmt, data, offset): # return mode is zero and is checked separately by each box helper. 'bool x2w_bvh_triangle_descriptor_ok(uint word0, uint word1, uint word2, uint word3) {', ' return (word1 & 0x7fffff00u) == 0u && (word3 & 0x0fffffffu) == 0x01000000u &&', - ' (word3 >> 28u) == 8u && word2 >= 1u && word2 < 0x04000000u &&', + ' (word3 >> 28u) == 8u && word2 < 0x04000000u &&', ' (word0 != 0u || (word1 & 0x000000ffu) != 0u);', '}', 'uint4 x2w_bvh_intersect_triangle(ByteAddressBuffer nodes, uint node, uint word0, uint word1,', @@ -11148,7 +11148,7 @@ def read(fmt, data, offset): ' uint kind = node & 7u;', ' if (kind > 3u || !x2w_bvh_triangle_descriptor_ok(word0, word1, word2, word3)) return miss;', ' uint offset = (node & 0xfffffff8u) << 3u;', - ' if ((offset >> 6u) + 1u > word2) return miss;', + ' if ((offset >> 6u) > word2) return miss;', ' uint id = nodes.Load(offset + 60u);', ' uint id_byte = (id >> (8u * kind)) & 0xffu;', ' uint i = id_byte & 3u;', From 263604fc6cbf49d24004db9b40792654cfde65a3 Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Fri, 27 Nov 2026 19:14:48 +0000 Subject: [PATCH 11/11] startup: cover BVH triangle operands and box return mode - assert the origin, direction and inverse-direction operands of the translated call - ignore the triangle return mode bit for box nodes in the translator guard and helper - add the triangle check to the Linux CI fragment - correct the BVH experiment notes and link both notes from experiments.md --- docs/experiments.md | 3 +++ .../experiments/startup-gfx2hlsl-bvh-box32.md | 5 ++-- .../startup-gfx2hlsl-bvh-triangle.md | 14 ++++++---- .../startup_gfx2hlsl_bvh_triangle.txt | 1 + tests/startup_gfx2hlsl_bvh_check.py | 27 +++++++++++++++++-- tests/startup_gfx2hlsl_bvh_triangle_check.py | 13 ++++++++- tools/startup/gfx2hlsl.py | 16 +++++++---- 7 files changed, 64 insertions(+), 15 deletions(-) create mode 100644 tests/checks/python-linux/startup_gfx2hlsl_bvh_triangle.txt diff --git a/docs/experiments.md b/docs/experiments.md index f25d09ff7f..4833e82240 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -4800,6 +4800,9 @@ Native readback remains pending, including the raw miss and disabled-slot words. The probe leaves translator behavior and form coverage unchanged. The node model and its witness set are described in [bvh-node-model.md](experiments/bvh-node-model.md). +The translator slices that consume the model are the +[FP32 and binary16 box nodes](experiments/startup-gfx2hlsl-bvh-box32.md) and the +[triangle nodes](experiments/startup-gfx2hlsl-bvh-triangle.md). ### gfx1013 2D explicit-LOD image gathers diff --git a/docs/experiments/startup-gfx2hlsl-bvh-box32.md b/docs/experiments/startup-gfx2hlsl-bvh-box32.md index 21acc67961..967256e65d 100644 --- a/docs/experiments/startup-gfx2hlsl-bvh-box32.md +++ b/docs/experiments/startup-gfx2hlsl-bvh-box32.md @@ -29,7 +29,8 @@ in `min.x`. for binary16, two for FP32; `size=0` is a one-unit span) and below 4 GiB; - a constant node pointer whose low three bits are 4 (64-byte aligned) or 5 (128-byte aligned) and inside the same 4 GiB relative address window; the entire node must fit within the 48-bit absolute address space; -- either value of the sort bit. +- either value of the sort bit, and either value of the triangle return mode bit (bit 120); + it selects the triangle result layout and does not change a box result. The manifest names the node allocation with `srv bvh base 0x size 0x`, using the decoded byte address for `base` and the unchanged descriptor size field for `size`. All four original descriptor @@ -40,7 +41,7 @@ of this change. ## Refused by name -Triangle nodes (kinds 0..3), every other node kind, `image_bvh64_intersect_ray`, A16, +Every node kind other than 4 and 5, `image_bvh64_intersect_ray`, A16, non-sequential addresses, a pixel or vertex stage, a node pointer that is not a straight-line constant, a T# loaded at run time, a type other than 8, nonzero box growing, an absolute (zero) base, a size that does not cover the node, size bits above 4 GiB, a node address that wraps the 48-bit address space, diff --git a/docs/experiments/startup-gfx2hlsl-bvh-triangle.md b/docs/experiments/startup-gfx2hlsl-bvh-triangle.md index 5eeb202be9..73e87d9eec 100644 --- a/docs/experiments/startup-gfx2hlsl-bvh-triangle.md +++ b/docs/experiments/startup-gfx2hlsl-bvh-triangle.md @@ -26,8 +26,10 @@ barycentric numerators `u`, `v` and `w`, the determinant `u + (v + w)` and ## Return and descriptor Triangle return mode 1 (bit 120 of the BVH T#, bit 24 of descriptor DWORD 3) returns the four words -`{t, determinant, v, w}` as float bit patterns. A miss is `{+inf, 1.0, 0, 0}`. Return mode 0 and -every other reserved word-3 bit are refused by name before any HLSL is emitted. +`{t, determinant, v, w}` as float bit patterns. A miss is `{+inf, 1.0, 0, 0}`. For triangle nodes, +return mode 0 and every other reserved word-3 bit are refused by name before any HLSL is emitted. +Box nodes (kinds 4 and 5) ignore bit 24 because one T# can cover both node types; every other +word-3 bit is still refused for them. The accepted slice uses: @@ -60,9 +62,11 @@ python3 -B tests/startup_gfx2hlsl_bvh_triangle_check.py dispatch > 3) | 4, word0=0x1000, word1=0, word2=0x40, extent=extent, origin=origin, direction=direction, expected=expected)) + # A T# can cover both box and triangle nodes; box kinds ignore the triangle return mode + # bit. These cases fail if either the translator or the emitted box helper rejects it. + name, offset, extent, origin, direction, expected = RAYS[0] + cases.append(dict(name="box32_return_mode_ignored", helper="x2w_bvh_intersect_box32", + pointer=(offset >> 3) | 5, word0=0x1000, word1=SORT_ENABLE, word2=0x0b, + word3=RESOURCE_TYPE | 0x01000000, extent=extent, origin=origin, + direction=direction, expected=expected)) + name, offset, extent, origin, direction, expected = HALF_RAYS[0] + cases.append(dict(name="box16_return_mode_ignored", helper="x2w_bvh_intersect_box16", + pointer=(offset >> 3) | 4, word0=0x1000, word1=SORT_ENABLE, word2=0x40, + word3=RESOURCE_TYPE | 0x01000000, extent=extent, origin=origin, + direction=direction, expected=expected)) return cases -BUFFER_SIZE = RESULT_OFFSET + 16 * (len(RAYS) + len(UNSORTED_RAYS) + len(HALF_RAYS) + len(HALF_UNSORTED_RAYS)) +BUFFER_SIZE = RESULT_OFFSET + 16 * len(dispatch_cases()) def translate_program(*, node=0x05, sort_boxes=True, word0=0x1000, word1=None, word2=0x0b, @@ -348,6 +360,16 @@ def controls(): check("sort-disabled box16 call uses a zero sort word", "0x00001000u, 0x00000000u, 0x0000000bu, 0x80000000u" in call, call) + # One T# can cover both node types, so a box node ignores the triangle return mode bit. + for node, helper in ((0x05, "x2w_bvh_intersect_box32"), (0x04, "x2w_bvh_intersect_box16")): + pipe, hlsl, refusals = translate_program(node=node, word3=RESOURCE_TYPE | 0x01000000) + check("box kind %d with triangle return mode bit translates" % (node & 7), + pipe is not None and not refusals, str(refusals)) + if pipe is not None: + call = next((line for line in hlsl.splitlines() if helper + "(r0" in line), "") + check("box kind %d call preserves the ignored return mode bit" % (node & 7), + "0x00001000u, 0x80000000u, 0x0000000bu, 0x81000000u" in call, call) + # Independently decode the 40-bit unit field; test the same raw DWORDs in # the emitted call and the decoded byte-address binding in the manifest. for units, high, base in ((0x1000, 0, 0x100000), (0x1008, 0, 0x100800), @@ -549,9 +571,10 @@ def dispatch_hlsl(mutation=None): for case, item in enumerate(dispatch_cases()): inv = tuple(1.0 / c for c in item["direction"]) lines.append( - " uint4 r%d = %s(data, 0x%08xu, 0x%08xu, 0x%08xu, 0x%08xu, 0x80000000u, " + " uint4 r%d = %s(data, 0x%08xu, 0x%08xu, 0x%08xu, 0x%08xu, 0x%08xu, " "%s, float3(%s, %s, %s), float3(%s, %s, %s));" % ( case, item["helper"], item["pointer"], item["word0"], item["word1"], item["word2"], + item.get("word3", 0x80000000), ffloat(item["extent"]), ffloat(item["origin"][0]), ffloat(item["origin"][1]), ffloat(item["origin"][2]), ffloat(inv[0]), ffloat(inv[1]), ffloat(inv[2]))) for word in range(4): diff --git a/tests/startup_gfx2hlsl_bvh_triangle_check.py b/tests/startup_gfx2hlsl_bvh_triangle_check.py index f2748c502b..792e61fcb5 100644 --- a/tests/startup_gfx2hlsl_bvh_triangle_check.py +++ b/tests/startup_gfx2hlsl_bvh_triangle_check.py @@ -75,6 +75,9 @@ def controls(): check("triangle kind %d call carries the node and four results" % kind, "0x0000000%du" % kind in call_line and all("v%d = bt" % reg in hlsl for reg in range(32, 36)), call_line) + check("triangle kind %d call passes origin, direction and inverse from v18..v26" % kind, + "float3(F(v18), F(v19), F(v20)), float3(F(v21), F(v22), F(v23)), " + "float3(F(v24), F(v25), F(v26))" in call_line, call_line) pipe, hlsl, refusals = translate_triangle(0x00, sort_boxes=False) check("sort-disabled triangle translates", pipe is not None and not refusals, str(refusals)) @@ -83,6 +86,14 @@ def controls(): check("sort-disabled triangle call keeps the zero sort word", "0x00001000u, 0x00000000u, 0x0000000bu, 0x81000000u" in call, call) + # One T# can cover both node types, so a box node ignores the triangle return mode bit. + pipe, hlsl, refusals = translate_triangle(node=0x05, word3=RESOURCE_TYPE | TRIANGLE_MODE) + check("box node with triangle return mode bit translates", pipe is not None and not refusals, str(refusals)) + if pipe is not None: + call = next((line for line in hlsl.splitlines() if "x2w_bvh_intersect_box32(r0" in line), "") + check("box call preserves the ignored return mode bit", + "0x00001000u, 0x80000000u, 0x0000000bu, 0x81000000u" in call, call) + helpers = "\n".join(G.BVH_HELPERS) check("translated triangle shader embeds the dispatch-tested helpers", hlsl is not None and helpers in hlsl, "") @@ -102,7 +113,7 @@ def controls(): cases = [ ("triangle return mode 0", dict(node=0x00, word3=RESOURCE_TYPE), "does not match node kind 0"), - ("box return mode 1", dict(node=0x05, word3=RESOURCE_TYPE | TRIANGLE_MODE), "does not match node kind 5"), + ("box reserved word 3 bit", dict(node=0x05, word3=RESOURCE_TYPE | 0x100), "does not match node kind 5"), ("unknown node kind", dict(node=0x06), "node kind 6"), ("node outside size", dict(node=0x20, word2=3), "outside descriptor size"), ("absolute base", dict(node=0x00, word0=0, word1=0), "absolute node base"), diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index c59f66dd0f..33923008bc 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -8108,8 +8108,13 @@ def op_image_bvh_intersect_ray(self, ops, mods): if vals[3] is not None: if (vals[3] >> 28) & 0xf != 8: raise Unsupported('%s descriptor type %d is not 8' % (name, (vals[3] >> 28) & 0xf)) - expected_mode = 0x01000000 if triangle else 0 - if (vals[3] & 0x0fffffff) != expected_mode: + # The triangle return mode bit only selects the triangle result layout. One T# can + # cover both node types, so a box node ignores it; every other reserved bit is refused. + if triangle: + mode_ok = (vals[3] & 0x0fffffff) == 0x01000000 + else: + mode_ok = (vals[3] & 0x0effffff) == 0 + if not mode_ok: raise Unsupported('%s descriptor word 3 %#x does not match node kind %d' % (name, vals[3], kind)) base = key[0][1] if base == 0: @@ -11106,7 +11111,7 @@ def read(fmt, data, offset): # slice does not bind, so it is refused here as a miss rather than read at address zero. 'bool x2w_bvh_descriptor_ok(uint word0, uint word1, uint word2, uint word3) {', ' return (word1 & 0x7fffff00u) == 0u &&', - ' word3 == 0x80000000u && word2 < 0x04000000u &&', + ' (word3 & 0xfeffffffu) == 0x80000000u && word2 < 0x04000000u &&', ' (word0 != 0u || (word1 & 0x000000ffu) != 0u);', '}', # A triangle node is 64 bytes: five float3 vertices at 0..59 and one ID dword at 60. @@ -11134,8 +11139,9 @@ def read(fmt, data, offset): ' float rz = x2w_bvh_component(rel, kz);', ' return float3(rx - sx * rz, ry - sy * rz, sz * rz);', '}', - # Triangle return mode 1 (bit 120) is the only triangle mode this slice lowers. The box - # return mode is zero and is checked separately by each box helper. + # Triangle return mode 1 (bit 120) is the only triangle mode this slice lowers. A box + # node ignores bit 120 because one T# covers both node types; its helper checks every + # other word-3 bit. 'bool x2w_bvh_triangle_descriptor_ok(uint word0, uint word1, uint word2, uint word3) {', ' return (word1 & 0x7fffff00u) == 0u && (word3 & 0x0fffffffu) == 0x01000000u &&', ' (word3 >> 28u) == 8u && word2 < 0x04000000u &&',