diff --git a/docs/experiments/native-global-srv-heap-replay.md b/docs/experiments/native-global-srv-heap-replay.md index bc4787af0c..f267ca20ca 100644 --- a/docs/experiments/native-global-srv-heap-replay.md +++ b/docs/experiments/native-global-srv-heap-replay.md @@ -92,6 +92,16 @@ The check runs, in order: for selections 0 and 1 (output equals the slot's data), compiled by `compile_dxil --requests`, replayed with the same result, and replaying selection 0 against the slot 1 reference reports a mismatch. +Section 11 of the check (#3224) forms the heap descriptor address the way a waterfall loop over a lane-selected slot +does: `s_add_u32 s24, s2, s17`, `s_add_u32 s25, 0, src_scc`, `s_load_dwordx4 s[20:23], s[24:25], 0x0` instead of the +SGPR offset of the load. The compiler tracks SCC as the carry of that add and reads the pair as the same indexed heap +descriptor, under the same contract. Without `.views` it is refused with the heap text. The program is recorded, +compiled and replayed for selections 0 and 1 like PROGRAM, with the slot 1 mismatch control. The other operand order +with `s_addc_u32 s25, 0, 0` compiles. These stay refused: a constant offset (`unbound numeric SGPR s2`), `s_mov_b32 +s25, 0` or an `s_cmp` between the adds (`heap descriptor address high word is not the carry of its offset add`) and an +immediate offset on the load. `tests/native_heap_offset_add_check.py` compiles the same form from a slot 67 request with +both heap flags: it reaches the heap text like the SGPR-offset form, and the controls keep their refusals. + ## Result ``` @@ -122,6 +132,15 @@ ctest --preset dev --no-tests=error -R "^native_global_srv_heap_replay(_warp|_ha load (`buffer_load_format_*`) through the heap descriptor. After the change, the test passes with 84 assertions. The run against the earlier commit `7582c01d` fails at the `window_loop` shape (old text "heap byte window in a program with a backward branch"). The run stops there. +- Added heap address (#3224), dev build on `main` `8007a539` plus the change, NVIDIA GeForce RTX 4090 (driver + 32.0.16.1088), Windows 11 build 26300, Windows SDK 10.0.26100 DXC, D3D12 debug layer not enabled: + `native_global_srv_heap_replay_hardware` passed, 118 assertions. `native_heap_offset_add` passed, 5 of 5. `_warp` + skipped (77) as above. + - With the compiler sources of `8007a539` (before the change), the replay fails at the first section 11 assertion + (`unbound numeric SGPR s2`) and `native_heap_offset_add` fails 3 of 5 (`unbound numeric SGPR s5`). + - With the high-word check removed, both tests fail at the `mov_high` controls. + - `ctest --preset dev --no-tests=error -R "native_|startup_compute|compile_dxil" -j 8`: 415 tests, 404 passed and + 11 skipped (77, WARP). ## Limits diff --git a/src/gfx1013_compute_native.cpp b/src/gfx1013_compute_native.cpp index dafa8d5a44..1f394106b0 100644 --- a/src/gfx1013_compute_native.cpp +++ b/src/gfx1013_compute_native.cpp @@ -457,7 +457,8 @@ static std::optional carry_destination(const Inst &i) { } struct Symbol { enum class Type { unknown, constant, masked, table, descriptor, indexed_descriptor, root_address, primitive_mask, - stride, byte_stride, zero_stride_word, byte_count, clear_oob, byte_oob, lane_mask, uniform_mask, unbound } type{}; + stride, byte_stride, zero_stride_word, byte_count, clear_oob, byte_oob, lane_mask, uniform_mask, + heap_offset, heap_carry, unbound } type{}; Word value = 0, offset = 0; unsigned index_mask = 0, definition = 0; bool numeric() const { return type == Type::unknown || type == Type::constant || type == Type::masked || type == Type::uniform_mask; } @@ -469,6 +470,8 @@ struct State { // Encoded VGPR and guest lane. A join can lose the identity while // retaining the fact that some path omitted the runtime lane write. std::map, std::optional> lane_spills; + // SCC, tracked only as the carry of a heap offset add (see heap_offset_add). + Symbol scc{}; Symbol &operator[](unsigned n) { return scalar[n]; } const Symbol &operator[](unsigned n) const { return scalar[n]; } const Symbol &at(unsigned n) const { return scalar.at(n); } @@ -561,6 +564,30 @@ Symbol source(const Inst &i, unsigned code, const State &s) { return {Symbol::Type::constant, i.literal}; return {}; } +// The low word of a resource-heap descriptor address formed by adding a byte offset, as in a waterfall loop over a +// lane-selected slot: s_add_u32 lo, , , then the carry into the high word. Returns the +// operand index of the offset. A constant offset is not matched: the selected slot must come from GPU data. +static std::optional heap_offset_add(const Inst &i, const State &s) { + if (i.name != "s_add_u32" || i.dst > 105) return {}; + for (unsigned k = 0; k < 2; ++k) { + const auto heap = source(i, i.src[k], s), offset = source(i, i.src[1 - k], s); + if (heap.type == Symbol::Type::table && heap.value == compute_resource_heap && !heap.offset && + i.src[1 - k] <= 105 && offset.numeric() && offset.type != Symbol::Type::constant) + return 1 - k; + } + return {}; +} +// The high word of that address: s_add_u32 hi, 0, src_scc or s_addc_u32 hi, 0, 0. +static bool heap_offset_carry(const Inst &i) { + return i.dst <= 105 && ((i.name == "s_add_u32" && ((i.src[0] == 128 && i.src[1] == 253) || + (i.src[0] == 253 && i.src[1] == 128))) || + (i.name == "s_addc_u32" && i.src[0] == 128 && i.src[1] == 128)); +} +// s[base:base+1] holds the resource-heap base plus a byte offset with its own carry in the high word. +static bool heap_offset_address(const State &s, unsigned base) { + return base + 1 < s.size() && s[base].type == Symbol::Type::heap_offset && + s[base + 1].type == Symbol::Type::heap_carry && s[base + 1].definition == s[base].definition; +} // Derive the rewritten byte-address V# symbolically. Each field carries its // source table/slot identity. Numeric consumption still requires real bits. // heap_window: the direct path under HeapViewContract::raw_buffer also rewrites a @@ -599,6 +626,10 @@ State transfer(const Inst &i, State s, bool wave64, bool graphics, bool heap_win refuse(i.pc, "invalid SGPR"); s[n] = v; }; + const Symbol carry = s.scc; + if (i.enc == Encoding::Sop1 || i.enc == Encoding::Sop2 || i.enc == Encoding::Sopc || i.enc == Encoding::Sopk) + s.scc = {}; + const auto heap_add = direct && !graphics ? heap_offset_add(i, s) : std::nullopt; if (direct && !graphics) { if (i.name == "v_writelane_b32") { if (auto lane = guest_spill_lane(i, wave64)) { @@ -632,6 +663,13 @@ State transfer(const Inst &i, State s, bool wave64, bool graphics, bool heap_win (i.src[0] == 193 || i.src[0] == 128) && (i.src[1] == 193 || i.src[1] == 128)) { set(i.dst,{Symbol::Type::uniform_mask,i.pc,0}); set(i.dst+1,{Symbol::Type::uniform_mask,i.pc,1}); + } else if (heap_add) { + const auto offset = source(i, i.src[*heap_add], s); + set(i.dst, {Symbol::Type::heap_offset, compute_resource_heap, 0, + offset.type == Symbol::Type::masked ? offset.value : ~0u, i.pc}); + s.scc = {Symbol::Type::heap_carry, compute_resource_heap, 0, 0, i.pc}; + } else if (direct && !graphics && carry.type == Symbol::Type::heap_carry && heap_offset_carry(i)) { + set(i.dst, carry); } else if (auto field = byte_descriptor_field(i,s,heap_window)) { set(i.dst,*field); } else if (i.enc == Encoding::FixedSetup) { @@ -643,9 +681,12 @@ State transfer(const Inst &i, State s, bool wave64, bool graphics, bool heap_win const unsigned offset_reg = i.b >> 25; const Symbol index = offset_reg < smem_sgpr_limit(!graphics && !wave64) ? s[offset_reg] : Symbol{}; unsigned n = memory_count(i); + const bool heap_address = i.op == 2 && i.b >> 25 == 125 && heap_offset_address(s, i.src[0]); for (unsigned j = 0; j < n; ++j) { Symbol v{}; - if (i.op == 2 && i.b >> 25 != 125 && base.type == Symbol::Type::table) { + if (heap_address) { + v = {Symbol::Type::indexed_descriptor, compute_resource_heap, (i.b & 0xfffff) + 4 * j, base.index_mask, i.pc}; + } else if (i.op == 2 && i.b >> 25 != 125 && base.type == Symbol::Type::table) { v = {Symbol::Type::indexed_descriptor, base.value, (i.b & 0xfffff) + 4*j, index.type == Symbol::Type::masked || index.type == Symbol::Type::constant ? index.value : ~0u, i.pc}; } else if (i.op < 8 && base.type == Symbol::Type::table) @@ -845,6 +886,10 @@ Program parse(const string &code, unsigned entry, const State &initial, bool gra changed = true; } } + if (!(in.scc == after.scc) && !(in.scc == Symbol{})) { + in.scc = {}; + changed = true; + } for (auto &[key, value] : in.lane_spills) { const auto other = after.lane_spills.find(key); if (value && (other == after.lane_spills.end() || !(other->second == value))) { diff --git a/src/gfx1013_direct_compute.inl b/src/gfx1013_direct_compute.inl index 3cb5e7cce6..8fbcfee7a2 100644 --- a/src/gfx1013_direct_compute.inl +++ b/src/gfx1013_direct_compute.inl @@ -541,6 +541,23 @@ struct DirectCompute { const unsigned limit = smem_sgpr_limit(!graphics_input && !wave64); const auto &low = s.at(i.src[0]); const bool root = low.type == Symbol::Type::root_address; + if (low.type == Symbol::Type::heap_offset) { + // A resource-heap address formed by s_add_u32 (heap_offset_add): the same slot read as the SGPR-offset + // load below, with the byte offset in the low word. + if (!heap_offset_address(s, i.src[0])) + refuse(i.pc, "heap descriptor address high word is not the carry of its offset add"); + if (i.op != 2) + refuse(i.pc, "heap descriptor address must load one descriptor with s_load_dwordx4"); + refuse_heap_contract(i.pc); + if (so != 125) + refuse(i.pc, "heap descriptor address with a second offset register"); + if (i.b & 0xfffff) + refuse(i.pc, "heap descriptor load with an immediate offset addresses another slot than the captured selection"); + auto index = ir.binary("lshr", read(i.src[0]), "5"); + for (unsigned j = 0; j < 4; ++j) + write(i.dst + j, index); + return; + } if (!root && low.type == Symbol::Type::table && low.value == compute_resource_heap) { // Reads from the whole descriptor heap: only the indexed descriptor load of a captured raw buffer slot. if (i.op >= 8) @@ -2301,6 +2318,14 @@ struct DirectCompute { } void arithmetic(const Inst &i, const State &state, const string *permuted = nullptr, bool compute = false) { auto n = i.name; + if (compute) { + if (const auto offset = heap_offset_add(i, state)) { + // The heap base is slot 0 of ResourceDescriptorHeap: the low word keeps the byte offset, the carry is 0. + write(i.dst, operand32(i, i.src[*offset])); + write(128, "0"); + return; + } + } if (compute && (n == "v_dot4_i32_i8" || n == "v_dot4_u32_u8")) { // Integer dot products use both packed words as-is. Require the // canonical VOP3P OP_SEL/OP_SEL_HI and zero NEG_LO/NEG_HI. diff --git a/tests/cmake/native_heap_offset_add.cmake b/tests/cmake/native_heap_offset_add.cmake new file mode 100644 index 0000000000..f4ab8ffb76 --- /dev/null +++ b/tests/cmake/native_heap_offset_add.cmake @@ -0,0 +1,7 @@ +# A slot 67 resource-heap descriptor address formed by s_add_u32 with its carry (#3224). +if(TARGET compile_dxil AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_heap_offset_add COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_heap_offset_add_check.py" + "$" "${DXC_BIN_DIR}") + set_tests_properties(native_heap_offset_add PROPERTIES TIMEOUT 60) +endif() diff --git a/tests/native_global_srv_heap_replay_check.py b/tests/native_global_srv_heap_replay_check.py index ad16834a7f..733f1a44f1 100644 --- a/tests/native_global_srv_heap_replay_check.py +++ b/tests/native_global_srv_heap_replay_check.py @@ -6,7 +6,9 @@ ResourceDescriptorHeap[slot] and stores them to u0. Slots 0 and 1 are raw buffers with different data, slot 2 is a texture, slot 3 a typed buffer. The fixture's `record` mode captures the GPU selector and the slot view types into a req_.views file and refuses the incompatible slots before the dispatch; `compile_dxil` and the fixture's `replay` -mode consume the same file offline. Exit 77 when the fixture reports a capability skip. +mode consume the same file offline. Section 11 forms the heap descriptor address by adding the byte offset to the heap +base (s_add_u32, carry into the high word) instead of the SGPR offset of the load. Exit 77 when the fixture reports a +capability skip. """ import pathlib import shutil @@ -393,4 +395,65 @@ def raw_load_request(name, width=1, *, offen=False, soffset=18, imm=0, flags=0, (code, out, err), _, _, _, cso = raw_load_request(name, **addressing) require(code == 1 and diagnostic in err and not cso.exists(), f"{name}: refused with '{diagnostic}'") + # 11. The heap descriptor address formed by adding the byte offset to the heap base, as a waterfall loop over a + # lane-selected slot does, instead of the SGPR offset of the load (encodings checked with tools/disasm_rdna2.py): + # s_add_u32 s24, s2, s17 ; s_add_u32 s25, 0, src_scc ; s_load_dwordx4 s[20:23], s[24:25], 0x0 + # It reads the same slot: recorded, compiled offline and replayed like PROGRAM. + ADD_LO, ADD_HI, ADDED_LOAD = 0x80181102, 0x8019fd80, [0xf408050c, 0xfa000000] + + def added(lo=ADD_LO, between=(), hi=ADD_HI, load_words=ADDED_LOAD): + return words_list[:heap_load] + [lo, *between, hi, *load_words] + words_list[heap_load + 2:] + + ADDED = added() + directory, added_stem = shader_request("added_nometa", ADDED) + out_dir = base / "added_nometa_out" + code, out, err = run([compile_dxil, sdk, cache, "gfx1013-container-cs", "--requests", directory, out_dir]) + require(code == 1 and HEAP_REFUSAL in err and not any(out_dir.glob("*.cso")), + "compile_dxil added address without .views refuses the heap read with the slot/type text") + added_outputs = {} + for n in (0, 1): + directory, added_stem = shader_request(f"added{n}", ADDED) + code, out, err = run([fixture, "record", sdk, cache, directory / (added_stem + ".cdx"), adapter, n, "ok"]) + require(code == 0 and "output matches slot %d data" % n in out, + f"record added select {n}: u0 equals the slot {n} data read through the added address") + out_dir = base / f"added{n}_out" + code, out, err = run([compile_dxil, sdk, cache, "gfx1013-container-cs", "--requests", directory, out_dir]) + cso = out_dir / (added_stem[len("req_"):] + ".cs.cso") + require(code == 0 and "requests=1 compiled=1 refused=0" in out and cso.exists(), + f"compile_dxil added select {n}: compiled and published a .cso") + added_outputs[n] = (directory, cso) + code, out, err = run([fixture, "replay", sdk, cache, directory / (added_stem + ".cdx"), cso, + directory / (added_stem + ".views"), adapter, "ok", n]) + require(code == 0 and "output matches slot %d data" % n in out, f"replay added select {n}: output equals slot {n} data") + directory, cso = added_outputs[0] + code, out, err = run([fixture, "replay", sdk, cache, directory / (added_stem + ".cdx"), cso, + directory / (added_stem + ".views"), adapter, "ok", 1]) + require(code == 1 and "mismatch word 0" in out, "replay added select 0 compared with slot 1 data reports a mismatch") + + high_word = "heap descriptor address high word is not the carry of its offset add" + added_shapes = { + # s_add_u32 s24, s17, s2 and s_addc_u32 s25, 0, 0: the other operand order and carry form + "added_swapped_addc": (added(lo=0x80180211, hi=0x82198080), None), + # s_add_u32 s24, s2, 0x40: a constant offset names a slot that is not the captured GPU selection + "added_constant": (added(lo=0x8018ff02, between=(0x00000040,)), "unbound numeric SGPR s2"), + # s_mov_b32 s25, 0: the high word drops the carry of the offset add + "added_mov_high": (added(hi=0xbe990380), high_word), + # s_cmp_lg_u32 s16, s16 between the adds: SCC is no longer the carry + "added_scc_clobbered": (added(between=(0xbf071010,)), high_word), + # s_load_dwordx4 s[20:23], s[24:25], 0x20 + "added_immediate": (added(load_words=[0xf408050c, 0xfa000020]), + "heap descriptor load with an immediate offset addresses another slot than the captured selection"), + } + for name, (program, expected) in added_shapes.items(): + directory, shape_stem = shader_request("shape_" + name, program) + (directory / (shape_stem + ".views")).write_text(good, newline="\n") + out_dir = base / ("shape_" + name + "_out") + code, out, err = run([compile_dxil, sdk, cache, "gfx1013-container-cs", "--requests", directory, out_dir]) + if expected is None: + require(code == 0 and "requests=1 compiled=1 refused=0" in out and any(out_dir.glob("*.cso")), + f"compile_dxil shape '{name}': compiled") + else: + require(code == 1 and expected in err and not any(out_dir.glob("*.cso")), + f"compile_dxil shape '{name}': refused with '{expected}'") + print("native_global_srv_heap_replay: all checks passed") diff --git a/tests/native_heap_offset_add_check.py b/tests/native_heap_offset_add_check.py new file mode 100644 index 0000000000..728b619414 --- /dev/null +++ b/tests/native_heap_offset_add_check.py @@ -0,0 +1,79 @@ +"""A slot 67 request that forms its resource-heap descriptor address by adding a byte offset (issue #3224). + +usage: native_heap_offset_add_check.py COMPILE_DXIL SDK + +A waterfall loop over a lane-selected heap slot adds the slot's byte offset to the heap base and carries into the high +word instead of passing the offset as the SGPR offset of the load: + + s_add_u32 s10, s5, s8 ; s_add_u32 s11, 0, src_scc ; s_load_dwordx4 s[12:15], s[10:11], 0x0 + +The requests are written from source with the entry layout of the start-up shaders that do this: user SGPRs s4 (a +descriptor table), s5 (the resource heap) and s6 (the sampler heap) under both directly indexed heap flags, wave32. Such a +load is the same GPU-selected heap read as the SGPR-offset form, so both now stop at the heap view contract, which a +.c67 request has no metadata for. Before this change the add was refused as a numeric use of the heap table. The +controls keep their refusals: a high word that is not the carry of the add, SCC clobbered between the adds, and a +constant offset. The GPU readback of the same address form is in native_global_srv_heap_replay_check.py (section 11). +Encodings were checked with tools/disasm_rdna2.py; the test needs no LLVM. +""" +import pathlib +import struct +import subprocess +import sys +import tempfile + +from native_compute_clear_check import write_request + +ROOT = "RootFlags(CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED | SAMPLER_HEAP_DIRECTLY_INDEXED), DescriptorTable(SRV(t0), UAV(u0))" +HEAP_CONTRACT = "direct resource-heap load requires the selected GPU slot and its view type" +HIGH_WORD = "heap descriptor address high word is not the carry of its offset add" +SELECT = [0x7E100500, 0x8F088508] # v_readfirstlane_b32 s8, v0 ; s_lshl_b32 s8, s8, 5 +ADD_LO, ADD_HI = 0x800A0805, 0x800BFD80 # s_add_u32 s10, s5, s8 ; s_add_u32 s11, 0, src_scc +LOAD = [0xF4080305, 0xFA000000] # s_load_dwordx4 s[12:15], s[10:11], 0x0 +END = [0xBF8CC07F, 0xBF810000] # s_waitcnt lgkmcnt(0) ; s_endpgm +PROGRAMS = { + "added": (SELECT + [ADD_LO, ADD_HI] + LOAD + END, HEAP_CONTRACT), + # s_mov_b32 s10, s5 ; s_mov_b32 s11, 0 ; s_load_dwordx4 s[12:15], s[10:11], s8: the SGPR-offset form + "sgpr_offset": (SELECT + [0xBE8A0305, 0xBE8B0380, 0xF4080305, 0x10000000] + END, HEAP_CONTRACT), + # s_mov_b32 s11, 0 instead of the carry + "mov_high": (SELECT + [ADD_LO, 0xBE8B0380] + LOAD + END, HIGH_WORD), + # s_cmp_lg_u32 s8, s8 between the adds + "scc_clobbered": (SELECT + [ADD_LO, 0xBF070808, ADD_HI] + LOAD + END, HIGH_WORD), + # s_add_u32 s10, s5, 0x40: a constant offset is not a GPU selection; the heap table is used as a number + "constant": (SELECT + [0x800AFF05, 0x40, ADD_HI] + LOAD + END, "unbound numeric SGPR s5"), +} + + +def main(compile_dxil, sdk): + failures = 0 + with tempfile.TemporaryDirectory(prefix="x2w_heap_offset_add_") as scratch: + base = pathlib.Path(scratch) + source = base / "root.hlsl" + source.write_text(f'#define RS "{ROOT}"') + binary = base / "root.bin" + subprocess.run([pathlib.Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "RS", "-Fo", binary, source], + check=True, capture_output=True) + root = binary.read_bytes() + # Group 32x1x1, wave32 (bit 20 of dword 4), 7 user SGPRs. + sa = struct.pack("<7I", 0, 0, 0, 32 | (1 << 16), 1 | (1 << 20), 0, 7 << 1) + for name, (program, expected) in PROGRAMS.items(): + folder = base / name + folder.mkdir() + marker = write_request(folder, program, root, sa) + output = marker.with_suffix(".cso") + result = subprocess.run([compile_dxil, sdk, base / "cache", "gfx1013-direct-cs@0", marker, output], + capture_output=True, text=True, timeout=60) + ok = result.returncode != 0 and expected in result.stderr and not output.exists() + print(("ok: " if ok else "FAIL: ") + f"{name}: refused with '{expected}' and no .cso") + if not ok: + print(result.stdout + result.stderr) + failures += 1 + if failures: + return 1 + print("native_heap_offset_add: all checks passed") + return 0 + + +if __name__ == "__main__": + if len(sys.argv) != 3: + raise SystemExit(__doc__) + sys.exit(main(*sys.argv[1:]))