From 5d325d30390e7864f1bd3da53306cbfe0a4cafd3 Mon Sep 17 00:00:00 2001 From: Chad Hyatt Date: Fri, 27 Nov 2026 04:16:17 -0600 Subject: [PATCH] shader: correct FP32 BVH descriptor byte units and child results Decode the 40-bit descriptor base in 256-byte units and preserve the full encoded words. Preserve unsorted result slots and use positive-infinity miss keys. Refuse unsupported 48-bit node wraps. Source-built model and translator checks passed; DXC/GPU execution not available on this host. AI-assisted backport patch from x2w-microlift --- .../experiments/startup-gfx2hlsl-bvh-box32.md | 66 +++--- tests/startup_gfx2hlsl_bvh_check.py | 202 ++++++++++++------ tools/startup/gfx2hlsl.py | 56 ++--- 3 files changed, 202 insertions(+), 122 deletions(-) diff --git a/docs/experiments/startup-gfx2hlsl-bvh-box32.md b/docs/experiments/startup-gfx2hlsl-bvh-box32.md index 8e9521be92..f1430af9fe 100644 --- a/docs/experiments/startup-gfx2hlsl-bvh-box32.md +++ b/docs/experiments/startup-gfx2hlsl-bvh-box32.md @@ -3,61 +3,73 @@ `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. +hits by entry distance only when bit 31 of descriptor DWORD 1 is set. With sorting disabled each +result remains in its original child slot, including holes. Sorted misses use a positive-infinity +key so that a valid hit at `FLT_MAX` still precedes them. 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. +The BVH T# fields are RDNA 2 ISA Table 49: base 39:0 (encoded in 256-byte units), 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, +- 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, 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 5, 128-byte aligned and inside the 4 GiB relative + address window; the entire node must fit within the 48-bit absolute address space; - 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`, using the decoded +byte address for `base` and the unchanged descriptor size field for `size`. All four original descriptor +DWORDs are passed to the helper. For example, base field `0x1000` means byte address `0x100000`, and +`0x1008` means `0x100800`; both are aligned by construction. The host must bind a raw +`ByteAddressBuffer` at the decoded 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. +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, +and reserved T# fields. 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 +```sh +python3 -B tests/gfx1030_bvh_box/check.py --model-only +python3 -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. +The translator check compares synthetic nodes and rays against the independently existing binary32 +reference in `tests/gfx1030_bvh_box/bvh_model.py`. It checks the sort-bit negative control (word 0 +changes from `0x1d` to `0x25`), the three-hit sort-disabled result with its second slot still invalid +(`0x25, 0xffffffff, 0x2d, 0x35`), and the finite `FLT_MAX` hit with infinite extent. It separately checks +the translation, full descriptor literals, and manifest for `0x1000`, `0x1008`, and a base using +the high byte of DWORD 1. The top-of-address-space witness checks a valid node ending at the +48-bit boundary and refuses a node whose start wraps to zero in the independent model, before +binding a resource or emitting a helper. The check also covers the named refusals and the actual +emitted helper's mutation sites. It compiles the translated compute shader with DXC when available; +without DXC it prints `dxc compile: skip` and does not count that compilation 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. +The dispatch mode compiles the same emitted helper with a `RWByteAddressBuffer` in place of the +bound `ByteAddressBuffer`, writes synthetic nodes and rays, and compares the four result DWORDs +for every case. Its negative controls remove miss filling, compact the unsorted slots, substitute +`FLT_MAX` for the infinite miss key, reintroduce the erroneous low-byte alignment check, and ignore +the high byte of the encoded base in the zero-base check. Each mutant must change its designated +witness result. This is a reproduction procedure, not a new GPU execution result. -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. +This is a translator slice. It does not execute the native gfx1030 probe, does not establish the +host binding of the node allocation 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 35cecf48d9..531caecccc 100644 --- a/tests/startup_gfx2hlsl_bvh_check.py +++ b/tests/startup_gfx2hlsl_bvh_check.py @@ -4,9 +4,8 @@ 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). +by name before any HLSL is emitted. The independent CPU box reference is +tests/gfx1030_bvh_box/bvh_model.py; the Windows dispatch exercises the actual emitted helper. """ import math import os @@ -24,6 +23,7 @@ sys.path.insert(0, str(HERE)) import gfx2hlsl as G # noqa: E402 import startup_gfx2hlsl_compute_check as C # noqa: E402 +from gfx1030_bvh_box import bvh_model as B # noqa: E402 INVALID = 0xffffffff SORT_ENABLE = 1 << 31 @@ -40,6 +40,9 @@ def box(child, depth, x=-8): 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)), + # A finite hit at FLT_MAX must sort ahead of misses (key +infinity). + 512: (box(INVALID, 1), (0x4d, (FLT_MAX,) * 3, (FLT_MAX,) * 3), + box(0x55, 2, x=32), box(INVALID, 3)), } ORIGIN = (0.5, -0.5, -1.0) FORWARD = (0.25, -0.125, 0.5) @@ -49,10 +52,23 @@ def box(child, depth, x=-8): ("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)), + ("finite_max", 512, math.inf, (0.0, 0.0, 0.0), (1.0, 1.0, 1.0), (0x4d, INVALID, INVALID, INVALID)), + ("encoded_base_low_bits", 0, 19.0, ORIGIN, FORWARD, (0x1d, 0x25, INVALID, INVALID)), + ("encoded_base_high_byte", 256, 19.0, ORIGIN, FORWARD, (0x0d, 0x35, 0x3d, 0x45)), ) UNSORTED_RAYS = ( - ("unsorted_three_hits", 384, 19.0, ORIGIN, FORWARD, (0x25, 0x2d, 0x35, INVALID)), + ("unsorted_three_hits", 384, 19.0, ORIGIN, FORWARD, (0x25, INVALID, 0x2d, 0x35)), + ("unsorted_mixed", 0, 19.0, ORIGIN, FORWARD, (0x25, 0x1d, INVALID, INVALID)), + ("unsorted_finite_max", 512, math.inf, (0.0, 0.0, 0.0), (1.0, 1.0, 1.0), + (INVALID, 0x4d, INVALID, INVALID)), ) +DESCRIPTOR_BASES = { + "encoded_base_low_bits": (0x1008, 0), + "encoded_base_high_byte": (0, 0x81), +} +RESULT_OFFSET = max(NODES) + 128 +RESULT_WORD = RESULT_OFFSET // 4 +BUFFER_SIZE = RESULT_OFFSET + 16 * (len(RAYS) + len(UNSORTED_RAYS)) failures = [] @@ -65,22 +81,21 @@ def check(label, ok, 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 node_bytes(): + data = bytearray(RESULT_OFFSET) + for offset, nodes in NODES.items(): + struct.pack_into("<4I", data, offset, *(child for child, _, _ in nodes)) + for i, (_, lo, hi) in enumerate(nodes): + struct.pack_into("<6f", data, offset + 16 + 24 * i, *lo, *hi) + return data + + +def reference(offset, extent, origin, direction, sort_boxes): + """Use the independent model on bytes relative to the bound allocation.""" + return tuple(B.intersect( + node_bytes(), B.descriptor(sort=sort_boxes), (offset >> 3) | 5, + extent=extent, origin=origin, direction=direction, + inverse=tuple(1.0 / c for c in direction))) def model(nodes, extent, origin, direction, sort_boxes): @@ -89,7 +104,7 @@ def model(nodes, extent, origin, direction, sort_boxes): items = [] for child, lo, hi in nodes: if child == INVALID: - items.append([INVALID, FLT_MAX]) + items.append([INVALID, math.inf]) 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)] @@ -99,17 +114,16 @@ def model(nodes, extent, origin, direction, sort_boxes): if hit: items.append([child, tmin if sort_boxes else 0.0]) else: - items.append([INVALID, FLT_MAX]) + items.append([INVALID, math.inf]) if not sort_boxes: - ordered = [child for child, _key in items if child != INVALID] - return tuple(ordered) + (INVALID,) * (4 - len(ordered)) + return tuple(child for child, _key in items) 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, +def translate_program(*, node=0x05, sort_boxes=True, word0=0x1000, 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.""" @@ -154,11 +168,11 @@ def add(name, asm, length=8): def controls(): bad = None for name, offset, extent, origin, direction, expected in RAYS: - actual = reference(NODES[offset], extent, origin, direction, True) + actual = reference(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)) + check("independent public box model matches sorted fixture expectations", bad is None, str(bad)) bad = None for name, offset, extent, origin, direction, expected in RAYS: @@ -166,25 +180,25 @@ def controls(): if actual != expected: bad = (name, actual, expected) break - check("emitted sort network matches the CPU reference", bad is None, str(bad)) + check("transcribed helper model matches independent 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) + unsorted = reference(0, 19.0, ORIGIN, FORWARD, False) + sorted_result = reference(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) + actual = reference(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, "") + reference(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)) @@ -197,14 +211,54 @@ def controls(): 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) + 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) + "0x00001000u, 0x80000000u, 0x0000000bu, 0x80000000u" in call_line + and "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, "") + call = next((line for line in hlsl.splitlines() if "x2w_bvh_intersect_box32(r0" in line), "") + check("sort-disabled call uses a zero sort word", + "0x00001000u, 0x00000000u, 0x0000000bu, 0x80000000u" 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), + (0, 0x81, 0x810000000000)): + words = (units, high | SORT_ENABLE, 0x0b, RESOURCE_TYPE) + check("public model decodes base %#x" % base, + B.node_address(words, 5) == (5, base), str(B.node_address(words, 5))) + pipe, hlsl, refusals = translate_program(node=0x25, word0=words[0], word1=words[1]) + check("encoded base %#x translates" % base, pipe is not None and not refusals, str(refusals)) + if pipe is not None: + manifest = pipe.manifest() + call = next((line for line in hlsl.splitlines() if "x2w_bvh_intersect_box32(r0" in line), "") + literal_words = ", ".join("0x%08xu" % word for word in words) + check("manifest uses byte base %#x" % base, "srv 0 bvh base %#x size 0xb" % base in manifest, manifest) + check("call preserves all four descriptor DWORDs at %#x" % base, literal_words in call, call) + + # The model wraps the absolute node address at 48 bits. The raw-bound + # helper cannot represent that wrap, so the translator must refuse it. + words = (0xffffffff, SORT_ENABLE | 0xff, 0x0b, RESOURCE_TYPE) + check("public model wraps the node address", B.node_address(words, 0x25) == (5, 0), + str(B.node_address(words, 0x25))) + pipe, boundary_hlsl, refusals = translate_program(node=0x15, word0=words[0], word1=words[1]) + check("node ending exactly at the 48-bit boundary translates", + pipe is not None and not refusals, str(refusals)) + pipe, wrap_hlsl, refusals = translate_program(node=0x25, word0=words[0], word1=words[1]) + check("refuses 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_box32" not in wrap_hlsl and "uint4 bt" not in wrap_hlsl, str(refusals)) + + # Portable checks ensure the actual emitted helper and every negative + # mutation are present even when a GPU dispatch is unavailable. + helpers = "\n".join(G.BVH_HELPERS) + check("translated shader embeds the dispatch-tested helper", hlsl is not None and helpers in hlsl, "") + for mutation in MUTATIONS: + dispatch_hlsl(mutation) # Every refusal must happen before a helper call or a result VGPR is emitted. cases = [ @@ -219,7 +273,7 @@ def controls(): ("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"), + ("reserved word 1", dict(word1=SORT_ENABLE | 0x100), "reserved word 1"), ("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"), @@ -289,11 +343,31 @@ def fbits(value): return "0x%08xu" % struct.unpack("> 3) | 5, sort_word, ffloat(extent), ffloat(origin[0]), ffloat(origin[1]), + case, (offset >> 3) | 5, base0, word1, 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);" % (RESULT_OFFSET + 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" +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(mutate), encoding="ascii") + source.write_text(dispatch_hlsl(mutation), 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)], + 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: @@ -336,11 +411,14 @@ def run_dispatch(dxc, runner, adapter, directory, mutate=False): 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 @@ -352,22 +430,22 @@ def check_dispatch(dxc, runner, adapter): 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]) + cases = RAYS + UNSORTED_RAYS + for case, (_name, _offset, _extent, _origin, _direction, expected) in enumerate(cases): + start = RESULT_WORD + 4 * case + got = tuple(words[start:start + 4]) 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]) + for mutation, (witness, _replacements) in MUTATIONS.items(): + status, mutant = run_dispatch(dxc, runner, adapter, directory, mutation=mutation) + if status == 77: + print("dispatch control: skip (adapter unavailable)") + return 77 + case = next(i for i, ray in enumerate(cases) if ray[0] == witness) + start = RESULT_WORD + 4 * case + changed = tuple(mutant[start:start + 4]) + check("dispatch %s control changes %s" % (mutation, witness), changed != cases[case][-1], + "got %s" % ["%08x" % w for w in changed]) if failures: print("FAILED: %s" % ", ".join(failures)) return 1 diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 06a13d774a..35f78f4479 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -7885,7 +7885,8 @@ def bvh_descriptor(self, tok): '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] + # The 40-bit base represents address bits 47:8, not a byte address. + base = (((values[1] & 0xff) << 32) | (values[0] & 0xffffffff)) << 8 return (('bvhbase', base, values[2]), None), words, values def op_image_bvh_intersect_ray(self, ops, mods): @@ -7897,9 +7898,10 @@ def op_image_bvh_intersect_ray(self, ops, mods): 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. + 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, 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': @@ -7934,8 +7936,6 @@ def op_image_bvh_intersect_ray(self, ops, mods): 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)) @@ -7946,25 +7946,24 @@ def op_image_bvh_intersect_ray(self, ops, mods): 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: + base = key[0][1] + 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 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])) + if base + node_offset + 128 > 1 << 48: + 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 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, + 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): @@ -10797,13 +10796,14 @@ def read(fmt, data, offset): 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, + # The 128-bit BVH T# (RDNA 2 ISA Table 49): base in 256-byte units at 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 &&', + ' return (word1 & 0x7fffff00u) == 0u &&', ' word3 == 0x80000000u && word2 >= 1u && word2 < 0x04000000u &&', ' (word0 != 0u || (word1 & 0x000000ffu) != 0u);', '}', @@ -10825,10 +10825,10 @@ def read(fmt, data, offset): # 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;', + ' return hit ? tmin : asfloat(0x7f800000u);', '}', - # 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. + # The five compare-exchange stages of Mesa radv_nir_rt_common.c: a strict comparison + # sorts misses (key +inf) to the end without swapping equal keys within each pair. '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; }', '}', @@ -10861,22 +10861,12 @@ def read(fmt, data, offset): ' 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;', + # With sorting disabled, each result remains in its original child slot. + ' if (!sort_boxes) return uint4(c0, c1, c2, c3);', + ' float k0 = h0 ? d0 : asfloat(0x7f800000u);', + ' float k1 = h1 ? d1 : asfloat(0x7f800000u);', + ' float k2 = h2 ? d2 : asfloat(0x7f800000u);', + ' float k3 = h3 ? d3 : asfloat(0x7f800000u);', ' x2w_bvh_sort_pair(c0, c1, k0, k1);', ' x2w_bvh_sort_pair(c2, c3, k2, k3);', ' x2w_bvh_sort_pair(c0, c2, k0, k2);',