diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 42747530e6..5c25411c74 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -141,6 +141,8 @@ jobs: (["tests/startup_gfx2hlsl_mad_check.py", "binary", "llvm-mc-15"], {}), (["tests/shader_signed_zero_minmax_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_compute_check.py", "binary", "llvm-mc-15"], {}), + (["tests/startup_gfx2hlsl_compute_spill_check.py", "binary", "llvm-mc-15"], {}), + (["tests/startup_gfx2hlsl_compute_mask_spill_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_compute_lds_b64_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_compute_lds_b128_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_calculated_target_check.py", "binary", "llvm-mc-15"], {}), @@ -336,6 +338,8 @@ jobs: tests/startup_gfx2hlsl_neg_check.py \ tests/shader_signed_zero_minmax_check.py \ tests/startup_gfx2hlsl_compute_check.py \ + tests/startup_gfx2hlsl_compute_spill_check.py \ + tests/startup_gfx2hlsl_compute_mask_spill_check.py \ tests/startup_compute_lds_b64_check.py \ tests/startup_compute_lds_b128_check.py \ tests/startup_compute_translate_check.py \ diff --git a/AGENTS.md b/AGENTS.md index 90800c9151..378ebd05da 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -169,6 +169,8 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_interp_p2_hi_check.py ./out/pe-env/bin/python -B tests/shader_signed_zero_minmax_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_compute_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_compute_spill_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_compute_mask_spill_check.py ./out/pe-env/bin/python -B tests/startup_compute_image_store_check.py ./out/pe-env/bin/python -B tests/startup_compute_image_store_d16_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_heap_record_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 06d1968747..ecef6104c0 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4291,6 +4291,38 @@ if(EXISTS "${INTAKE_PYTHON}") PASS_REGULAR_EXPRESSION "control ${control}: rejected at word=[0-9]+ ") endforeach() endforeach() + # gfx2hlsl constant-lane SGPR spills of descriptor and pointer words in compute stages, across branches (#1723). + add_test(NAME startup_gfx2hlsl_compute_spill_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_compute_spill_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_compute_spill_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_compute_spill_check.py" dispatch "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_gfx2hlsl_compute_spill_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + foreach(control IN ITEMS s-arm-swapped s-store-dropped p-store-dropped) + add_test(NAME startup_gfx2hlsl_compute_spill_${control}_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_compute_spill_check.py" control ${control} "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_gfx2hlsl_compute_spill_${control}_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77 + PASS_REGULAR_EXPRESSION "control ${control}: rejected at word=[0-9]+ ") + endforeach() + endforeach() + # gfx2hlsl constant-lane SGPR spills of lane masks in compute stages (#1723). + add_test(NAME startup_gfx2hlsl_compute_mask_spill_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_compute_mask_spill_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_compute_mask_spill_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_compute_mask_spill_check.py" dispatch "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_gfx2hlsl_compute_mask_spill_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + foreach(control IN ITEMS m-saveexec-dropped m-mask-inverted v-branch-inverted) + add_test(NAME startup_gfx2hlsl_compute_mask_spill_${control}_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_compute_mask_spill_check.py" control ${control} "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_gfx2hlsl_compute_mask_spill_${control}_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77 + PASS_REGULAR_EXPRESSION "control ${control}: rejected at word=[0-9]+ ") + endforeach() + endforeach() # gfx2hlsl v_mad_u64_u32 / v_mad_i64_i32: helper math against a 64-bit reference, carry-out mask, refusals (Part of #1723). add_test(NAME startup_gfx2hlsl_mad64 COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_mad64_check.py") diff --git a/docs/experiments.md b/docs/experiments.md index 9a97ab9d25..80072fc221 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -15382,6 +15382,10 @@ The same slots are lowered in pixel stages with branches. The slot variable is a Wave64 lanes and vertex stages: the same slot model now accepts lanes 0..63 and vertex stages. A wave32 program takes the lane select modulo 32, so lanes `k` and `k + 32` of one VGPR would be one slot there and two in wave64; the translator does not know the wave size and refuses that pair. Lane 64 and above, compute stages and register-selected lanes stay refused. `tests/startup_gfx2hlsl_spill_wave64_check.py` draws a pixel program with slots on lanes 32, 33, 40 and 63 (16 x 16 pixels) and a vertex program with slots on lanes 0 and 48 whose reloads reach a flat parameter (one pixel), each compared with a reference replayed from the slot rule; wrong-lane and ignored-overwrite translations must fail. Run `ctest --preset dev --no-tests=error -R "^startup_gfx2hlsl_spill_wave64" -V`. +Compute stages: the same slots are lowered in `cs` (with branches, through the same write-before-read proof), and a spilled descriptor or pointer word (`desc`, `ptr`, `ptrhi` symbols) is carried by identity: the slot holds the symbol, nothing is emitted, and the reload restores the same symbol. A word whose symbol does not name one value (a modified descriptor word, a pointer with a non-numeric offset) is refused when it is spilled; writes of different symbols joined at a read are refused; lane masks are the next step (`startup_gfx2hlsl_compute_mask_spill`, below). A reload also keeps the provenance of the word it restores: a formatted buffer load past the entry block accepts a reloaded descriptor only when every write that can supply it was spilled from the entry block or from one untouched local table load of a proven pointer, i.e. when the original would have been accepted at the write. `tests/startup_gfx2hlsl_compute_spill_check.py` (`startup_gfx2hlsl_compute_spill*`) builds two gfx1013 compute fixtures from source (a read descriptor spilled in the entry block and the store descriptor spilled on both arms of a uniform branch, reloaded inside an `s_cbranch_execz` region for a formatted load and a store; a table pointer pair spilled and reloaded to load a descriptor), eight refused variants each with its exact reason, probes for `ptrhi` and modified words, eleven translator mutations that must each turn a control red, and a WARP/hardware dispatch with three mutated translations that must mismatch. + +Lane masks in compute: `v_writelane_b32` accepts `vcc_lo` or an SGPR the translator tracks as a mask (not proven-on-every-path marks, exec, `vcc_hi` and m0 stay refused), and `v_readlane_b32` reloads it into an SGPR (marked a mask again) or into `vcc_lo`. The translator models a mask per invocation as that invocation's own bit (a v_cmp stores `w`, or `exec & w` once EXEC is not known), and the write and the reload both ignore EXEC and copy the whole wave mask, so a reload used only as a mask has, in every invocation, the bit the invocation had at the write: the slot variable takes the mask's variable at the write and the reload copies it back. A reload is refused when an instruction reachable before its next write reads it as anything but a lane select or carry-in, an `s_cbranch_vccz` / `_vccnz` condition, a copy into `exec_lo` / `vcc_lo` or another spill, and when it may see two writes of which one is a mask. `tests/startup_gfx2hlsl_compute_mask_spill_check.py` (`startup_gfx2hlsl_compute_mask_spill*`) builds two gfx1013 compute fixtures from source (a `vcc_lo` and an SGPR compare result spilled, a uniform branch, both reloaded into SGPRs and used by `v_cndmask_b32_e64` and `s_and_saveexec_b32`; a `vcc_lo` reloaded into `vcc_lo` and used by `v_cndmask_b32_e32` and `s_cbranch_vccz`), twelve refused variants, translator mutations that must each turn a control red, and a WARP/hardware dispatch with three mutated translations that must mismatch. + The binary32 table (`VEC_F`) applies the same operand-count rule. Before this change, a form one source short (`v_add_f32 v1, v2`) raised `IndexError` in `Stage.one` instead of `Unsupported`. A form with one source too many (`v_med3_f32 v1, v2, v3, v4, v5`) translated with the extra source dropped. `tests/startup_gfx2hlsl_operand_count_check.py` (`startup_gfx2hlsl_operand_count`) checks every operation of both tables: one source fewer and one source more are refused, and the exact count translates. It also checks that the constant and accumulator forms (`v_fmac_f32`, `v_mac_f32`, `v_fmamk_f32`, `v_fmaak_f32`, `v_madmk_f32`, `v_madak_f32`) keep translating with their usual operands. As a control, it loads the translator with the new `VEC_F` guard removed and requires both old failures to come back. ## Startup translator: binary32 rounding diff --git a/tests/startup_gfx2hlsl_compute_mask_spill_check.py b/tests/startup_gfx2hlsl_compute_mask_spill_check.py new file mode 100644 index 0000000000..d1d6f02def --- /dev/null +++ b/tests/startup_gfx2hlsl_compute_mask_spill_check.py @@ -0,0 +1,455 @@ +"""Constant-lane SGPR spills of lane masks in compute stages of tools/startup/gfx2hlsl.py (#1723). + + (no arguments) translation controls and translator mutations, pure Python + binary assemble the fixture sources (gfx1013) and compare with the words here + dispatch + translate, compile with DXC cs_6_0, dispatch and compare every word + control + the same dispatch with a mutated translation, which must mismatch + +`v_writelane_b32 vN, M, k` copies the whole wave mask M (vcc_lo, or an SGPR holding a lane mask) into lane k of vN +whatever EXEC is, and `v_readlane_b32 D, vN, k` copies it back to every lane (AMD RDNA 2 ISA reference, VOP3 lane +operations). The translator models a lane mask per invocation as that invocation's own bit (a v_cmp stores `w`, or +`exec & w` once EXEC is not known, so an inactive lane's bit is 0). A reload that is only used as a mask afterwards +sees, in every invocation, the bit that invocation had at the write: the spill is the identity on that bit, so the slot +variable takes the mask's own variable at the write and the reload marks the destination a mask again. + +Fixtures (source-built gfx1013, 4 groups of 8 lanes, root constants key and stride in s4-s5, one descriptor table in s6): +- M spills the compare result vcc_lo (lanes below 5, lane 0 of v40) and an SGPR compare result s26 (lanes below 3, + lane 1), branches on the key, clobbers both, reloads them into SGPRs, selects with v_cndmask_b32_e64 and runs a + masked xor through s_and_saveexec_b32. +- V spills a vcc_lo that is the same in every lane of a group (2 > group index), clobbers vcc_lo, reloads it into + vcc_lo itself, selects with v_cndmask_b32_e32 and skips an add with s_cbranch_vccz. +""" +import re +import struct +import subprocess +import sys +import tempfile +import types +from pathlib import Path + +HERE = Path(__file__).resolve().parent +TOOLS = HERE.parent / 'tools' +sys.path.insert(0, str(TOOLS / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +import startup_gfx2hlsl_compute_check as C # noqa: E402 +import startup_gfx2hlsl_compute_spill_check as S # noqa: E402 + +failures = [] + + +def check(label, ok, detail=''): + print('%s: %s' % (label, 'ok' if ok else 'MISMATCH')) + if not ok: + failures.append(label) + if detail: + print(' ' + str(detail)[:1500]) + + +PROLOGUE = """\ +s_mov_b32 s10, s6 +s_mov_b32 s11, 0 +s_load_dwordx4 s[12:15], s[10:11], 0x0 +s_load_dwordx4 s[16:19], s[10:11], 0x10 +s_waitcnt lgkmcnt(0) +s_lshl_b32 s20, s7, 3 +v_add_nc_u32 v3, s20, v0 +v_lshlrev_b32 v4, 2, v3 +buffer_load_dword v5, v4, s[12:15], 0 offen +s_waitcnt vmcnt(0) +""" +M_SPILL = """\ +v_cmp_gt_u32 vcc_lo, 5, v0 +v_writelane_b32 v40, vcc_lo, 0 +v_cmp_gt_u32 s26, 3, v0 +v_writelane_b32 v40, s26, 1 +""" +M_BRANCH = """\ +s_and_b32 s22, s4, 1 +s_cmp_lg_u32 s22, 0 +s_cbranch_scc0 Lelse +v_mov_b32 v7, 100 +s_branch Ljoin +Lelse: +v_mov_b32 v7, 200 +Ljoin: +""" +M_CLOBBER = """\ +v_cmp_gt_u32 vcc_lo, 1, v0 +s_mov_b32 s26, 0 +""" +M_RELOAD = """\ +v_readlane_b32 s25, v40, 0 +v_readlane_b32 s27, v40, 1 +""" +M_USE = """\ +v_cndmask_b32_e64 v6, v5, v7, s25 +v_cndmask_b32_e64 v6, v6, 7, s27 +s_and_saveexec_b32 s23, s25 +v_xor_b32 v6, 0x55, v6 +s_mov_b32 exec_lo, s23 +buffer_store_dword v6, v4, s[16:19], 0 offen +s_endpgm +""" +SOURCE_M = PROLOGUE + M_SPILL + M_BRANCH + M_CLOBBER + M_RELOAD + M_USE +SOURCE_V = PROLOGUE + """\ +v_mov_b32 v8, s7 +v_cmp_gt_u32 vcc_lo, 2, v8 +v_writelane_b32 v40, vcc_lo, 0 +v_cmp_gt_u32 vcc_lo, 1, v0 +v_readlane_b32 vcc_lo, v40, 0 +v_cndmask_b32_e32 v6, v5, v8, vcc_lo +s_cbranch_vccz Lskip +v_add_nc_u32 v6, 1000, v6 +Lskip: +buffer_store_dword v6, v4, s[16:19], 0 offen +s_endpgm +""" +EXPECTED_ACCEPTED = {'M': SOURCE_M, 'V': SOURCE_V} + +# name -> (base source, [(old, new)], what the refusal must say, why it is refused). Each variant is a fixture with one +# change; it is assembled in binary mode like the fixtures and must be refused for that reason and no other. +VARIANTS = { + 'm0-source': (SOURCE_M, [('v_writelane_b32 v40, s26, 1\n', 's_mov_b32 m0, 5\nv_writelane_b32 v40, m0, 1\n')], + 'source m0 is a lane mask or m0', 'm0 is not a mask: it is refused as a spill source'), + 'exec-source': (SOURCE_M, [('v_writelane_b32 v40, s26, 1\n', 'v_writelane_b32 v40, exec_lo, 1\n')], + 'source exec_lo is a lane mask or m0', 'exec is refused as a spill source'), + 'vcc-hi-source': (SOURCE_M, [('v_writelane_b32 v40, vcc_lo, 0\n', 'v_writelane_b32 v40, vcc_hi, 0\n')], + 'source vcc_hi is a lane mask or m0', 'vcc_hi is not the wave32 mask'), + 'numeric-use': (SOURCE_M, [(M_RELOAD, M_RELOAD + 'v_add_nc_u32 v9, s25, v5\n')], 'reads as data', + 'the reloaded mask is read as numeric data'), + 'numeric-use-vcc': (SOURCE_V, [('Lskip:\n', 'Lskip:\nv_add_nc_u32 v9, vcc_lo, v5\n')], 'reads as data', + 'the reloaded vcc_lo is read as numeric data'), + 'masks-joined': (SOURCE_M, [(M_BRANCH, M_BRANCH.replace('v_mov_b32 v7, 100\n', 'v_mov_b32 v7, 100\n' + 'v_writelane_b32 v40, s26, 0\n'))], + 'one of them a lane mask', 'one arm overwrites lane 0 with a different mask'), + 'mask-and-number-joined': (SOURCE_M, [(M_BRANCH, M_BRANCH.replace('v_mov_b32 v7, 100\n', 'v_mov_b32 v7, 100\n' + 's_mov_b32 s28, 9\nv_writelane_b32 v40, s28, 0\n'))], + 'one of them a lane mask', 'one arm overwrites lane 0 with a number'), + 'reload-before-write': (SOURCE_M, [('v_writelane_b32 v40, s26, 1\n', '')], 'no v_writelane_b32 of it on some path', + 'lane 1 is never written'), + 'mask-reloaded-into-vcc-from-number': (SOURCE_V, [('v_writelane_b32 v40, vcc_lo, 0\n', 's_mov_b32 s28, 1\n' + 'v_writelane_b32 v40, s28, 0\n')], + 'requires an SGPR destination', 'a number is reloaded into vcc_lo'), + 'mask-from-one-arm': (SOURCE_M, [('v_cmp_gt_u32 s26, 3, v0\nv_writelane_b32 v40, s26, 1\n', 's_mov_b32 s26, 0\n'), + ('v_mov_b32 v7, 100\n', 'v_mov_b32 v7, 100\nv_cmp_gt_u32 s26, 3, v0\n'), + ('Ljoin:\n', 'Ljoin:\nv_writelane_b32 v40, s26, 1\n')], + 'lane mask not proven on every path', 'the mask is computed in one arm only'), + 'write-in-execz': (SOURCE_M, [(M_CLOBBER, M_CLOBBER + 's_mov_b32 s21, exec_lo\nv_cmp_gt_u32 vcc_lo, 5, v0\n' + 's_mov_b32 exec_lo, vcc_lo\ns_cbranch_execz Lz\nv_writelane_b32 v40, vcc_lo, 2\n' + 'Lz:\ns_mov_b32 exec_lo, s21\n')], + 'inside a block s_cbranch_execz skips per lane', 'a mask written inside an execz region'), + 'loop-carried': (SOURCE_M, [('Ljoin:\n', 'Ljoin:\ns_mov_b32 s22, 0\nLloop:\nv_readlane_b32 s25, v40, 0\n' + 'v_writelane_b32 v40, s25, 0\ns_add_u32 s22, s22, 1\ns_cmp_lt_u32 s22, 2\n' + 's_cbranch_scc1 Lloop\n')], + 'written later in a loop', 'a mask reloaded by a loop body that writes it again'), +} + + +def variant_source(name): + base, edits = VARIANTS[name][:2] + for old, new in edits: + assert base.count(old) == 1, (name, old) + base = base.replace(old, new) + return base + + +def all_sources(): + return {**EXPECTED_ACCEPTED, **{name: variant_source(name) for name in VARIANTS}} + + +ENCODING = (C.USER7 | C.TGID_X | C.tidig(1), (8, 1, 1), (4, 1, 1)) +WORDS = { + 'M': bytes.fromhex( + '06038abe80038bbe050308f4000000fa050408f4100000fa7fc08cbf0783148f1400064a82060834001030e004050380' + '703f8cbf8500887d280061d76a0001001a00c4d483000200280061d71a02010004811687168007bf030084bfff020e7e' + '64000000020082bfff020e7ec80000008100887d80039abe190060d7280101001b0060d728030100060001d5050f6600' + '060001d5060f6d00193c97beff0c0c3a550000001703febe001070e004060480000081bf'), + 'V': bytes.fromhex( + '06038abe80038bbe050308f4000000fa050408f4100000fa7fc08cbf0783148f1400064a82060834001030e004050380' + '703f8cbf0702107e8210887d280061d76a0001008100887d6a0060d72801010005110c02020086bfff0c0c4ae8030000' + '001070e004060480000081bf'), + 'm0-source': bytes.fromhex( + '06038abe80038bbe050308f4000000fa050408f4100000fa7fc08cbf0783148f1400064a82060834001030e004050380' + '703f8cbf8500887d280061d76a0001001a00c4d4830002008503fcbe280061d77c02010004811687168007bf030084bf' + 'ff020e7e64000000020082bfff020e7ec80000008100887d80039abe190060d7280101001b0060d728030100060001d5' + '050f6600060001d5060f6d00193c97beff0c0c3a550000001703febe001070e004060480000081bf'), + 'exec-source': bytes.fromhex( + '06038abe80038bbe050308f4000000fa050408f4100000fa7fc08cbf0783148f1400064a82060834001030e004050380' + '703f8cbf8500887d280061d76a0001001a00c4d483000200280061d77e02010004811687168007bf030084bfff020e7e' + '64000000020082bfff020e7ec80000008100887d80039abe190060d7280101001b0060d728030100060001d5050f6600' + '060001d5060f6d00193c97beff0c0c3a550000001703febe001070e004060480000081bf'), + 'vcc-hi-source': bytes.fromhex( + '06038abe80038bbe050308f4000000fa050408f4100000fa7fc08cbf0783148f1400064a82060834001030e004050380' + '703f8cbf8500887d280061d76b0001001a00c4d483000200280061d71a02010004811687168007bf030084bfff020e7e' + '64000000020082bfff020e7ec80000008100887d80039abe190060d7280101001b0060d728030100060001d5050f6600' + '060001d5060f6d00193c97beff0c0c3a550000001703febe001070e004060480000081bf'), + 'numeric-use': bytes.fromhex( + '06038abe80038bbe050308f4000000fa050408f4100000fa7fc08cbf0783148f1400064a82060834001030e004050380' + '703f8cbf8500887d280061d76a0001001a00c4d483000200280061d71a02010004811687168007bf030084bfff020e7e' + '64000000020082bfff020e7ec80000008100887d80039abe190060d7280101001b0060d728030100190a124a060001d5' + '050f6600060001d5060f6d00193c97beff0c0c3a550000001703febe001070e004060480000081bf'), + 'numeric-use-vcc': bytes.fromhex( + '06038abe80038bbe050308f4000000fa050408f4100000fa7fc08cbf0783148f1400064a82060834001030e004050380' + '703f8cbf0702107e8210887d280061d76a0001008100887d6a0060d72801010005110c02020086bfff0c0c4ae8030000' + '6a0a124a001070e004060480000081bf'), + 'masks-joined': bytes.fromhex( + '06038abe80038bbe050308f4000000fa050408f4100000fa7fc08cbf0783148f1400064a82060834001030e004050380' + '703f8cbf8500887d280061d76a0001001a00c4d483000200280061d71a02010004811687168007bf050084bfff020e7e' + '64000000280061d71a000100020082bfff020e7ec80000008100887d80039abe190060d7280101001b0060d728030100' + '060001d5050f6600060001d5060f6d00193c97beff0c0c3a550000001703febe001070e004060480000081bf'), + 'mask-and-number-joined': bytes.fromhex( + '06038abe80038bbe050308f4000000fa050408f4100000fa7fc08cbf0783148f1400064a82060834001030e004050380' + '703f8cbf8500887d280061d76a0001001a00c4d483000200280061d71a02010004811687168007bf060084bfff020e7e' + '6400000089039cbe280061d71c000100020082bfff020e7ec80000008100887d80039abe190060d7280101001b0060d7' + '28030100060001d5050f6600060001d5060f6d00193c97beff0c0c3a550000001703febe001070e004060480000081bf'), + 'reload-before-write': bytes.fromhex( + '06038abe80038bbe050308f4000000fa050408f4100000fa7fc08cbf0783148f1400064a82060834001030e004050380' + '703f8cbf8500887d280061d76a0001001a00c4d48300020004811687168007bf030084bfff020e7e64000000020082bf' + 'ff020e7ec80000008100887d80039abe190060d7280101001b0060d728030100060001d5050f6600060001d5060f6d00' + '193c97beff0c0c3a550000001703febe001070e004060480000081bf'), + 'mask-reloaded-into-vcc-from-number': bytes.fromhex( + '06038abe80038bbe050308f4000000fa050408f4100000fa7fc08cbf0783148f1400064a82060834001030e004050380' + '703f8cbf0702107e8210887d81039cbe280061d71c0001008100887d6a0060d72801010005110c02020086bfff0c0c4a' + 'e8030000001070e004060480000081bf'), + 'mask-from-one-arm': bytes.fromhex( + '06038abe80038bbe050308f4000000fa050408f4100000fa7fc08cbf0783148f1400064a82060834001030e004050380' + '703f8cbf8500887d280061d76a00010080039abe04811687168007bf050084bfff020e7e640000001a00c4d483000200' + '020082bfff020e7ec8000000280061d71a0201008100887d80039abe190060d7280101001b0060d728030100060001d5' + '050f6600060001d5060f6d00193c97beff0c0c3a550000001703febe001070e004060480000081bf'), + 'write-in-execz': bytes.fromhex( + '06038abe80038bbe050308f4000000fa050408f4100000fa7fc08cbf0783148f1400064a82060834001030e004050380' + '703f8cbf8500887d280061d76a0001001a00c4d483000200280061d71a02010004811687168007bf030084bfff020e7e' + '64000000020082bfff020e7ec80000008100887d80039abe7e0395be8500887d6a03febe020088bf280061d76a040100' + '1503febe190060d7280101001b0060d728030100060001d5050f6600060001d5060f6d00193c97beff0c0c3a55000000' + '1703febe001070e004060480000081bf'), + 'loop-carried': bytes.fromhex( + '06038abe80038bbe050308f4000000fa050408f4100000fa7fc08cbf0783148f1400064a82060834001030e004050380' + '703f8cbf8500887d280061d76a0001001a00c4d483000200280061d71a02010004811687168007bf030084bfff020e7e' + '64000000020082bfff020e7ec8000000800396be190060d728010100280061d7190001001681168016820abff9ff85bf' + '8100887d80039abe190060d7280101001b0060d728030100060001d5050f6600060001d5060f6d00193c97beff0c0c3a' + '550000001703febe001070e004060480000081bf'), +} +WORDS_OUT = C.WORDS +SENTINEL = C.SENTINEL +KEY = C.KEY + + +def translate(name, code=None, module=G): + return module.ComputePipeline(code or WORDS[name], C.root_blob(), ENCODING[0], ENCODING[1]) + + +def refusal(name, module=G): + try: + translate(name, module=module).hlsl_cs() + except module.Unsupported as reason: + return str(reason) + return None + + +def expected(name): + out = [SENTINEL] * WORDS_OUT + for gx in range(4): + for tx in range(8): + i, word = gx * 8 + tx, C.input_word(gx * 8 + tx) + if name == 'M': + v7 = 100 if KEY & 1 else 200 + a, b = tx < 5, tx < 3 + word = v7 if a else word + word = 7 if b else word + out[i] = word ^ 0x55 if a else word + else: + word = gx if gx < 2 else word + out[i] = word + 1000 if gx < 2 else word + return out + + +def controls(module=G, quiet=False): + """-> the labels of the controls that failed (all printed unless quiet).""" + red = [] + + def verdict(label, ok, detail=''): + if not ok: + red.append(label) + if not quiet: + check(label, ok, detail) + + for name in EXPECTED_ACCEPTED: + reason = refusal(name, module) + verdict('fixture %s translates (%s)' % (name, reason), reason is None) + for name, (_, _, fragment, why) in VARIANTS.items(): + reason = refusal(name, module) + verdict('refused: %s (%s)' % (why, reason), reason is not None and fragment in reason, reason) + verdict('mask spills stay refused in a pixel stage (%s)' % probe_pixel(module), 'holds a lane mask or descriptor' in + probe_pixel(module)) + return red + + +def probe_pixel(module): + """A pixel stage that spills a lane mask keeps the refusal of step 1: only compute stages model the mask this way.""" + stage = module.Stage.__new__(module.Stage) + stage.kind, stage.lines, stage.sym = 'ps', [], {} + stage.used_s, stage.used_v, stage.uniform_v, stage.varying_s = set(), set(), set(), set() + stage.scc_uniform, stage.exec_known, stage.has_branches, stage.blocks, stage.masks = True, True, False, [], {20} + stage.join_masks = set() + stage.ins = [(0, 1, 'v_writelane_b32', 'v_writelane_b32 v10, s20, 3')] + try: + stage.one('v_writelane_b32', 'v_writelane_b32 v10, s20, 3') + except module.Unsupported as why: + return str(why) + return 'accepted' + + +# Each translator mutation must turn at least one control red. +MUTATIONS = { + 'a mask is not marked again after the reload': (' if mask:\n self.masks.add(dst[1])', + ' if False:\n self.masks.add(dst[1])'), + 'a reloaded mask is read as data': (" if not (self.per_lane_read(j, key) or copy or", " if not (True or copy or"), + 'a lane select is not a mask read': (" if not (self.per_lane_read(j, key) or copy or", " if not (copy or"), + 'two writes with a mask join': (' if any(s[3] for s in stored) and len(stored) > 1:', ' if False:'), + 'm0 is a mask source': (" elif ops[1] in ('vcc', 'vcc_lo', 'vcc_hi', 'exec', 'exec_lo', 'exec_hi', 'm0'):", + " elif ops[1] in ('vcc', 'vcc_lo', 'vcc_hi', 'exec', 'exec_lo', 'exec_hi'):"), + 'exec is a mask source': (" elif ops[1] in ('vcc', 'vcc_lo', 'vcc_hi', 'exec', 'exec_lo', 'exec_hi', 'm0'):", + " elif ops[1] in ('vcc', 'vcc_lo', 'vcc_hi', 'm0'):"), + 'vcc_hi is a mask source': (" if ops[1] == 'vcc_lo' and self.spills_lane_masks():", + " if ops[1] in ('vcc_hi', 'vcc_lo') and self.spills_lane_masks():"), + 'a mask not proven on every path is spilled': (' if src[1] in self.join_masks:', ' if False:'), + 'the write stores the inverted bit': ("value, sym, uniform, proven, mask = 'vcc', None", + "value, sym, uniform, proven, mask = '(vcc ^ 1u)', None"), + 'the reload restores the neighbouring slot': (" self.set_s(dst[1], 'sp%d_%d' % (n, lane), sym=None if mask else sym,", + " self.set_s(dst[1], 'sp%d_%d' % (n, lane ^ int(mask)), sym=None if mask else sym,"), + 'every stage spills masks': (" return getattr(self, 'kind', None) == 'cs'", ' return True'), + 'a number is reloaded into vcc_lo': (" if not (mask and ops[0] == 'vcc_lo'):", " if ops[0] != 'vcc_lo':"), + 'no loop-carried refusal': (" if max(writes) > i:", " if False:"), + 'no write-before-read refusal': (" if writes is None:\n raise Unsupported('v_readlane_b32 reads v%d lane %d with no", + " if writes is None and False:\n raise Unsupported('v_readlane_b32 reads v%d lane %d with no"), +} + + +def mutated(old, new): + source = (TOOLS / 'startup' / 'gfx2hlsl.py').read_text(encoding='utf-8').replace('\r\n', '\n') + assert source.count(old) == 1, old + module = types.ModuleType('gfx2hlsl_mutant') + module.__file__ = str(TOOLS / 'startup' / 'gfx2hlsl.py') + exec(compile(source.replace(old, new), module.__file__, 'exec'), module.__dict__) + return module + + +def check_mutations(): + for label, (old, new) in MUTATIONS.items(): + try: + module = mutated(old, new) + red = controls(module, quiet=True) + check_text(module, quiet=True) + except Exception as error: # a mutant that crashes the translator is caught as well + red = ['crash: %s' % error] + check('mutation "%s" turns %d control(s) red: %s' % (label, len(red), red[:3]), bool(red)) + + +def check_text(module=G, quiet=False): + """-> the labels of the text checks that failed. The slot takes the mask's variable at the write and the reload copies + it back, which is what makes the spill the identity on each invocation's bit.""" + red = [] + + def verdict(label, ok, detail=''): + if not ok: + red.append(label) + if not quiet: + check(label, ok, detail) + + m, v = translate('M', module=module).hlsl_cs(), translate('V', module=module).hlsl_cs() + lines = [line.strip() for line in m.splitlines()] + verdict('M: the slots take the mask variables, the reloads copy them back', + 'sp40_0 = vcc;' in lines and 'sp40_1 = s26;' in lines and 's25 = sp40_0;' in lines and 's27 = sp40_1;' in lines, m) + verdict('M: the compare writes the bit of its own invocation', 'vcc = ((0x00000005u > v0) ? 1u : 0u);' in lines, m) + verdict('M: the reloaded masks select and narrow EXEC', 'v6 = (s25 & 1) ? v7 : v5;' in lines and + 'exec = (exec & s25) & 1; scc = exec != 0;' in lines, m) + vl = [line.strip() for line in v.splitlines()] + verdict('V: vcc_lo is reloaded into vcc and drives the branch', + 'sp40_0 = vcc;' in vl and 'vcc = sp40_0;' in vl and 'pc = ((vcc & 1) == 0) ? 2 : 1;' in vl, v) + return red + + +# ---- binary and dispatch --------------------------------------------------------------------------------------------- +def check_binary(llvm_mc): + for name, source in all_sources().items(): + built = S.assemble_labels(llvm_mc, source) + check('llvm-mc assembles %s to the recorded words' % name, built == WORDS[name], built.hex()) + + +# control -> (case, text the translation must contain once, replacement) +CONTROLS = { + 'm-saveexec-dropped': ('M', 'exec = (exec & s25) & 1; scc = exec != 0;', 'scc = exec != 0;'), + 'm-mask-inverted': ('M', 'sp40_0 = vcc;', 'sp40_0 = vcc ^ 1u;'), + 'v-branch-inverted': ('V', 'pc = ((vcc & 1) == 0) ? 2 : 1;', 'pc = ((vcc & 1) != 0) ? 2 : 1;'), +} + + +def run_case(name, dxc, runner, adapter, directory, control=None): + hlsl = translate(name).hlsl_cs() + if control: + _, old, new = CONTROLS[control] + assert hlsl.count(old) == 1, (control, hlsl) + hlsl = hlsl.replace(old, new) + 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 = ENCODING[2] + constants = [KEY, C.STRIDE] + [0] * 14 + case.write_bytes(struct.pack(' assemble the fixture sources (gfx1013) and compare with the words here + dispatch + translate, compile with DXC cs_6_0, dispatch and compare every word + control + the same dispatch with a mutated translation, which must mismatch + +`v_writelane_b32 vN, sM, k` parks SGPR sM in lane k of vN and `v_readlane_b32 sD, vN, k` reads it back; both ignore +EXEC (AMD RDNA 2 ISA reference, VOP3 lane operations). A descriptor or pointer word has no run-time value in the +translation: it is a symbol (`('desc', table, offset, dword)`, `('ptr', ...)`), so the slot carries the symbol and the +reload restores the same one. The write-before-read proof of tests/startup_gfx2hlsl_spill_branches_check.py (a write +on every path, regions the wave runs while a thread skips them, loop-carried reads) decides whether a reload sees the +symbol, and a reload keeps the provenance of the word it restores: a formatted buffer load past the entry block +accepts a reloaded descriptor only when every write that can supply it was itself the word of an entry-block or +local table load. + +Fixtures (source-built gfx1013, root constants key and stride in s4-s5, one descriptor table in s6): +- S spills the table's read descriptor s[12:15] (formatted load) in the entry block and its store descriptor s[16:19] + in both arms of a uniform branch on the key, clobbers both, and inside an s_cbranch_execz region reloads them and + loads RG16_UINT words through one and stores through the other. 16 lanes, lanes below 12 store four words each. +- P spills the table pointer pair s[10:11] (the low word a table pointer, the high word the constant zero), clobbers + it, reloads it inside an s_cbranch_execz region and loads the store descriptor through it (shape of case J of + tests/startup_gfx2hlsl_compute_check.py). Four groups of eight lanes, lanes below 3 store one word. +""" +import re +import struct +import subprocess +import sys +import tempfile +import types +from pathlib import Path + +HERE = Path(__file__).resolve().parent +TOOLS = HERE.parent / 'tools' +sys.path.insert(0, str(TOOLS / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +import startup_gfx2hlsl_compute_check as C # noqa: E402 + +failures = [] + + +def check(label, ok, detail=''): + print('%s: %s' % (label, 'ok' if ok else 'MISMATCH')) + if not ok: + failures.append(label) + if detail: + print(' ' + str(detail)[:1500]) + + +SOURCE_S = """\ +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_writelane_b32 v40, s12, 0 +v_writelane_b32 v40, s13, 1 +v_writelane_b32 v40, s14, 2 +v_writelane_b32 v40, s15, 3 +s_and_b32 s23, s4, 1 +s_cmp_lg_u32 s23, 0 +s_cbranch_scc0 Lelse +v_writelane_b32 v40, s16, 4 +v_writelane_b32 v40, s17, 5 +v_writelane_b32 v40, s18, 6 +v_writelane_b32 v40, s19, 7 +v_mov_b32 v1, 1 +s_branch Ljoin +Lelse: +v_writelane_b32 v40, s16, 4 +v_writelane_b32 v40, s17, 5 +v_writelane_b32 v40, s18, 6 +v_writelane_b32 v40, s19, 7 +v_mov_b32 v1, 0 +Ljoin: +s_mov_b32 s12, 0 +s_mov_b32 s13, 0 +s_mov_b32 s14, 0 +s_mov_b32 s15, 0 +s_mov_b32 s16, 0 +s_mov_b32 s17, 0 +s_mov_b32 s18, 0 +s_mov_b32 s19, 0 +v_lshlrev_b32 v4, 4, v0 +s_mov_b32 s21, exec_lo +v_cmp_gt_u32 vcc_lo, 12, v0 +s_mov_b32 exec_lo, vcc_lo +s_cbranch_execz Lend +v_readlane_b32 s12, v40, 0 +v_readlane_b32 s13, v40, 1 +v_readlane_b32 s14, v40, 2 +v_readlane_b32 s15, v40, 3 +v_readlane_b32 s16, v40, 4 +v_readlane_b32 s17, v40, 5 +v_readlane_b32 s18, v40, 6 +v_readlane_b32 s19, v40, 7 +buffer_load_format_xyzw v[5:8], v[0:1], s[12:15], 0 idxen offen offset:2 +s_waitcnt vmcnt(0) +buffer_store_dwordx4 v[5:8], v4, s[16:19], 0 offen +Lend: +s_mov_b32 exec_lo, s21 +s_endpgm +""" +SOURCE_P = """\ +s_mov_b32 s10, s6 +s_mov_b32 s11, 0 +s_load_dwordx4 s[12:15], s[10:11], 0x0 +s_waitcnt lgkmcnt(0) +v_writelane_b32 v41, s10, 0 +v_writelane_b32 v41, s11, 1 +s_mov_b32 s10, 0 +s_mov_b32 s11, 0 +s_lshl_b32 s20, s7, 3 +v_add_nc_u32 v3, s20, v0 +v_lshlrev_b32 v4, 2, v3 +s_mov_b32 s21, exec_lo +v_cmp_gt_u32 vcc_lo, 3, v0 +s_mov_b32 exec_lo, vcc_lo +s_cbranch_execz Lend +v_readlane_b32 s10, v41, 0 +v_readlane_b32 s11, v41, 1 +s_load_dwordx4 s[16:19], s[10:11], 0x10 +s_mul_i32 s22, s7, s5 +s_add_u32 s22, s22, s4 +buffer_load_dword v5, v4, s[12:15], 0 offen +s_waitcnt vmcnt(0) lgkmcnt(0) +v_xor_b32 v5, s22, v5 +buffer_store_dword v5, v4, s[16:19], 0 offen +Lend: +s_mov_b32 exec_lo, s21 +s_endpgm +""" +S_ARM = ('v_writelane_b32 v40, s16, 4\nv_writelane_b32 v40, s17, 5\nv_writelane_b32 v40, s18, 6\n' + 'v_writelane_b32 v40, s19, 7\n') +S_ENTRY = 'v_writelane_b32 v40, s12, 0\nv_writelane_b32 v40, s13, 1\nv_writelane_b32 v40, s14, 2\nv_writelane_b32 v40, s15, 3\n' + +# name -> (base source, [(old, new)], what the refusal must say, why it is refused). Each variant is a fixture with one +# change; it is assembled in binary mode like the fixtures and must be refused for that reason and no other. +VARIANTS = { + 'reload-before-write': (SOURCE_S, [(S_ENTRY, '')], 'no v_writelane_b32 of it on some path', + 'the read descriptor is never written to its lanes'), + 'two-descriptors-joined': (SOURCE_S, [(S_ARM + 'v_mov_b32 v1, 0', S_ARM.replace('s16', 's12').replace('s17', 's13') + .replace('s18', 's14').replace('s19', 's15') + 'v_mov_b32 v1, 0')], + 'joins different descriptor or pointer words', + 'one arm spills the read descriptor and the other the store descriptor into the same lanes'), + 'modified-word': (SOURCE_S, [('s_and_b32 s23, s4, 1', 's_and_b32 s17, s17, 0xc000ffff\ns_and_b32 s23, s4, 1')], + 'modified descriptor or pointer word', 'a stride word rewritten before the spill'), + 'lane-mask': (SOURCE_S, [('v_writelane_b32 v40, s16, 4\nv_writelane_b32 v40, s17, 5\nv_writelane_b32 v40, s18, 6\n' + 'v_writelane_b32 v40, s19, 7\nv_mov_b32 v1, 1', + 'v_cmp_gt_u32 s20, 12, v0\nv_writelane_b32 v40, s20, 4\nv_mov_b32 v1, 1')], + 'one of them a lane mask', 'a compare result spilled in one arm where the other arm spills a descriptor ' + '(lane masks have their own fixtures in tests/startup_gfx2hlsl_compute_mask_spill_check.py)'), + 'wrong-lane': (SOURCE_S, [('v_readlane_b32 s13, v40, 1', 'v_readlane_b32 s13, v40, 5')], + 'descriptor whose words were rewritten', 'word 1 of the descriptor reloaded from the lane of word 5'), + 'unproven-descriptor': (SOURCE_S, [(S_ENTRY, ''), ('v_mov_b32 v1, 1', S_ENTRY + 'v_mov_b32 v1, 1'), + ('v_mov_b32 v1, 0', S_ENTRY + 'v_mov_b32 v1, 0')], + 'requires descriptor words proven in the entry block', + 'the read descriptor is spilled in the arms, where its load is not local'), + 'written-in-region-read-outside': (SOURCE_S, [ + (S_ARM + 'v_mov_b32 v1, 1', 'v_mov_b32 v1, 1'), (S_ARM + 'v_mov_b32 v1, 0', 'v_mov_b32 v1, 0'), + (''.join('s_mov_b32 s%d, 0\n' % r for r in range(16, 20)), ''), + (''.join('v_readlane_b32 s%d, v40, %d\n' % (r, r - 12) for r in range(16, 20)), ''), + ('s_cbranch_execz Lend\n', 's_cbranch_execz Lend\n' + S_ARM), ('Lend:\n', 'Lend:\nv_readlane_b32 s16, v40, 4\n')], + 'effect outside scalar registers', 'the store descriptor is written inside the ' + 'execz region (the lane write is a cross-lane effect there) and reloaded after it'), + 'loop-carried': (SOURCE_S, [('Ljoin:\n', 'Ljoin:\ns_mov_b32 s22, 0\nLloop:\nv_readlane_b32 s16, v40, 4\n' + 'v_writelane_b32 v40, s16, 4\ns_add_u32 s22, s22, 1\ns_cmp_lt_u32 s22, 2\n' + 's_cbranch_scc1 Lloop\n')], + 'written later in a loop', 'a reload whose lane is written again by the loop body'), +} +EXPECTED_ACCEPTED = {'S': SOURCE_S, 'P': SOURCE_P} + + +def variant_source(name): + base, edits = VARIANTS[name][:2] + for old, new in edits: + assert base.count(old) == 1, (name, old) + base = base.replace(old, new) + return base + + +def all_sources(): + return {**EXPECTED_ACCEPTED, **{name: variant_source(name) for name in VARIANTS}} + + +def assemble_labels(llvm_mc, source): + """llvm-mc leaves a branch label to the linker, so the words come from a first pass for the instruction sizes.""" + from startup_flat_param_check import assemble + lines = source.splitlines() + plain = [line for line in lines if not line.endswith(':')] + sizes = [] + for line in plain: + sizes.append(len(assemble(llvm_mc, line + '\n'))) + labels, position, at = {}, 0, 0 + for line in lines: + if line.endswith(':'): + labels[line[:-1]] = position + else: + position += sizes[at] + at += 1 + out, position = [], 0 + for line, size in zip(plain, sizes): + m = re.fullmatch(r'(s_c?branch\w*) (L\w+)', line) + if m: + line = '%s %d' % (m[1], (labels[m[2]] - (position + 4)) // 4) + out.append(line) + position += size + words = bytearray() + for line in out: + built = bytearray(assemble(llvm_mc, line + '\n')) + if re.match(r'v_(read|write)lane_b32\b|v_cmp\w*\s', line) and len(built) == 8: + # src2 of the lane operations and of the VOP3 compares is unused: LLVM 15 encodes it as 0, newer LLVM as the + # inline constant 0 (128). + # Clear it so the recorded words hold for both. + dword = int.from_bytes(built[4:8], 'little') & ~(0x1ff << 18) + built[4:8] = dword.to_bytes(4, 'little') + words += built + return bytes(words) + + +# CASE: (source, words as hex, rsrc2, group size, group counts) +USER7, TGID_X, tidig = C.USER7, C.TGID_X, C.tidig +CASES_ENCODING = { + 'S': (USER7, (16, 1, 1), (1, 1, 1)), + 'P': (USER7 | TGID_X | tidig(1), (8, 1, 1), (4, 1, 1)), +} +WORDS = { + 'S': bytes.fromhex( + '06038abe80038bbe05030cf4000000fa7fc08cbf280061d70c000100280061d70d020100280061d70e040100280061d7' + '0f06010004811787178007bf0a0084bf280061d710080100280061d7110a0100280061d7120c0100280061d7130e0100' + '8102027e090082bf280061d710080100280061d7110a0100280061d7120c0100280061d7130e01008002027e80038cbe' + '80038dbe80038ebe80038fbe800390be800391be800392be800393be840008347e0395be8c00887d6a03febe150088bf' + '0c0060d7280101000d0060d7280301000e0060d7280501000f0060d728070100100060d728090100110060d7280b0100' + '120060d7280d0100130060d7280f010002300ce000050380703f8cbf001078e0040504801503febe000081bf'), + 'P': bytes.fromhex( + '06038abe80038bbe050308f4000000fa7fc08cbf290061d70a000100290061d70b02010080038abe80038bbe0783148f' + '1400064a820608347e0395be8300887d6a03febe0e0088bf0a0060d7290101000b0060d729030100050408f4100000fa' + '0705169316041680001030e00405038070008cbf160a0a3a001070e0040504801503febe000081bf'), + 'reload-before-write': bytes.fromhex( + '06038abe80038bbe05030cf4000000fa7fc08cbf04811787178007bf0a0084bf280061d710080100280061d7110a0100' + '280061d7120c0100280061d7130e01008102027e090082bf280061d710080100280061d7110a0100280061d7120c0100' + '280061d7130e01008002027e80038cbe80038dbe80038ebe80038fbe800390be800391be800392be800393be84000834' + '7e0395be8c00887d6a03febe150088bf0c0060d7280101000d0060d7280301000e0060d7280501000f0060d728070100' + '100060d728090100110060d7280b0100120060d7280d0100130060d7280f010002300ce000050380703f8cbf001078e0' + '040504801503febe000081bf'), + 'two-descriptors-joined': bytes.fromhex( + '06038abe80038bbe05030cf4000000fa7fc08cbf280061d70c000100280061d70d020100280061d70e040100280061d7' + '0f06010004811787178007bf0a0084bf280061d710080100280061d7110a0100280061d7120c0100280061d7130e0100' + '8102027e090082bf280061d70c080100280061d70d0a0100280061d70e0c0100280061d70f0e01008002027e80038cbe' + '80038dbe80038ebe80038fbe800390be800391be800392be800393be840008347e0395be8c00887d6a03febe150088bf' + '0c0060d7280101000d0060d7280301000e0060d7280501000f0060d728070100100060d728090100110060d7280b0100' + '120060d7280d0100130060d7280f010002300ce000050380703f8cbf001078e0040504801503febe000081bf'), + 'modified-word': bytes.fromhex( + '06038abe80038bbe05030cf4000000fa7fc08cbf280061d70c000100280061d70d020100280061d70e040100280061d7' + '0f06010011ff1187ffff00c004811787178007bf0a0084bf280061d710080100280061d7110a0100280061d7120c0100' + '280061d7130e01008102027e090082bf280061d710080100280061d7110a0100280061d7120c0100280061d7130e0100' + '8002027e80038cbe80038dbe80038ebe80038fbe800390be800391be800392be800393be840008347e0395be8c00887d' + '6a03febe150088bf0c0060d7280101000d0060d7280301000e0060d7280501000f0060d728070100100060d728090100' + '110060d7280b0100120060d7280d0100130060d7280f010002300ce000050380703f8cbf001078e0040504801503febe' + '000081bf'), + 'lane-mask': bytes.fromhex( + '06038abe80038bbe05030cf4000000fa7fc08cbf280061d70c000100280061d70d020100280061d70e040100280061d7' + '0f06010004811787178007bf060084bf1400c4d48c000200280061d7140801008102027e090082bf280061d710080100' + '280061d7110a0100280061d7120c0100280061d7130e01008002027e80038cbe80038dbe80038ebe80038fbe800390be' + '800391be800392be800393be840008347e0395be8c00887d6a03febe150088bf0c0060d7280101000d0060d728030100' + '0e0060d7280501000f0060d728070100100060d728090100110060d7280b0100120060d7280d0100130060d7280f0100' + '02300ce000050380703f8cbf001078e0040504801503febe000081bf'), + 'wrong-lane': bytes.fromhex( + '06038abe80038bbe05030cf4000000fa7fc08cbf280061d70c000100280061d70d020100280061d70e040100280061d7' + '0f06010004811787178007bf0a0084bf280061d710080100280061d7110a0100280061d7120c0100280061d7130e0100' + '8102027e090082bf280061d710080100280061d7110a0100280061d7120c0100280061d7130e01008002027e80038cbe' + '80038dbe80038ebe80038fbe800390be800391be800392be800393be840008347e0395be8c00887d6a03febe150088bf' + '0c0060d7280101000d0060d7280b01000e0060d7280501000f0060d728070100100060d728090100110060d7280b0100' + '120060d7280d0100130060d7280f010002300ce000050380703f8cbf001078e0040504801503febe000081bf'), + 'unproven-descriptor': bytes.fromhex( + '06038abe80038bbe05030cf4000000fa7fc08cbf04811787178007bf120084bf280061d710080100280061d7110a0100' + '280061d7120c0100280061d7130e0100280061d70c000100280061d70d020100280061d70e040100280061d70f060100' + '8102027e110082bf280061d710080100280061d7110a0100280061d7120c0100280061d7130e0100280061d70c000100' + '280061d70d020100280061d70e040100280061d70f0601008002027e80038cbe80038dbe80038ebe80038fbe800390be' + '800391be800392be800393be840008347e0395be8c00887d6a03febe150088bf0c0060d7280101000d0060d728030100' + '0e0060d7280501000f0060d728070100100060d728090100110060d7280b0100120060d7280d0100130060d7280f0100' + '02300ce000050380703f8cbf001078e0040504801503febe000081bf'), + 'written-in-region-read-outside': bytes.fromhex( + '06038abe80038bbe05030cf4000000fa7fc08cbf280061d70c000100280061d70d020100280061d70e040100280061d7' + '0f06010004811787178007bf020084bf8102027e010082bf8002027e80038cbe80038dbe80038ebe80038fbe84000834' + '7e0395be8c00887d6a03febe150088bf280061d710080100280061d7110a0100280061d7120c0100280061d7130e0100' + '0c0060d7280101000d0060d7280301000e0060d7280501000f0060d72807010002300ce000050380703f8cbf001078e0' + '04050480100060d7280901001503febe000081bf'), + 'loop-carried': bytes.fromhex( + '06038abe80038bbe05030cf4000000fa7fc08cbf280061d70c000100280061d70d020100280061d70e040100280061d7' + '0f06010004811787178007bf0a0084bf280061d710080100280061d7110a0100280061d7120c0100280061d7130e0100' + '8102027e090082bf280061d710080100280061d7110a0100280061d7120c0100280061d7130e01008002027e800396be' + '100060d728090100280061d7100801001681168016820abff9ff85bf80038cbe80038dbe80038ebe80038fbe800390be' + '800391be800392be800393be840008347e0395be8c00887d6a03febe150088bf0c0060d7280101000d0060d728030100' + '0e0060d7280501000f0060d728070100100060d728090100110060d7280b0100120060d7280d0100130060d7280f0100' + '02300ce000050380703f8cbf001078e0040504801503febe000081bf'), +} + + +KEY, STRIDE, SENTINEL, WORDS_OUT = C.KEY, C.STRIDE, C.SENTINEL, C.WORDS +LIVE_LANES = 12 + + +def expected(name): + out = [SENTINEL] * WORDS_OUT + if name == 'S': + data = C.formatted_input() + for lane in range(LIVE_LANES): # the same RG16_UINT words as case L-uint, the lanes the compare leaves active + low, high = struct.unpack_from(' the labels of the controls that failed (all printed unless quiet).""" + red = [] + + def verdict(label, ok, detail=''): + if not ok: + red.append(label) + if not quiet: + check(label, ok, detail) + + for name in ('S', 'P'): + reason = refusal(name, module) + verdict('fixture %s translates (%s)' % (name, reason), reason is None) + for name, (_, _, fragment, why) in VARIANTS.items(): + reason = refusal(name, module) + verdict('refused: %s (%s)' % (why, reason), reason is not None and fragment in reason, reason) + return red + + +def probe_refusals(): + """Unit probes on a compute Stage that has symbols a table program cannot give it: ptrhi, a pointer with an offset.""" + def reason(sym_text, source_sym, kind='cs'): + stage = G.Stage.__new__(G.Stage) + stage.kind, stage.lines, stage.sym = kind, [], {20: source_sym} if source_sym else {} + stage.used_s, stage.used_v, stage.uniform_v, stage.varying_s = set(), set(), set(), set() + stage.scc_uniform, stage.exec_known, stage.has_branches, stage.blocks, stage.masks = True, True, False, [], set() + stage.ins = [(4 * i, 1, a.split(' ', 1)[0], a) for i, a in enumerate(sym_text)] + for _, _, name, asm in stage.ins: + try: + stage.one(name, asm) + except G.Unsupported as why: + return str(why) + return stage + + spill = ['v_writelane_b32 v10, s20, 3', 'v_readlane_b32 s21, v10, 3'] + for label, sym in (('a table pointer', ('ptr', ('table', 0))), ('the high word of a root pointer', ('ptrhi', ('root', 2))), + ('a descriptor word', ('desc', ('table', 0), 0, 1))): + stage = reason(spill, sym) + check('compute stage spills %s and reloads the same symbol' % label, + not isinstance(stage, str) and stage.sym.get(21) == sym, stage) + for label, sym in (('a pointer with an offset', ('ptr', ('table', 0), 'added')), + ('a descriptor word with its stride cleared', ('desc', ('table', 0), 0, 1, 'stride0'))): + text = reason(spill, sym) + check('refused: %s (%s)' % (label, text), isinstance(text, str) and 'modified descriptor or pointer word' in text) + for label, sym in (('a table pointer', ('ptr', ('table', 0))), ('a descriptor word', ('desc', ('table', 0), 0, 1))): + text = reason(spill, sym, kind='ps') + check('refused: %s in a pixel stage (%s)' % (label, text), + isinstance(text, str) and 'holds a lane mask or descriptor' in text) + + +# Each translator mutation must turn at least one control red. +MUTATIONS = { + 'the reload restores no symbol': (' self.set_s(dst[1], \'sp%d_%d\' % (n, lane), sym=sym, uniform=uniform)', + ' self.set_s(dst[1], \'sp%d_%d\' % (n, lane), sym=None, uniform=uniform)'), + 'the reload drops the provenance': (" return all(\n getattr(self, 'reload_proven', {}).get(reloads[w], False)", + " return all(\n False and getattr(self, 'reload_proven', {}).get(reloads[w], False)"), + 'every reload counts as proven': (" return all(\n getattr(self, 'reload_proven', {}).get(reloads[w], False)", + " return all(\n True or getattr(self, 'reload_proven', {}).get(reloads[w], False)"), + 'a write counts as proven wherever the descriptor came from': ( + " if sym[0] != 'desc' or not getattr(self, 'past_entry', False):\n return True\n return self.formatted", + " if True:\n return True\n return self.formatted"), + 'the reload reads the neighbouring lane': (' reach[i] = state.get((vreg, lane))', + ' reach[i] = state.get((vreg, lane ^ 1))'), + 'different symbols join into none': (" if sym is None and any(s[0] is not None and s[0][0] in self.SPILL_SYMBOLS for s in stored):", + " if False:"), + 'a modified word is carried': (" if not names_one_value(held):", " if False:"), + 'no branches in a compute stage': ("(kind not in ('ps', 'cs') or getattr(self, 'spill_reach', None) is None)):", + "(kind != 'ps' or getattr(self, 'spill_reach', None) is None)):"), + 'compute stages refused': ("SPILL_STAGES = ('ps', 'vs', 'ms', 'cs')", "SPILL_STAGES = ('ps', 'vs', 'ms')"), + 'no loop-carried refusal': (" if max(writes) > i:", " if False:"), + 'no write-before-read refusal': (" if writes is None:\n raise Unsupported('v_readlane_b32 reads v%d lane %d with no", + " if writes is None and False:\n raise Unsupported('v_readlane_b32 reads v%d lane %d with no"), +} + + +def mutated(old, new): + source = (TOOLS / 'startup' / 'gfx2hlsl.py').read_text(encoding='utf-8').replace('\r\n', '\n') + assert source.count(old) == 1, old + module = types.ModuleType('gfx2hlsl_mutant') + module.__file__ = str(TOOLS / 'startup' / 'gfx2hlsl.py') + exec(compile(source.replace(old, new), module.__file__, 'exec'), module.__dict__) + return module + + +def check_mutations(): + for label, (old, new) in MUTATIONS.items(): + try: + red = controls(mutated(old, new), quiet=True) + except Exception as error: # a mutant that crashes the translator is caught as well + red = ['crash: %s' % error] + check('mutation "%s" turns %d control(s) red: %s' % (label, len(red), red[:3]), bool(red)) + + +def check_text(): + s, p = translate('S').hlsl_cs(), translate('P').hlsl_cs() + check('the descriptor slots are declared and never assigned', [l for l in s.splitlines() if 'sp40_' in l] == + [l for l in s.splitlines() if l.lstrip().startswith('uint sp40_')], s) + check('the formatted load reads word 3 of the table descriptor', 'switch ((ud3 >> 12) & 127u)' in s) + check('the pointer slot is never assigned, the constant high word is', '= sp41_0' not in p and 's11 = sp41_1;' in p, p) + check('the pointer fixture stores through the reloaded table', p.count('u0.Store(') == 1) + + +# ---- binary and dispatch --------------------------------------------------------------------------------------------- +def check_binary(llvm_mc): + for name, source in all_sources().items(): + built = assemble_labels(llvm_mc, source) + check('llvm-mc assembles %s to the recorded words' % name, built == WORDS[name], built.hex()) + + +# control -> (case, text the translation must contain once, replacement) +CONTROLS = { + 's-arm-swapped': ('S', 'pc = (!scc) ? 2 : 1;', 'pc = (!scc) ? 1 : 2;'), + 's-store-dropped': ('S', 'u0.Store4(a, uint4(v5, v6, v7, v8));', ''), + 'p-store-dropped': ('P', 'u0.Store(a, v5);', ''), +} + + +def run_case(name, dxc, runner, adapter, directory, control=None): + hlsl = translate(name).hlsl_cs() + if control: + _, old, new = CONTROLS[control] + assert hlsl.count(old) == 1, (control, hlsl) + hlsl = hlsl.replace(old, new) + 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_ENCODING[name][2] + constants = [KEY, STRIDE] + [0] * 14 + source = b'' + if name == 'S': + constants[2:4] = [C.L_STRIDE, C.L_WORD3['L-uint']] + source = C.formatted_input() + case.write_bytes(struct.pack(' mnemonic, for branches not proven wave-uniform self.wqm_set_at = None # offset of the s_wqm exec, exec that proved whole-quad EXEC first - self.spill_slots = {} # (vgpr, lane) -> (sym, uniform) for constant-lane SGPR spills + self.spill_slots = {} # (vgpr, lane) -> (sym, uniform, proven, mask) for constant-lane SGPR spills self.vcc_events = {} self.vcc_lost = self.vcc_descriptor_overwritten = False self.entry_table_pointers = { @@ -3567,7 +3567,7 @@ def translate(self): self.uniform_expr = {} # proven VGPR -> uniform HLSL expression over scalars that defined it self.uniform_load_temps = set() # temporaries of uniform loads past the entry block (set_v) self.uniform_branches = set() # s_cbranch_* offsets proven uniform in this pass (spill-slot proof) - self.spill_writes = {} # instruction index of a v_writelane_b32 translated in this pass -> (sym, uniform) + self.spill_writes = {} # instruction index of a v_writelane_b32 translated in this pass -> (sym, uniform, proven, mask) self.heap_index = {} # SGPR -> what its word is for a resource-heap s_load (see heap_record) self.heap_index_was = {} # the marks the current instruction's destinations held before it self.since_join = None # SGPRs proven uniform since the last branch target (None: none reached) @@ -6733,9 +6733,32 @@ def formatted_pointer_copy(self, pointer, before): return None return source[1], index + def spill_word_proven(self, reg, sym): + """True when the descriptor word held in s would pass the formatted-load provenance proof here: it is + still in the entry block, or it is a word of one untouched local table load (or an already proven reload).""" + if sym[0] != 'desc' or not getattr(self, 'past_entry', False): + return True + return self.formatted_descriptor_from_block(('s', reg, reg), sym) + def formatted_descriptor_from_block(self, reg, first): - """Require one untouched local load and a table pointer that no incoming path can rewrite.""" + """Require one untouched local load and a table pointer that no incoming path can rewrite. A word written + by a v_readlane_b32 reload counts when every v_writelane_b32 that can supply it passed this same proof.""" + if not first: + return False start, end = self.descriptor_block_first, self.descriptor_instruction_index + reloads = {} + for w in range(reg[1], reg[2] + 1): + for at in range(end - 1, start - 1, -1): + _, _, name, asm = self.ins[at] + if w in self.descriptor_scalar_writes(name, parse(asm)[1]): + if re.sub(r'_e(32|64)$', '', name) == 'v_readlane_b32': + reloads[w] = at + break + if reloads: + return all( + getattr(self, 'reload_proven', {}).get(reloads[w], False) if w in reloads else + self.formatted_descriptor_from_block(('s', w, w), self.sym.get(w)) for w in range(reg[1], reg[2] + 1)) + width = reg[2] - reg[1] + 1 block = self.ins[start:end] words = set(range(reg[1], reg[2] + 1)) for index in range(len(block) - 1, -1, -1): @@ -6745,7 +6768,7 @@ def formatted_descriptor_from_block(self, reg, first): continue m = re.fullmatch(r's_load_dwordx(4|8|16)', name) load = reg_range(args[0]) - if not m or not load or load[1] + first[3] != reg[1] or int(m.group(1)) < first[3] + 4: + if not m or not load or load[1] + first[3] != reg[1] or int(m.group(1)) < first[3] + width: return False base = reg_range(args[1]) if not base or base[0] != 's': @@ -8056,8 +8079,26 @@ def op_v_readfirstlane_b32(self, ops, mods): # the write lies in such a region that the read is outside (a loop or arm the wave can run after this pixel # left it). Several writes: the value is chosen by the path, so every write must lie outside every such region; # the reload then keeps a constant only if all of them stored it, and is not claimed uniform. + # Compute stages (cs) use the same proof, branches included. A spilled descriptor or pointer word (SPILL_SYMBOLS) is a + # symbol with no run-time value: the slot carries the symbol, the reload restores it, and the word keeps the + # provenance the formatted loads require (formatted_descriptor_from_block follows a reload to the writes that supply it). + # Lane masks (compute only). The translator models a lane mask (vcc_lo, or an SGPR in self.masks) per invocation + # as that invocation's own bit: `vcc` / `sN` hold bit 0 of the wave mask, and a v_cmp stores `w` (all lanes active) + # or `exec & w`, so an inactive lane's bit is already 0 in the variable. `v_writelane_b32 vN, M, k` copies the whole + # wave mask into lane k whatever EXEC is, `v_readlane_b32 D, vN, k` copies it back to every lane, so a mask that is + # only ever used as a mask afterwards (reject_lane_mask_data and the mask rules refuse every numeric read of a marked + # register, vcc included) has, after the reload, each invocation's bit equal to its bit at the write: the spill is + # the identity on the per-invocation bit. The slot variable spN_k is therefore assigned the mask's own variable at + # the write, in every invocation, and the reload copies it into the destination and marks it a mask again (or + # assigns vcc for a `vcc_lo` destination). The slot proof of spill_join (written on every path, no loop-carried + # read, no write in a region the wave runs while the invocation skips it; writes in s_cbranch_execz blocks are + # refused by execz_refusals) decides what a reload sees. A reload that may see two writes of which one is a mask + # is refused: nothing proves they store the same mask. exec, vcc and vcc_hi (64-bit forms), and m0 stay refused + # as sources, a mask register in join_masks (mark not proven on every path) too. SPILL_LANES = 64 - SPILL_STAGES = ('ps', 'vs', 'ms') + SPILL_STAGES = ('ps', 'vs', 'ms', 'cs') + # Symbols a spill carries by identity: the SGPR holds no run-time value in the translation, so the slot holds none either. + SPILL_SYMBOLS = ('desc', 'ptr', 'ptrhi') def spill_reaching(self, cfg): """Instruction index of each v_readlane_b32 -> the v_writelane_b32 indices that can supply its (VGPR, lane), or @@ -8121,8 +8162,49 @@ def spill_join(self, n, lane): raise Unsupported('v_readlane_b32 reads v%d lane %d outside the region of the branch at %#x that writes ' 'it, which is not proven uniform' % (n, lane, off)) stored = [self.spill_writes[w] for w in sorted(writes)] - sym = stored[0][0] if all(s == stored[0][0] for s, _ in stored) else None - return sym, len(stored) == 1 and stored[0][1] + if any(s[3] for s in stored) and len(stored) > 1: + # Which mask the reload holds would depend on the path; nothing proves the writes store the same one. + raise Unsupported('v_readlane_b32 joins %d writes of v%d lane %d, one of them a lane mask' % (len(stored), n, lane)) + sym = stored[0][0] if all(s[0] == stored[0][0] for s in stored) else None + if sym is None and any(s[0] is not None and s[0][0] in self.SPILL_SYMBOLS for s in stored): + # A descriptor or pointer word has no run-time variable: only the same symbol on every path can be reloaded. + raise Unsupported('v_readlane_b32 joins different descriptor or pointer words of v%d lane %d' % (n, lane)) + return sym, len(stored) == 1 and stored[0][1], all(s[2] for s in stored), stored[0][3] + + def require_mask_reads_only(self, key): + """Refuse a reloaded lane mask (scalar state `key`: 'vcc' or 'sN') that an instruction reachable before its next + write reads as anything but a mask. The translator marks the register a mask but does not refuse every numeric + read of one, and a numeric read would see the whole wave mask where the model has one bit. Accepted reads: a lane + select or carry-in (per_lane_read), a read by s_cbranch_vccz / _vccnz, a copy into exec_lo or vcc_lo, and another + spill of it.""" + effects = [scalar_effects(name, asm) for _, _, name, asm in self.ins] + index = {off: i for i, (off, *_) in enumerate(self.ins)} + todo, seen = [self.descriptor_instruction_index + 1], set() + while todo: + j = todo.pop() + if j in seen or j >= len(self.ins): + continue + seen.add(j) + _, _, name, asm = self.ins[j] + base = re.sub(r'_e(32|64)$', '', name) + ops = parse(asm)[1] + if key in effects[j][0]: + copy = base == 's_mov_b32' and len(ops) == 2 and ops[0] in ('exec_lo', 'vcc_lo') and key in scalar_tokens(ops[1]) + if not (self.per_lane_read(j, key) or copy or base == 'v_writelane_b32' or + (key == 'vcc' and base in ('s_cbranch_vccz', 's_cbranch_vccnz'))): + raise Unsupported('v_readlane_b32 reloads a lane mask that %s reads as data' % name) + if key in effects[j][1]: + continue + target = None + if base == 's_branch' or base.startswith('s_cbranch'): + target = index.get(int(ops[0].split('_')[1], 16)) + if base not in ('s_branch', 's_endpgm'): + todo.append(j + 1) + if target is not None: + todo.append(target) + + def spills_lane_masks(self): + return getattr(self, 'kind', None) == 'cs' def spill_operands(self, name, ops, mods): if mods or len(ops) != 3: @@ -8140,12 +8222,12 @@ def spill_operands(self, name, ops, mods): if not 0 <= lane < self.SPILL_LANES: raise Unsupported('%s lane %d outside 0..%d' % (name, lane, self.SPILL_LANES - 1)) if kind not in self.SPILL_STAGES: - raise Unsupported('%s is lowered in pixel, vertex and mesh stages only' % name) + raise Unsupported('%s is lowered in pixel, vertex, mesh and compute stages only' % name) if not self.tracks_uniformity() or (getattr(self, 'has_branches', True) and - (kind != 'ps' or getattr(self, 'spill_reach', None) is None)): + (kind not in ('ps', 'cs') or getattr(self, 'spill_reach', None) is None)): raise Unsupported('%s needs straight-line code to prove write-before-read' % name) self.require_spill_only(vreg[1], name) - if kind in ('ps', 'vs'): # the wave size is unknown there; slot 57 mesh is always wave64, so k and k + 32 are two slots + if kind in ('ps', 'vs', 'cs'): # the wave size is unknown there; slot 57 mesh is always wave64, so k and k + 32 are two slots self.require_spill_lanes_apart(vreg[1], name) return vreg[1], sreg, lane @@ -8181,42 +8263,72 @@ def require_spill_only(self, n, name): def op_v_writelane_b32(self, ops, mods): n, src, lane = self.spill_operands('v_writelane_b32', ops, mods) + mask = False if src is None: # Slot 57 mesh keeps ordinary scalar spills only (R0Y00 on #2637). Raw EXEC words are not # proven under the one-lane model (exec_hi would be wrong under full EXEC; exec_lo under # a lane-0 mask would reload per thread). mesh_entry_aot still models EXEC for #2127. - if ops[1] in ('vcc', 'vcc_lo', 'vcc_hi', 'exec', 'exec_lo', 'exec_hi', 'm0'): + if ops[1] == 'vcc_lo' and self.spills_lane_masks(): + value, sym, uniform, proven, mask = 'vcc', None, False, False, True + elif ops[1] in ('vcc', 'vcc_lo', 'vcc_hi', 'exec', 'exec_lo', 'exec_hi', 'm0'): raise Unsupported('v_writelane_b32 source %s is a lane mask or m0' % ops[1]) else: - value, sym, uniform = self.u(ops[1]), None, True + value, sym, uniform, proven = self.u(ops[1]), None, True, False if re.fullmatch(r'0x[0-9a-f]{8}u', value): sym = ('const', int(value[2:-1], 16)) else: - if self.is_lane_mask(ops[1]) or (self.sym.get(src[1]) or ('',))[0] not in ('', 'const', 'ud', 'fixed_buffer_word'): + held = self.sym.get(src[1]) or ('',) + carried = held[0] in self.SPILL_SYMBOLS and getattr(self, 'kind', None) == 'cs' + mask = self.spills_lane_masks() and src[1] in self.masks + if mask: + if src[1] in self.join_masks: + raise Unsupported('v_writelane_b32 source s%d holds a lane mask not proven on every path' % src[1]) + value, sym, uniform, proven = self.S(src[1]), (held if held[0] == 'execcopy' else None), False, False + elif not carried and (self.is_lane_mask(ops[1]) or held[0] not in ('', 'const', 'ud', 'fixed_buffer_word')): raise Unsupported('v_writelane_b32 source s%d holds a lane mask or descriptor' % src[1]) - value = self.S(src[1]) - sym = self.sym.get(src[1]) if (self.sym.get(src[1]) or ('',))[0] == 'const' else None - uniform = self.uniform_source(ops[1]) + elif carried: + # A descriptor or pointer word of a compute stage: the slot holds the symbol itself, so the reload + # restores the same word. Nothing is emitted: the translation has no run-time value for it. + if not names_one_value(held): + raise Unsupported('v_writelane_b32 source s%d holds a modified descriptor or pointer word' % src[1]) + value, sym, uniform, proven = None, held, True, self.spill_word_proven(src[1], held) + else: + value = self.S(src[1]) + sym = held if held[0] == 'const' else None + uniform = self.uniform_source(ops[1]) + proven = False slots = self.__dict__.setdefault('spill_slots', {}) - slots[(n, lane)] = (sym, uniform) + slots[(n, lane)] = (sym, uniform, proven, mask) if getattr(self, 'spill_reach', None) is not None: - self.spill_writes[self.descriptor_instruction_index] = (sym, uniform) - self.emit('sp%d_%d = %s;' % (n, lane, value)) + self.spill_writes[self.descriptor_instruction_index] = (sym, uniform, proven, mask) + if value is not None: + self.emit('sp%d_%d = %s;' % (n, lane, value)) def op_v_readlane_b32(self, ops, mods): if len(ops) != 3 or reg_range(ops[1]) is None or reg_range(ops[1])[0] != 'v': raise Unsupported('v_readlane_b32 requires a VGPR source') n, dst, lane = self.spill_operands('v_readlane_b32', ops, mods) - if dst is None: - raise Unsupported('v_readlane_b32 requires an SGPR destination') if getattr(self, 'has_branches', False): - sym, uniform = self.spill_join(n, lane) + sym, uniform, proven, mask = self.spill_join(n, lane) else: slot = getattr(self, 'spill_slots', {}).get((n, lane)) if slot is None: raise Unsupported('v_readlane_b32 reads v%d lane %d before any v_writelane_b32 wrote it' % (n, lane)) - sym, uniform = slot - self.set_s(dst[1], 'sp%d_%d' % (n, lane), sym=sym, uniform=uniform) + sym, uniform, proven, mask = slot + if dst is None: + if not (mask and ops[0] == 'vcc_lo'): + raise Unsupported('v_readlane_b32 requires an SGPR destination') + self.emit('vcc = sp%d_%d;' % (n, lane)) + self.require_mask_reads_only('vcc') + return + self.set_s(dst[1], 'sp%d_%d' % (n, lane), sym=None if mask else sym, uniform=uniform) + if mask: + self.masks.add(dst[1]) + if sym is not None: + self.sym[dst[1]] = sym + self.require_mask_reads_only('s%d' % dst[1]) + if getattr(self, 'descriptor_instruction_index', None) is not None: # unit probes build a Stage without translate() + self.__dict__.setdefault('reload_proven', {})[self.descriptor_instruction_index] = proven def op_v_mov_b32(self, ops, mods): if len(ops) != 2: