diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 58c2f00a5e..e700a078b5 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -90,6 +90,7 @@ jobs: (["tests/startup_flat_param_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_bit_alu_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_mad_check.py", "binary", "llvm-mc-15"], {}), + (["tests/startup_gfx2hlsl_compute_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_swap_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_shift64_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_vopc_sdwa_check.py", "binary", "llvm-mc-15"], {}), @@ -225,6 +226,7 @@ jobs: tests/startup_flat_param_check.py \ tests/startup_gfx2hlsl_bit_alu_check.py \ tests/startup_gfx2hlsl_mad_check.py \ + tests/startup_gfx2hlsl_compute_check.py \ tests/startup_gfx2hlsl_swap_check.py \ tests/startup_gfx2hlsl_shift64_check.py \ tests/startup_gfx2hlsl_vopc_sdwa_check.py \ diff --git a/AGENTS.md b/AGENTS.md index 8951f7f7d9..5a53720b50 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -149,6 +149,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_image_load_mip_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_operand_count_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_mad_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_compute_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_swap_check.py ./out/pe-env/bin/python -B tests/startup_image_2d_array_check.py ./out/pe-env/bin/python -B tests/startup_image_sample_a16_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 1d301b2b72..2a1c6a582f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2695,6 +2695,22 @@ if(EXISTS "${INTAKE_PYTHON}") set_tests_properties(startup_gfx2hlsl_mad_dispatch_${adapter} startup_gfx2hlsl_mad_preserve_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) endforeach() + # gfx2hlsl compute stage: entry registers, numthreads and the offen buffer store, dispatched on a plain device (#1412). + add_test(NAME startup_gfx2hlsl_compute_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_compute_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_compute_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_compute_check.py" dispatch "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_gfx2hlsl_compute_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + foreach(control IN ITEMS swapped-axes dropped-store b-offset c-unpredicated) + add_test(NAME startup_gfx2hlsl_compute_${control}_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_compute_check.py" control ${control} "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_gfx2hlsl_compute_${control}_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77 + PASS_REGULAR_EXPRESSION "control ${control}: rejected at word=[0-9]+ ") + endforeach() + endforeach() # gfx2hlsl 64-bit VOP3 shifts: binary round-trip, overlap, guards and WARP/hardware draws (Refs #1723). add_test(NAME startup_gfx2hlsl_shift64_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_shift64_check.py") diff --git a/docs/experiments.md b/docs/experiments.md index f8a077fc56..5c6884bb3d 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -12161,6 +12161,64 @@ ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_mad_' -V python -B tests/startup_gfx2hlsl_mad_check.py binary llvm-mc-15 ``` +## Compute stage in the startup translator + +`gfx2hlsl.ComputePipeline` translates one gfx1013 compute program with the root and resource model of +the graphics stages. The caller passes `COMPUTE_PGM_RSRC2` and the thread group size, which are pipeline +register state. Each group-ID axis enabled by `TGID_X/Y/Z_EN` gets the next SGPR after the user +SGPRs, with no gap for an omitted axis (`SV_GroupID`). v0-v2 hold `SV_GroupThreadID` up to +`TIDIG_COMP_CNT`. This is how `compute_store_aot` decodes `COMPUTE_PGM_RSRC2` (#1608). +`TG_SIZE_EN` stays refused. + +Root parameters are placed from s4, which is an inference, like the graphics stages' s8. #1608 defines no +root placement. The only in-repo evidence is the local compute-record scan above, whose table bindings +used s4 or s5. A numeric read of a user SGPR that the root signature does not place, including s0-s3, +is refused because its value is unknown. + +Inside a block that `s_cbranch_execz` skips, a scalar instruction is refused. The wave runs that block +when any lane is active, while the one-lane model would skip it for an inactive lane. An image sample +with implicit LOD is also refused, because a compute lane has no derivatives. + +The output is a `cs` HLSL main with `[numthreads]` and a version 2 manifest. The manifest has +`stage cs` and `group` lines, plus one `uav table ` line for each store +target. The only store lowered is `buffer_store_dword[x2|x3|x4]` in the `offen` form: a per-lane byte VGPR, plus +the scalar offset and the immediate, through a descriptor at a fixed root-table offset. It writes a +`RWByteAddressBuffer`. All four descriptor words must still be the words the `s_load` returned. Refused: +- the `off` and `idxen` forms, and the cache-policy flags; +- an immediate offset that is not a multiple of 4; +- a descriptor word that was moved, overwritten or modified; +- a descriptor that is also loaded. + +As in #2059, the run-time part of the address is rounded down to a multiple of 4. That rounding, and the +handling of out-of-range stores, are assumptions, not measurements. +The runtime has no slot-67 path yet, so no translated compute program runs in the stand-in. + +`startup_gfx2hlsl_compute_check.py` translates three source-built programs: +- Case A enables all three group-ID axes and v0-v2, with group size 2x3x4 and 3x2x2 groups, and stores one word. +- Case B enables X and Z only, so Z is s8, with group size 5x2x1 and 4x1x3 groups. It stores two words at an + immediate offset. +- Case C enables Y only, with group size 8x1x1 and 1x5x1 groups. It stores four words from every lane, then + three words under an exec mask set from a compare. + +Each thread reads a read buffer at its own index and stores to its own destination. DXC compiles the HLSL +for `cs_6_0`, and a plain D3D12 device dispatches it. The root signature is the test runner's (a root SRV, +a root UAV and the root constants), so the manifest's table lines and the descriptor fetch are not exercised +on the GPU. All 320 words are compared, including the sentinels. Four controls must each mismatch: swapping +the X and Y group IDs, dropping the store, dropping case B's immediate offset, and dropping case C's exec +predicate. The pure-Python controls refuse every reviewed input that was previously accepted: a modified +descriptor word, an execz-skipped scalar write, an implicit-LOD sample and a misaligned immediate offset. + +Translating every cached graphics request before and after the descriptor-tracking change gave identical +output and refusals. The local check covered 925 requests, 123 of which translate. + +On Windows 11 (26300), all 320 words matched in every case on WARP (10.0.26100.10068) and on an RTX 5090 +(32.0.16.2135), with the debug layer on. + +```powershell +ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_compute_' -V +python -B tests/startup_gfx2hlsl_compute_check.py binary llvm-mc-15 +``` + ## Startup translator: refusal census The startup shader translator normally stops a pipeline at its first refusal. Fixing that refusal can expose gaps that were previously hidden, as documented in the [issue #1723 census](https://github.com/R0Y00/Xbox2Windows/issues/1723). diff --git a/tests/startup_gfx2hlsl_compute_check.py b/tests/startup_gfx2hlsl_compute_check.py new file mode 100644 index 0000000000..70ab2a1acd --- /dev/null +++ b/tests/startup_gfx2hlsl_compute_check.py @@ -0,0 +1,404 @@ +"""Compute stage of tools/startup/gfx2hlsl.py: entry registers, numthreads and the offen buffer store (#1412). + + (no arguments) translation controls, pure Python + binary reassemble the fixture sources and compare them with the words below + dispatch + translate, compile with DXC cs_6_0, dispatch and compare every word + control + the same dispatch with a mutated translation, which must mismatch + +The fixtures are source-built gfx1013 compute programs. The root signature puts two root constants (key, stride) +in s4-s5 and a descriptor table in s6; the table holds a read buffer at byte 0 and a writable buffer at byte 16. +COMPUTE_PGM_RSRC2 and the thread group size are pipeline register state, given here as the runtime would give them. +Each thread names its group and local IDs only by the registers that state gives them, computes its own index, +reads the read buffer at that index and stores to its own destination: + +- case A enables all three group-ID axes and v0-v2, with group size 2x3x4 and 3x2x2 groups, and stores one word; +- case B enables X and Z only (Y omitted, so Z is s8), v0-v1, group size 5x2x1 and 4x1x3 groups, and stores two + words at an immediate offset of 8 bytes; +- case C enables Y only (s7), v0 only, group size 8x1x1 and 1x5x1 groups, stores four words with every lane, then + three words at offset 16 under an exec mask set from a compare (lanes with tid.x < 6), and restores exec. + +The dispatch runs on a plain D3D12 device (the stand-in has no slot-67 path yet). The root signature is the runner's: +root SRV t0 (read buffer), root UAV u0 (writable buffer) and 16 root constants at b0, which match the translation's +r0, u0 and entry cbuffer. The manifest's table lines and the descriptor fetch are therefore not exercised on the GPU. +All 320 words are compared, so a word outside the written records must keep the sentinel. The controls swap the X +and Y group IDs at entry, drop the store, drop case B's immediate offset, or drop case C's exec predicate; each must +change the readback. +""" +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +import gfx2hlsl as G # noqa: E402 + +SENTINEL = 0xc5c5c5c5 +WORDS = 320 +MASK = 0xffffffff +KEY, STRIDE = 0x01234567, 0x9e3779b9 +TGID_X, TGID_Y, TGID_Z, TG_SIZE_EN = 1 << 7, 1 << 8, 1 << 9, 1 << 10 +USER7 = 7 << 1 # s0-s3, two root constants, one table + + +def tidig(components): + return (components - 1) << 11 + + +SOURCE_A = """\ +s_mov_b32 s10, s6 +s_mov_b32 s11, 0 +s_load_dwordx8 s[12:19], s[10:11], 0x0 +s_waitcnt lgkmcnt(0) +v_mad_u32_u24 v3, v1, 2, v0 +v_mad_u32_u24 v3, v2, 6, v3 +s_mul_i32 s20, s8, 3 +s_add_u32 s20, s20, s7 +s_mul_i32 s21, s9, 6 +s_add_u32 s20, s20, s21 +s_mul_i32 s20, s20, 24 +v_add_nc_u32 v3, s20, v3 +v_lshlrev_b32 v4, 2, v3 +buffer_load_dword v5, v4, s[12:15], 0 offen +v_mul_lo_u32 v6, v3, s5 +v_add_nc_u32 v6, s4, v6 +s_waitcnt vmcnt(0) +v_mul_lo_u32 v5, v5, 33 +v_xor_b32 v5, v5, v6 +buffer_store_dword v5, v4, s[16:19], 0 offen +s_endpgm +""" +WORDS_A = bytes.fromhex( + '06038abe' '80038bbe' '05030cf4000000fa' '7fc08cbf' '030043d501050104' '030043d5020d0d04' '08831493' '14071480' + '09861593' '14151480' '14981493' '1406064a' '82060834' '001030e004050380' '060069d5030b0000' '040c0c4a' + '703f8cbf' '050069d505430100' '050d0a3a' '001070e004050480' '000081bf') + +SOURCE_B = """\ +s_mov_b32 s10, s6 +s_mov_b32 s11, 0 +s_load_dwordx8 s[12:19], s[10:11], 0x0 +s_waitcnt lgkmcnt(0) +v_mad_u32_u24 v3, v1, 5, v0 +s_lshl_b32 s20, s8, 2 +s_add_u32 s20, s20, s7 +s_mul_i32 s20, s20, 10 +v_add_nc_u32 v3, s20, v3 +v_lshlrev_b32 v4, 3, v3 +v_lshlrev_b32 v7, 2, v3 +buffer_load_dword v5, v7, s[12:15], 0 offen +v_mul_lo_u32 v6, v3, s5 +v_add_nc_u32 v6, s4, v6 +s_waitcnt vmcnt(0) +v_xor_b32 v5, v5, v6 +v_xor_b32 v6, 0x5a000000, v3 +buffer_store_dwordx2 v[5:6], v4, s[16:19], 0 offen offset:8 +s_endpgm +""" +WORDS_B = bytes.fromhex( + '06038abe' '80038bbe' '05030cf4000000fa' '7fc08cbf' '030043d5010b0104' '0882148f' '14071480' '148a1493' + '1406064a' '83060834' '82060e34' '001030e007050380' '060069d5030b0000' '040c0c4a' '703f8cbf' '050d0a3a' + 'ff060c3a0000005a' '081074e004050480' '000081bf') + +SOURCE_C = """\ +s_mov_b32 s10, s6 +s_mov_b32 s11, 0 +s_load_dwordx8 s[12:19], s[10:11], 0x0 +s_waitcnt lgkmcnt(0) +s_lshl_b32 s20, s7, 3 +v_add_nc_u32 v3, s20, v0 +v_lshlrev_b32 v7, 2, v3 +buffer_load_dword v8, v7, s[12:15], 0 offen +v_mul_u32_u24 v4, 28, v3 +v_mov_b32 v9, v3 +v_mul_lo_u32 v10, v3, s5 +v_add_nc_u32 v10, s4, v10 +s_waitcnt vmcnt(0) +v_xor_b32 v11, v8, v10 +buffer_store_dwordx4 v[8:11], v4, s[16:19], 0 offen +s_mov_b32 s21, exec_lo +v_cmp_gt_u32 vcc_lo, 6, v0 +s_mov_b32 exec_lo, vcc_lo +buffer_store_dwordx3 v[8:10], v4, s[16:19], 0 offen offset:16 +s_mov_b32 exec_lo, s21 +s_endpgm +""" +WORDS_C = bytes.fromhex( + '06038abe' '80038bbe' '05030cf4000000fa' '7fc08cbf' '0783148f' '1400064a' '82060e34' '001030e007080380' + '9c060816' '0303127e' '0a0069d5030b0000' '0414144a' '703f8cbf' '0815163a' '001078e004080480' '7e0395be' + '8600887d' '6a03febe' '10107ce004080480' '1503febe' '000081bf') + +CASES = { + # name: (source, words, rsrc2, group size, group counts) + 'A': (SOURCE_A, WORDS_A, USER7 | TGID_X | TGID_Y | TGID_Z | tidig(3), (2, 3, 4), (3, 2, 2)), + 'B': (SOURCE_B, WORDS_B, USER7 | TGID_X | TGID_Z | tidig(2), (5, 2, 1), (4, 1, 3)), + 'C': (SOURCE_C, WORDS_C, USER7 | TGID_Y | tidig(1), (8, 1, 1), (1, 5, 1)), +} + +# Single instructions the controls splice into case A before its store, recorded from llvm-mc 15. +STORE_A = WORDS_A.index(bytes.fromhex('001070e004050480')) +SPLICE = { + 's_mov_b32 s18, 0': '800392be', + 's_or_b32 s17, s17, 0x40000': '11ff118800000400', + 's_and_b32 s18, s18, 0xffff': '12ff1287ffff0000', + 's_mov_b32 s18, 4': '840392be', + 'v_cmp_gt_u32 vcc_lo, 1, v0': '8100887d', + 's_and_saveexec_b32 s0, vcc_lo': '6a3c80be', + 's_cbranch_execz 1': '010088bf', + 's_add_u32 s20, s7, 1': '07811480', + 's_or_b32 exec_lo, exec_lo, s0': '7e007e88', + 'v_mov_b32 v5, s20': '14020a7e', + 's_mov_b32 s21, exec_lo': '7e0395be', + 's_mov_b32 exec_lo, vcc_lo': '6a03febe', + 's_mov_b32 exec_lo, s21': '1503febe', + 's_mov_b64 s[20:21], 0': '800494be', + 's_mov_b64 s[22:23], 0': '800496be', + 's_load_dwordx8 s[24:31], s[10:11], 0x40': '05060cf4400000fa', + 'image_sample v[12:15], v[0:1], s[24:31], s[20:23] dmask:0xf dim:SQ_RSRC_IMG_2D': '080f80f0000ca600', + 'image_sample_lz v[12:15], v[0:1], s[24:31], s[20:23] dmask:0xf dim:SQ_RSRC_IMG_2D': '080f9cf0000ca600', + 'buffer_store_dword v5, v4, s[16:19], 0 offen': '001070e004050480', + 'buffer_store_dword v5, v4, s[16:19], 0 offen offset:6': '061070e004050480', + 'buffer_store_dword v5, v4, s[16:19], 0 offen offset:4092': 'fc1f70e004050480', +} + + +def splice(*lines, at=STORE_A): + return WORDS_A[:at] + b''.join(bytes.fromhex(SPLICE[line]) for line in lines) + WORDS_A[at:] + + +def root_blob(): + """RTS0: param 0 = two root constants (b0), param 1 = a descriptor table with no ranges.""" + params_at, constants_at = 24, 24 + 2 * 12 + table_at = constants_at + 12 + rts0 = (struct.pack('<6I', 2, 2, params_at, 0, table_at + 8, 0) + + struct.pack('<3I', 1, 0, constants_at) + struct.pack('<3I', 0, 0, table_at) + + struct.pack('<3I', 0, 0, 2) + struct.pack('<2I', 0, table_at + 8)) + part = b'RTS0' + struct.pack(' (case, text the translation must contain once, replacement) +CONTROLS = { + 'swapped-axes': ('A', ' s7 = gid.x;\n s8 = gid.y;\n', ' s7 = gid.y;\n s8 = gid.x;\n'), + 'dropped-store': ('A', ' u0.Store(a, v5);\n', ''), + 'b-offset': ('B', ' a = (v4 + 8) & 0xfffffffcu;\n', ' a = (v4 + 0) & 0xfffffffcu;\n'), + 'c-unpredicated': ('C', 'if (exec & 1) u0.Store3(', 'u0.Store3('), +} + + +def mutate(hlsl, control): + _, old, new = CONTROLS[control] + assert hlsl.count(old) == 1, (control, hlsl) + return hlsl.replace(old, new) + + +def run_case(name, dxc, runner, adapter, directory, control=None): + hlsl = translate(name).hlsl_cs() + if control: + hlsl = mutate(hlsl, control) + src, cso, case = (directory / ('%s.%s' % (name, ext)) for ext in ('hlsl', 'cso', 'case')) + src.write_text(hlsl, encoding='ascii') + subprocess.run([dxc, '-T', 'cs_6_0', '-E', 'main', '-Fo', str(cso), str(src)], check=True) + groups = CASES[name][4] + constants = [KEY, STRIDE] + [0] * 14 + case.write_bytes(struct.pack(' user: + raise Unsupported('root signature needs s4-s%d, COMPUTE_PGM_RSRC2 gives %d user SGPRs' % (root_end - 1, user)) + for n in list(range(4)) + list(range(root_end, user)): + self.sym[n] = ('unknown user sgpr',) + self.entry = [] + for axis, n in sorted(groups.items()): + self.used_s.add(n) + self.entry.append('s%d = gid.%s;' % (n, 'xyz'[axis])) + for i in range(threads): + self.used_v.add(i) + self.entry.append('v%d = tid.%s;' % (i, 'xyz'[i])) + # ---- operand helpers --------------------------------------------------------------------- def S(self, n): """Runtime expression of scalar register n (uint).""" @@ -731,9 +764,13 @@ def const_words(self, tok): # ---- instruction translation ------------------------------------------------------------- def translate(self): targets = set() + skipped = [] # compute: (branch, target) of each s_cbranch_execz for off, n, name, asm in self.ins: if name.startswith('s_cbranch') or name == 's_branch': - targets.add(int(parse(asm)[1][0].split('_')[1], 16)) + target = int(parse(asm)[1][0].split('_')[1], 16) + targets.add(target) + if name == 's_cbranch_execz' and self.kind == 'cs': + skipped.append((off, target)) self.blocks = [] # (offset, [lines], terminator) self.uniform_v = set() self.varying_s = set() @@ -755,6 +792,12 @@ def translate(self): # branch-free program is past it too (dead code). self.past_entry = bool(self.blocks) or 0 in targets try: + if any(branch < off < target or target <= off < branch for branch, target in skipped) and ( + name.startswith(('s_', 'v_readlane', 'v_readfirstlane', 'v_writelane')) + and not name.startswith(SKIPPABLE_SCALAR)): + # The wave runs this block when any lane is active, so its scalar state changes for every + # lane; the one-lane model would skip it for an inactive lane. + raise Unsupported('%s inside a block s_cbranch_execz skips per lane' % name) term = self.one(name, asm) except Unsupported as reason: if refusals is None: @@ -1192,7 +1235,10 @@ def src_sym(t): self.varying_s.add(d + 1) elif own and own[0] in ('desc', 'ptr', 'ptrhi') and any(s == own for s in syms): if own[0] == 'desc': - self.pipe.modified.add((own[1], own[2])) + self.pipe.modified.add(desc_key(own)) + # The word keeps its descriptor identity for loads; an exact-word check (unmodified_descriptor) + # sees the mark. + self.sym[d] = own[:4] + ('modified',) else: self.sym[d] = ('descnum',) return None @@ -1651,6 +1697,64 @@ def op_buffer_load_dwordx3(self, ops, mods): def op_buffer_load_dwordx4(self, ops, mods): self.op_buffer_load_dword(ops, mods, 4) + def op_buffer_store_dword(self, ops, mods, count=1): + # Compute-stage store in the offen form: per-lane byte VGPR plus the scalar offset and the 12-bit immediate, + # through a descriptor read from a fixed root-table slot, to a RWByteAddressBuffer (manifest `uav` line). + # Like the loads, this assumes a raw descriptor (no swizzle or stride). Out-of-range stores: assumes a future + # runtime sizes the view to the descriptor's range so both sides drop them; nothing binds or checks that yet. + if self.kind != 'cs': + raise Unsupported('buffer_store_dword' + ('x%d' % count if count > 1 else '')) # the unknown-op refusal + offset = 0 + for m in mods: + if m.startswith('offset:') and re.fullmatch(r'0x[0-9a-f]+|\d+', m[7:]): + offset += int(m[7:], 0) + elif m != 'offen': + raise Unsupported('buffer store modifier %s' % m) + if len(ops) != 4 or 'offen' not in mods: + raise Unsupported('buffer store without the offen address form') + src, vaddr = reg_range(ops[0]), reg_range(ops[1]) + if not src or src[0] != 'v' or src[2] - src[1] != count - 1 or src[2] > 255: + raise Unsupported('buffer store data %s' % ops[0]) + if not vaddr or vaddr[0] != 'v' or vaddr[1] != vaddr[2] or vaddr[1] > 255: + raise Unsupported('buffer store vaddr %s for offen' % ops[1]) + # All four words must still be the loaded words of one descriptor at a fixed table offset: a moved, + # overwritten or modified word (stride, num_records) would change what the store does. + rsrc = reg_range(ops[2]) + first = self.sym.get(rsrc[1]) if rsrc and rsrc[0] == 's' and rsrc[2] - rsrc[1] == 3 else None + if not first or first[0] != 'desc' or first[1][0] != 'table' or first[2] is None or first[3] % 4: + raise Unsupported('buffer store through %s holding %s' % (ops[2], first)) + if (any(self.sym.get(rsrc[1] + k) != first[:3] + (first[3] + k,) for k in range(4)) + or desc_key(first) in self.pipe.modified): + raise Unsupported('buffer store through a modified descriptor') + key = desc_key(first) + terms = [self.u(ops[1])] + if re.fullmatch(r'0x[0-9a-f]+|\d+', ops[3]): + offset += int(ops[3], 0) + else: + sreg = reg_range(ops[3]) + if not sreg or sreg[0] != 's' or sreg[1] != sreg[2] or sreg[1] > 105: + raise Unsupported('buffer soffset %s' % ops[3]) + terms.append(self.S(sreg[1])) + if offset % 4: + raise Unsupported('buffer store at unaligned immediate offset %d' % offset) + uav = self.pipe.uav(key) + words = [self.u('v%d' % n) for n in range(src[1], src[2] + 1)] + data = words[0] if count == 1 else 'uint%d(%s)' % (count, ', '.join(words)) + # Store* needs a multiple of four. As in #2059, the run-time part (VGPR and register soffset) is rounded down: + # an assumption that a dword access ignores the low two address bits, not a measurement. + self.emit('a = (%s + %d) & 0xfffffffcu;' % (' + '.join(terms), offset)) + store = '%s.Store%s(a, %s);' % (uav, '' if count == 1 else count, data) + self.emit(store if self.exec_known else 'if (exec & 1) %s' % store) + + def op_buffer_store_dwordx2(self, ops, mods): + self.op_buffer_store_dword(ops, mods, 2) + + def op_buffer_store_dwordx3(self, ops, mods): + self.op_buffer_store_dword(ops, mods, 3) + + def op_buffer_store_dwordx4(self, ops, mods): + self.op_buffer_store_dword(ops, mods, 4) + def tbuffer(self, ops, mods, count): dst = reg_range(ops[0]) formats = [m for m in mods if m.startswith('format:')] @@ -1696,6 +1800,8 @@ def op_tbuffer_load_format_xyzw(self, ops, mods): self.tbuffer(ops, mods, 4) def image(self, ops, mods, how): + if getattr(self, 'kind', None) == 'cs' and 'd16' in mods: + raise Unsupported('compute d16 image load requires validated SRV formats') dst = reg_range(ops[0]) dim = [m for m in mods if m.startswith('dim:')][0][4:] dmask = int([m for m in mods if m.startswith('dmask:')][0][6:], 0) @@ -1789,6 +1895,9 @@ def image(self, ops, mods, how): uv = 'float3(%s, %s, %s)' % (self.f(cs[0]), self.f(cs[1]), self.f(cs[2])) else: uv = 'float2(%s, %s)' % (self.f(cs[0]), self.f(cs[1])) + if how == 'sample' and self.kind == 'cs': + # A compute lane has no pixel quad to supply derivatives; level 0 would be a guess. + raise Unsupported('image_sample with implicit LOD in a compute program') if how == 'l': call = '%s.SampleLevel(%s, %s, %s)' % (tex, smp, uv, self.f(lod)) elif how == 'lz' or not self.exec_known or self.kind != 'ps' or len(self.blocks) > 0: @@ -2832,6 +2941,70 @@ def manifest(self): return '\n'.join(lines) + '\n' +class ComputePipeline(Pipeline): + """One compute program with the root and resource model of Pipeline. COMPUTE_PGM_RSRC2 and the thread group + size are pipeline register state the caller supplies; COMPUTE_PGM_RSRC2 is decoded as compute_store_aot does + (#1608). Root parameters from s4 are an inference (see Stage.setup_entry).""" + + def __init__(self, cs_code, root_blob, rsrc2, group, sampler_heap=None, refusals=None, decoded=None): + from compute_store_aot import checked_group, entry_registers + try: + self.entry = entry_registers(rsrc2) # (user SGPRs, {axis: group-ID SGPR}, thread-ID VGPRs) + self.group = checked_group(group) + except ValueError as reason: + raise Unsupported(str(reason)) from None + self.root = parse_root(root_blob) + self.vs_fetch, self.packed_position_vgpr, self.rtv_formats = None, None, () + self.sampler_heap = os.environ.get('X2W_SAMPLER_HEAP') == '1' if sampler_heap is None else sampler_heap + self.uses_sampler_heap = False + self.resources, self.uavs, self.samplers, self.uds = {}, {}, {}, [] + self.notes, self.modified = set(), set() + self.cs = Stage(self, 'cs', cs_code, refusals=refusals, decoded=decoded) + + def resource(self, key, kind): + if key in self.uavs: + raise Unsupported('descriptor %s used for a load and a store' % (key,)) + return super().resource(key, kind) + + def uav(self, key): + if key in self.resources: + raise Unsupported('descriptor %s used for a load and a store' % (key,)) + return 'u%d' % self.uavs.setdefault(key, len(self.uavs)) + + def common(self): + out = [line for line in super().common() if self.uds or not line.startswith('cbuffer entry')] + return out + ['RWByteAddressBuffer u%d : register(u%d);' % (i, i) for i in sorted(self.uavs.values())] + + def hlsl_cs(self): + s = self.cs + if s.exports: + raise Unsupported('export in a compute program') + body = s.body() + return '\n'.join(self.common() + ['[numthreads(%d, %d, %d)]' % self.group, + 'void main(uint3 gid : SV_GroupID, uint3 tid : SV_GroupThreadID) {'] + + s.declarations() + [' ' + line for line in s.entry] + body + ['}']) + '\n' + + def manifest(self): + # Version 2: `stage cs`, `group` and `uav` lines, which a graphics-only reader must not take for a draw. + 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': + where = 'table %d %d' % (source[1], off or 0) + elif source[0] == 'root': + where = 'root %d' % source[1] + else: + raise Unsupported('resource through %s' % (source,)) + lines.append('srv %d %s %s' % (r['index'], r['kind'], where)) + lines += ['uav %d table %d %d' % (i, key[0][1], key[1]) for key, i in sorted(self.uavs.items(), key=lambda kv: kv[1])] + for key, i in self.samplers.items(): + comparison = key[0] == 'cmp' + lines.append('%s %d %s' % ('smpc' if comparison else 'smp', i, ' '.join('0x%x' % w for w in key[comparison:]))) + if self.uses_sampler_heap: + lines.append('smpheap %d %d fallback %d' % (SAMPLER_HEAP_SIZE, SAMPLER_HEAP_SPACE, SAMPLER_HEAP_FALLBACK)) + return '\n'.join(lines) + '\n' + + def fnv(data, h=1469598103934665603): for b in data: h = ((h ^ b) * 1099511628211) & 0xffffffffffffffff