diff --git a/docs/experiments/startup-gfx2hlsl-bvh-box32.md b/docs/experiments/startup-gfx2hlsl-bvh-box32.md new file mode 100644 index 0000000000..8e9521be92 --- /dev/null +++ b/docs/experiments/startup-gfx2hlsl-bvh-box32.md @@ -0,0 +1,63 @@ +# 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 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 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/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..35cecf48d9 --- /dev/null +++ b/tests/startup_gfx2hlsl_bvh_check.py @@ -0,0 +1,394 @@ +"""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)), + 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) +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)), +) +UNSORTED_RAYS = ( + ("unsorted_three_hits", 384, 19.0, ORIGIN, FORWARD, (0x25, 0x2d, 0x35, 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]) + 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] + 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))) + 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, "") + + 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, 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])) + 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", "608", 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])) + 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[136:140] + 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 6eeb8d1f40..6912c58f1a 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -2383,6 +2383,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() @@ -2787,6 +2788,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() @@ -3698,6 +3706,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 @@ -7811,6 +7820,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 texel to a 2D or 2D-array image, or to a 1D or 3D compute image. @@ -10601,9 +10719,102 @@ 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;', + # 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);', + ' 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 = () @@ -10643,6 +10854,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() @@ -10902,8 +11114,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);' % ({'tex1d': 'RWTexture1D', 'tex2d': 'RWTexture2D', 'tex2da': 'RWTexture2DArray', 'tex3d': 'RWTexture3D', 'raw': 'RWByteAddressBuffer'}[r['kind']], 'u' if r['kind'] == 'raw' else 'w', r['index'], r['index'])) for key, i in self.samplers.items(): @@ -11236,8 +11450,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), - '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)) @@ -11288,6 +11506,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.uses_lerp_u8 = False self.resources, self.uavs, self.samplers, self.uds = {}, {}, {}, [] @@ -11332,7 +11551,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]