mirror of
https://github.com/ProjectLeonida/mandy.git
synced 2026-12-06 09:48:38 +00:00
Merge pull request #930 from fin-github/shader/sub-co-same-operand
rdna2spirv: write out a carry-out subtract of a register from itself (AMD Windows driver crash) (SHADER-SUB-CO-SAME)
This commit is contained in:
@ -343,6 +343,7 @@ How the generated SPIR-V expects the runtime to work:
|
||||
| Mesh primitive export and allocation (`exp prim`, `MSG_GS_ALLOC_REQ`) | The GFX10 NGG formats, from Mesa 22.3 `src/amd/llvm/ac_llvm_build.c`: `ac_build_sendmsg_gs_alloc_req` (lines 4475–4477) puts `prim_cnt << 12 \| vtx_cnt` in m0, and `ac_pack_prim_export` (lines 4518–4539) packs index 0, 1 and 2 in bits 0–8, 10–18 and 20–28, the edge flags in bits 9, 19 and 29 and "null primitive (skip)" in bit 31. Thread t exports vertex t and primitive t, only below the vertex and primitive counts (`src/amd/common/ac_nir_lower_ngg.c`, `emit_ms_finale`, lines 4056–4067). Translated: the counts from m0 (each clamped to PSV0's maximum) go to `OpSetMeshOutputsEXT` or the `--mesh-compute` header; `PrimitiveTriangleIndicesEXT` takes the three 9-bit fields without the edge flags, and `CullPrimitiveEXT` (or the slot's culled word) is bit 31; invocations at or past a count write nothing. Executed for both paths in `tests/semantic/test_ms_prim_export.py` (72 threads in two wave64 waves: odd threads set the edge flags, threads with t & 2 the null bit). Open: the index fields are not clamped to the vertex count as Mesa's mesh lowering clamps them (`ac_nir_lower_ngg.c` line 4112), so a null primitive whose fields point past the count (skipped on hardware) would be undefined in SPIR-V; no corpus count of such exports exists. |
|
||||
| Geometry shaders | On output stream zero, `GS_OP_EMIT_CUT` emits the staged vertex and ends its strip under the same EXEC guard. The synthetic `gs_emit_cut.asm` checks that six vertices form two separate triangles. [RDNA 2 ISA, S_SENDMSG](https://docs.amd.com/api/khub/documents/Et~wpu9g~Ffl7d9q0QZ~Og/content). All 195 are `$GS_VoxelizeGeneric` permutations: legacy (merged ES/GS) wave32 programs on LDS rings, with no `exp`. All 195 are `$GS_VoxelizeGeneric` permutations: legacy (merged ES/GS) programs on LDS rings, with no `exp`, written for wave64 (the FSSM header's wave-size flag says wave64 in 195 of 195, see *Wave size*, and the translator's index marks all 195 `wave64` with `subgroup_size` 64 at `f847748c`; the code agrees: the EXEC prologue that `gs_tri.asm` mirrors compares the thread count with 64 and writes a 64-bit EXEC, the count in #94 finds `v_mbcnt_hi_u32_b32` in all 195, and the translator marks all 195 `wave64`; an earlier version of this row said wave32, TEST-251). Inputs: vertex i sits at the dword offset in v0 lo / v0 hi / v1 lo; an LDS read at vertex base + 4·(4·reg + comp) is input-signature register reg, component comp (checked: SV_Position xyz in dwords 0–2 and TEXCOORD0.xy in 4–5, as ISG1 declares). Outputs: emitted vertex k is dwords [k·4·nreg, (k+1)·4·nreg) of the lane's GSVS area, dword = 4·reg + comp of the output signature (20 dwords = 5 OSG1 registers; every write matches a declared mask). Translation: synthetic offsets (vertex i at dword 64·i), LDS reads → `gl_in[i]` inputs, LDS writes → staged slots, `MSG_GS EMIT` → copy slot (emit count) to the outputs + `OpEmitVertex`, `CUT` → `OpEndPrimitive`, `GS_DONE` → nothing. The prologue's `s_bfm_b64`/`s_cselect` EXEC setup is fed s3 = 64 << 8. GPU-checked with `runtime/test/shaders/gs_tri.asm` (`VKH_GS=… vk_harness`): 0 error. Without a geometry stage (Apple GPUs: Metal, MoltenVK), `tools/spirv_gs_to_compute.py` lowers the translated module to a compute capture pass, one invocation per input primitive: inputs come from a buffer, each `OpEmitVertex` guards its record/meta stores and `%gsc_n` increment on `n < OutputVertices` (dropping excess vertices rather than overflowing into the next primitive's slots, and updating `OpPhi` predecessors across split blocks, and rejecting (`Unsupported`) an `OpEmitVertex` in a loop header before its `OpLoopMerge`, which the split would move; SHADER-617, checked on the CPU by `tests/test_spirv_gs_to_compute_bounds.py`), and a meta buffer holds each primitive's vertex count (`<= OutputVertices`) and strip ends, for an ordinary draw afterwards (SHADER-159). Metal, MoltenVK), `tools/spirv_gs_to_compute.py` lowers the translated module to a compute capture pass, one invocation per input primitive: inputs come from a buffer, each `OpEmitVertex` writes the outputs to a record buffer, and a meta buffer holds each primitive's vertex count and strip ends, for an ordinary draw afterwards (SHADER-159). `gs_tri` lowered this way, converted with SPIRV-Cross and run natively on an Apple A18 Pro: 195/195 records exact for 65 random triangles, and the captured fullscreen triangle drawn from the records matches all 4096 gradient pixels. Not done: wiring it into a draw path, and GS that use cross-lane operations or more than one invocation. |
|
||||
| Integer clamp | The VOP3 `clamp` bit on `v_add_nc_u32`, `v_sub_nc_u32`, `v_subrev_nc_u32` saturates the result to [0, 0xFFFFFFFF], and on `v_add_nc_i32`/`v_sub_nc_i32` to [0x80000000, 0x7FFFFFFF]; without it they wrap. GFX9+ semantics: LLVM selects `uaddsat`/`usubsat` and `saddsat`/`ssubsat` to exactly these ops with clamp set. **Until this change clamp was silently ignored on the unsigned ops** (and the signed ones were `Unsupported`). Checked on the CPU by `tests/semantic/test_alu_add_nc_clamp.py`. The carry-out unsigned ops (`v_add_co_u32`, `v_sub_co_u32`, `v_subrev_co_u32`, `v_add_co_ci_u32`, `v_sub_co_ci_u32`, `v_subrev_co_ci_u32`) with VOP3 `clamp` likewise saturate D to `0xFFFFFFFF` on add carry or `0` on sub borrow while still reporting the real carry/borrow bit in `sdst` (**until 2026-11-22 the translator ignored `clamp` on all six**); confirmed natively on RDNA2 (AMD Radeon 680M `gfx1035` wave32 & wave64 via `tools/hw_oracle`, and independently on `gfx1036` in #1746) and CPU-checked by `tests/semantic/test_alu_add_co_clamp.py`. The 16-bit unsigned add/sub (`v_add_nc_u16`, `v_sub_nc_u16`, and the `v_add_u16`/`v_sub_u16`/`v_subrev_u16` `_e64` names) saturate to [0, 0xFFFF] with `clamp` (llvm-mc 21 gfx1030 encodes the bit on them, and LLVM selects i16 `uaddsat`/`usubsat` to them); **until 2026-11-22 the translator wrapped instead**. `clamp` on any other 16-bit integer op raises `Unsupported`. CPU-checked by `tests/semantic/test_alu_u16_clamp.py` (the high half of the destination is kept), **not GPU-verified**. CPU-checked by `tests/semantic/test_alu_u16_clamp.py` (the high half of the destination is kept), and **Hardware-verified on RDNA2** (AMD Radeon 680M, `gfx1035`, Windows 11, driver `26.5.1`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137): all 32-bit and 16-bit `*_nc_*` `clamp` cases (including `op_sel` and kept destination half on u16) match hardware bit-for-bit. **Open divergence measured on the same hardware:** `v_add_co_u32`, `v_sub_co_u32`, `v_subrev_co_u32`, `v_add_co_ci_u32`, `v_sub_co_ci_u32` and `v_subrev_co_ci_u32` with `clamp` saturate D (`0xFFFFFFFF` / `0`) while still reporting the real carry/borrow in `sdst`, whereas the translator currently ignores `clamp` on these carry-out ops. |
|
||||
| Carry-out subtract of a register from itself | `v_sub_co_u32`, `v_subrev_co_u32`, `v_sub_co_ci_u32` and `v_subrev_co_ci_u32` whose two sources are the same operand (`vD, sdst, vX, vX`) are written out as what x - x gives: D = 0 - carry in and borrow out = carry in (D = 0 and no borrow without a carry in; `clamp` saturates D to 0 on that borrow), with no `OpISubBorrow %x %x`. The values are the same as before; the form is there for AMD's Windows driver, whose compiler dies with an access violation (`0xC0000005` in `amdvlk64.dll`, at `0xafeb87` in 32.0.21037.1004 and `0xaff2d7` in 32.0.21045.29003, Radeon iGPU of a Ryzen 9 9950X3D, gfx1036) creating a native wave64 compute pipeline in which the borrow of an `OpISubBorrow` of one value with itself predicates the value operand of an `OpGroupNonUniformShuffle`. Measured by editing the translated module of a reduced `crosslane_fuzz.py` program (`v_sub_co_u32_e64 v4, s[18:19], v1, v1`, `s_and_saveexec_b64`, `ds_bpermute_b32`): `OpISubBorrow %x %x` crashes 3 of 3, also with the same id written twice, while a borrow of two different registers, `x < x`, `x != x`, `x - 0`, a literal `false` mask, the shuffle of a literal 0 and the same module without the shuffle all compile and run. The `--wave64-emulate` form of the same programs has no shuffle and never crashed. Found with `crosslane_fuzz.py --seed 880317 --wave 64 --w64-native --no-maskdata --dpp --ext --programs 400`: programs 1 and 181 were harness errors (exit 3221225477) on both drivers and match with this form (399 of 400 match, the other one differs only in a hypothesis op, as before). Checked on the CPU by `tests/semantic/test_sub_co_same_operand.py` (wave32 and native wave64 run, the emulated form by its text). **Not counted over the corpus**: whether a game shader subtracts a register from itself with a carry out is unmeasured (no package here), and other ways for that driver to see an `OpISubBorrow` of two equal values (two registers holding the same value) are not covered. |
|
||||
| Push-constant tail as a uniform block (`--pc-tail-ubo`) | For devices whose `maxPushConstantsSize` is 128, Vulkan's minimum, which can't take the 144-byte block (152 with `--mesh-compute`): AMD's older Windows drivers on RDNA2 iGPUs (Radeon 680M on 22.40.84.06, 610M on 24.10.16.14, the Ryzen 5 7600's iGPU on 24.10.24; a 610M on 26.11.2 reports 256) and some Intel Arc drivers (D3D-14, `push_constants_need_fallback` in `d3d12_vulkan_device.cpp`). The push-constant block keeps dwords 0–31 (s0–s31, 128 bytes). The tail that follows them by default, the heap base and code base and, with `--mesh-compute`, the output address, becomes `%pc_tail`: a uniform block at **set 1, binding 0** with the same members in the same order at offsets 0, 4, … (16 bytes, 24 with `--mesh-compute`). Set 1 is otherwise unused, so set 0's update-after-bind table doesn't change. The block is declared, and listed in the entry point's interface, only when the shader reads the tail (a memory access through the heap base, `s_getpc_b64`, or the `--mesh-compute` epilogue); the index then records `"pc_tail": {"set": 1, "binding": 0, "bytes": 16}`, and `"push_constant_bytes"` is 128 for every module. `"bindings"` still lists set 0 only. Without the flag nothing changes. **Checked:** `tests/test_pc_tail_ubo.py` (on `cs_store` and `ps_m15`: the block, its interface entry, `spirv-val`, the metadata, no block without a tail read, and the `--mesh-compute` address). The whole hand-written GPU test set in `runtime/test/shaders` is translated with the flag by `build.py` or `scripts/run_gpu_tests.py` under `LEONIDA_PC_TAIL_UBO=1`, and the index's `pc_tail` entries say which modules read the tail; how many do changes as shaders are added, so no count is kept here. The GPU test programs bind the block (`runtime/test/vk_pc_tail.h`; the list is in docs/testing.md), except with `--mesh-compute`, whose tests skip. The D3D12 layer does not yet: it refuses pipelines on a device with fewer than 144 push-constant bytes (`push_constants_fit` in `d3d12_vulkan_device.cpp`). |
|
||||
| `v_mad_u32_u16` / `v_mad_i32_i16` op_sel on S2 and D, and clamp | D = S0.half · S1.half + S2, the halves zero- (u16) or sign-extended (i16), op_sel bit 0 / 1 reading the high half of S0 / S1. The other bits and `clamp` were refused (`Unsupported: op_sel/clamp`) until their results were measured on RDNA2 (AMD Radeon iGPU, gfx1036, Windows driver 26.10.1, raw kernels through `tools/hw_oracle`, wave32 and wave64 alike; EGEN-HW-MAD-U32-U16, 44 words): **op_sel bit 2 adds S2[31:16] zero-extended, in the i16 op too** (`v_mad_i32_i16 d, 3, 3, 0xffff8000 op_sel:[0,0,1,0]` gives `0x00010008`, not 8); an inline float constant there is its f32 pattern (`1.0` adds `0x3f80`); **op_sel bit 3 writes the result shifted left by 16** (low half 0, the old D not kept); **`clamp` saturates the 32-bit sum** to [0, 0xffffffff] (u16) or [0x80000000, 0x7fffffff] (i16), before that shift (the 16-bit product itself never overflows). GPU-checked with `runtime/test/shaders/ps_valu16_mad_sel.asm` (4096/4096 on NVIDIA GeForce RTX 5080, driver 616.92, and the gfx1036 iGPU); CPU-checked by `tests/semantic/test_alu_mad_32_16.py` (40 seeded cases against a Python reference) and `tests/semantic/test_value_semantics.py`. |
|
||||
| `v_add_nc_i16`, `v_sub_nc_i16` | GFX10 VOP3-only signed 16-bit add and subtract. Without `clamp` they are bit-identical to `v_add_nc_u16`/`v_sub_nc_u16` (the low 16 bits wrap) and take the same path: `op_sel:[s0,s1,dst]` picks each source's half and the destination half, and the other half of D is kept. With `clamp`, the exact sum or difference of the sign-extended halves saturates to [-32768, 32767] (`SClamp`), where the u16 forms saturate to [0, 0xFFFF]. RDNA2 (GFX10.3) dropped reversed 16-bit integer subtraction (`v_subrev_nc_u16` / `v_subrev_nc_i16` do not exist on hardware; `v_subrev_f16` is the only 16-bit reverse subtract opcode). Checked by `tests/semantic/test_valu_add_sub_nc_i16.py` (a value grid with and without `clamp`, `op_sel`, literals, SGPR sources, and untouched half preservation) and **Hardware-verified on AMD RDNA2** (`gfx1036`, wave32 and wave64 via `tools/int_hw_probe.py`, `valu_add_nc_clamp/v_add_sub_nc_i16_clamp`): signed saturation to [-32768, 32767], `op_sel` source selection, and untouched destination half preservation match hardware bit-for-bit. Until 2026-11-22 both raised `Unsupported`. CPU-checked by `tests/semantic/test_valu_add_sub_nc_i16.py` (a value grid with and without `clamp`, `op_sel` including the destination half, and equality with the u16 forms without `clamp`). **GPU-verified** on native RDNA2 (gfx1036, the Radeon iGPU of a Ryzen 7 9800X3D, Windows driver 32.0.21042.62) through `tools/hw_oracle`, one-thread raw kernels: 112 of 112 directed cases (both ops; 0x7FFF+1, 0x8000+1, 0x8000+0xFFFF, 0x7FFF+0x7FFF, 0x8000+0x8000 and others, each with and without `clamp` and with `op_sel` `[0,0,0]`, `[1,0,1]`, `[0,1,0]` and `[1,1,1]`, the destination preset to 0xA5A5A5A5). For example `v_add_nc_i16(0x7FFF, 1)` gives 0x8000 wrapped and 0x7FFF with `clamp`, `v_sub_nc_i16(0x8000, 1) clamp` gives 0x8000, and the destination half `op_sel` doesn't pick keeps its 0xA5A5. `tools/pk16_diff.py --oracle translator,hw --ops v_add_nc_i16,v_sub_nc_i16 --programs 3000 --seed 1`: 3000 of 3000 programs agree with the hardware and the translator. **Not GPU-verified.** Measured on native gfx1100: `clamp` saturates the exact sign-extended sum to [-32768, 32767] and the other half of D is kept. |
|
||||
|
||||
194
tests/semantic/test_sub_co_same_operand.py
Normal file
194
tests/semantic/test_sub_co_same_operand.py
Normal file
@ -0,0 +1,194 @@
|
||||
"""Carry-out subtracts of a register from itself: v_sub_co_u32 / v_subrev_co_u32 (and the _ci_ forms) vD, sdst, vX, vX.
|
||||
|
||||
x - x is 0 with no borrow, so D = 0 - carry in and the borrow out is the carry in. The translator writes that out
|
||||
instead of OpISubBorrow %x %x: AMD's Windows driver (amdvlk64.dll 32.0.21037.1004 and 32.0.21045.29003, gfx1036)
|
||||
dies with an access violation creating a native wave64 compute pipeline in which the borrow of such an
|
||||
OpISubBorrow predicates the value of a subgroup shuffle (crosslane_fuzz.py --seed 880317 --wave 64 --w64-native
|
||||
--no-maskdata --dpp --ext, programs 1 and 181; docs/design.md, "Carry-out subtract of a register from itself").
|
||||
|
||||
Checked here, in wave32 and native wave64 (run in spirv_mini_interp):
|
||||
- D and the borrow mask for every lane, with and without a carry in, under a partial EXEC (an inactive lane keeps
|
||||
D and reads 0 in the mask), and the wave-wide count of the mask;
|
||||
- the clamp bit (D saturates to 0 on a borrow, the borrow is still reported);
|
||||
- no OpISubBorrow is emitted for the same-operand forms, and two different registers holding equal values still
|
||||
go through OpISubBorrow and give the same answers.
|
||||
With --wave64-emulate only the emitted form is checked (the last point).
|
||||
"""
|
||||
import gc
|
||||
import os
|
||||
import re
|
||||
import struct
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
import warnings
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
ROOT = os.path.dirname(os.path.dirname(HERE))
|
||||
TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")
|
||||
|
||||
sys.dont_write_bytecode = True
|
||||
if HERE not in sys.path:
|
||||
sys.path.insert(0, HERE)
|
||||
if TOOLS_DIR not in sys.path:
|
||||
sys.path.insert(0, TOOLS_DIR)
|
||||
|
||||
import rdna2spirv # noqa: E402
|
||||
import spirv_mini_interp as si # noqa: E402
|
||||
|
||||
STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4)
|
||||
VSHARP = [0, 0, 0xFFFFFFFF, 0x31016FAC] # OOB_SELECT 3 (raw): stores are in range up to num_records
|
||||
SENTINEL = 0xDEADBEEF
|
||||
|
||||
# (op, has carry in, reversed operands)
|
||||
OPS = [
|
||||
("v_sub_co_u32", False),
|
||||
("v_subrev_co_u32", False),
|
||||
("v_sub_co_ci_u32", True),
|
||||
("v_subrev_co_ci_u32", True),
|
||||
]
|
||||
|
||||
|
||||
def _translate_and_run(name, body_lines, wave_size, emulate):
|
||||
"""(SPIR-V assembly text, the output buffer after one workgroup of wave_size lanes). With emulate the module
|
||||
is only translated (the buffer is None): spirv_mini_interp does not run the --wave64-emulate round loop, as in
|
||||
test_carry_exec_mask.py; crosslane_fuzz.py runs the emulated form on a GPU."""
|
||||
prev_emu = rdna2spirv.WAVE64_EMULATE
|
||||
try:
|
||||
rdna2spirv.WAVE64_EMULATE = emulate
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
os.mkdir(os.path.join(tmp, "disasm"))
|
||||
os.mkdir(os.path.join(tmp, "fssm"))
|
||||
s_path = os.path.join(tmp, "disasm", name + ".s")
|
||||
with open(s_path, "w", encoding="utf-8", newline="\n") as f:
|
||||
f.write(f"; {name}\n")
|
||||
for ln in body_lines:
|
||||
f.write(f"\t{ln}\n")
|
||||
f.write("\ts_endpgm\n")
|
||||
with open(os.path.join(tmp, name + ".dxbc"), "wb") as f:
|
||||
f.write(STUB_DXBC)
|
||||
# COMPUTE_PGM_RSRC2 0x8088: 4 user SGPRs (s[0:3] = the output V#), TGID_X.
|
||||
with open(os.path.join(tmp, "fssm", name + ".fssm"), "wb") as f:
|
||||
f.write(bytes(0x138) + struct.pack("<4I", 0x8088, wave_size, 1, 1))
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("ignore", ResourceWarning)
|
||||
spv = rdna2spirv.translate(s_path)
|
||||
gc.collect()
|
||||
assert rdna2spirv.translate.last_gen.wave64 == (wave_size == 64), name
|
||||
finally:
|
||||
rdna2spirv.WAVE64_EMULATE = prev_emu
|
||||
if emulate:
|
||||
return spv, None
|
||||
sg_size = wave_size
|
||||
mem = si.run_workgroup(
|
||||
spv, wave_size, sg_size,
|
||||
inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i % sg_size},
|
||||
push_constants=VSHARP + [0] * 28, memory={},
|
||||
)
|
||||
return spv, mem
|
||||
|
||||
|
||||
class _SameOperandMixin:
|
||||
wave_size = 64
|
||||
emulate = False
|
||||
|
||||
def _names(self):
|
||||
if self.wave_size == 64:
|
||||
return {"exec": "exec", "mov": "s_mov_b64", "or": "s_or_b64", "bcnt": "s_bcnt1_i32_b64",
|
||||
"act": "s[4:5]", "tmp": "s[6:7]", "sdst": "s[10:11]", "cin": "s[12:13]", "active": [2, 5, 35, 40]}
|
||||
return {"exec": "exec_lo", "mov": "s_mov_b32", "or": "s_or_b32", "bcnt": "s_bcnt1_i32_b32",
|
||||
"act": "s4", "tmp": "s6", "sdst": "s10", "cin": "s12", "active": [2, 5, 19, 24]}
|
||||
|
||||
def _program(self, op, with_ci, src_a, src_b, clamp=False):
|
||||
"""The op under a partial EXEC, with lane-varying sources (v2 = v3 = 3 * lane + 7) and, for the _ci_ forms,
|
||||
a carry in on the odd lanes. Stores per lane: D, the lane's bit of the borrow mask, and the mask's count."""
|
||||
n = self._names()
|
||||
lines = [f"{n['mov']} {n['exec']}, -1"]
|
||||
lines.append(f"v_cmp_eq_u32_e64 {n['act']}, v0, {n['active'][0]}")
|
||||
for lane in n["active"][1:]:
|
||||
lines.append(f"v_cmp_eq_u32_e64 {n['tmp']}, v0, {lane}")
|
||||
lines.append(f"{n['or']} {n['act']}, {n['act']}, {n['tmp']}")
|
||||
lines += [
|
||||
"v_mul_lo_u32 v2, v0, 3",
|
||||
"v_add_nc_u32 v2, 7, v2",
|
||||
"v_mov_b32 v3, v2",
|
||||
f"v_mov_b32 v6, {SENTINEL:#x}",
|
||||
f"{n['mov']} {n['sdst']}, -1", # stale bits must be overwritten, also on inactive lanes
|
||||
]
|
||||
if with_ci:
|
||||
lines += ["v_and_b32 v7, 1, v0", f"v_cmp_ne_u32_e64 {n['cin']}, 0, v7"]
|
||||
inst = f"{op}_e64 v6, {n['sdst']}, {src_a}, {src_b}" + (f", {n['cin']}" if with_ci else "")
|
||||
if clamp:
|
||||
inst += " clamp"
|
||||
lines += [
|
||||
f"{n['mov']} {n['exec']}, {n['act']}",
|
||||
inst,
|
||||
f"{n['mov']} {n['exec']}, -1",
|
||||
f"{n['bcnt']} s14, {n['sdst']}",
|
||||
f"v_cndmask_b32_e64 v9, 0, 1, {n['sdst']}",
|
||||
"v_mov_b32 v10, s14",
|
||||
"v_mul_lo_u32 v11, v0, 12",
|
||||
"buffer_store_dword v6, v11, s[0:3], 0 offen",
|
||||
"v_add_nc_u32 v12, 4, v11",
|
||||
"buffer_store_dword v9, v12, s[0:3], 0 offen",
|
||||
"v_add_nc_u32 v12, 8, v11",
|
||||
"buffer_store_dword v10, v12, s[0:3], 0 offen",
|
||||
]
|
||||
return lines
|
||||
|
||||
def _check(self, mem, with_ci, clamp, what):
|
||||
if mem is None: # --wave64-emulate: translated only
|
||||
return
|
||||
active = set(self._names()["active"])
|
||||
borrowing = {lane for lane in active if with_ci and lane & 1}
|
||||
for lane in range(self.wave_size):
|
||||
d, bit, count = mem[lane * 12], mem[lane * 12 + 4], mem[lane * 12 + 8]
|
||||
self.assertEqual(count, len(borrowing), f"{what}: lane {lane} mask count")
|
||||
if lane not in active:
|
||||
self.assertEqual(d, SENTINEL, f"{what}: inactive lane {lane} D")
|
||||
self.assertEqual(bit, 0, f"{what}: inactive lane {lane} borrow bit")
|
||||
elif lane in borrowing:
|
||||
self.assertEqual(d, 0 if clamp else 0xFFFFFFFF, f"{what}: lane {lane} D with a carry in")
|
||||
self.assertEqual(bit, 1, f"{what}: lane {lane} borrow bit")
|
||||
else:
|
||||
self.assertEqual(d, 0, f"{what}: lane {lane} D")
|
||||
self.assertEqual(bit, 0, f"{what}: lane {lane} borrow bit")
|
||||
|
||||
def test_same_register_values_and_borrow(self):
|
||||
for op, with_ci in OPS:
|
||||
for clamp in (False, True):
|
||||
with self.subTest(op=op, clamp=clamp, wave=self.wave_size, emulate=self.emulate):
|
||||
name = f"cs_{op}_same{'_clamp' if clamp else ''}_w{self.wave_size}"
|
||||
spv, mem = _translate_and_run(name, self._program(op, with_ci, "v2", "v2", clamp),
|
||||
self.wave_size, self.emulate)
|
||||
self.assertNotIn("OpISubBorrow", spv, f"{op}: x - x is written out, not left to OpISubBorrow")
|
||||
self._check(mem, with_ci, clamp, f"{op} v2, v2")
|
||||
|
||||
def test_equal_values_in_two_registers_still_use_the_borrow_op(self):
|
||||
"""The same answers when the two sources are different registers that happen to hold equal values: that
|
||||
path is not changed, so it still goes through OpISubBorrow (and never with one id twice)."""
|
||||
for op, with_ci in OPS:
|
||||
with self.subTest(op=op, wave=self.wave_size, emulate=self.emulate):
|
||||
spv, mem = _translate_and_run(f"cs_{op}_two_w{self.wave_size}",
|
||||
self._program(op, with_ci, "v2", "v3"), self.wave_size, self.emulate)
|
||||
borrows = re.findall(r"OpISubBorrow %umul (\S+) (\S+)", spv)
|
||||
self.assertTrue(borrows, f"{op}: two registers still use OpISubBorrow")
|
||||
self.assertFalse([b for b in borrows if b[0] == b[1]], f"{op}: OpISubBorrow of one id with itself")
|
||||
self._check(mem, with_ci, False, f"{op} v2, v3")
|
||||
|
||||
|
||||
class SameOperandWave32(_SameOperandMixin, unittest.TestCase):
|
||||
wave_size = 32
|
||||
|
||||
|
||||
class SameOperandWave64Native(_SameOperandMixin, unittest.TestCase):
|
||||
wave_size = 64
|
||||
|
||||
|
||||
class SameOperandWave64Emulate(_SameOperandMixin, unittest.TestCase):
|
||||
wave_size = 64
|
||||
emulate = True
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@ -9933,18 +9933,28 @@ class Gen:
|
||||
self.emit(f"{cin} = OpSelect %uint {self.tmp_bool_nz(cin_m)} {self.cu(1)} {self.cu(0)}")
|
||||
else:
|
||||
cin = self.cu(0)
|
||||
s1, c1, s2, c2, r, carry = (self.tmp() for _ in range(6))
|
||||
if sub:
|
||||
self.emit(f"{s1} = OpISubBorrow %umul {x} {y}")
|
||||
if sub and srcs[0] == srcs[1]:
|
||||
# x - x: the difference is 0 and there is no borrow, so D = 0 - carry in and the borrow out is the
|
||||
# carry in. Written out instead of OpISubBorrow %x %x: AMD's Windows driver (amdvlk64.dll,
|
||||
# 32.0.21037.1004 and 32.0.21045.29003, gfx1036) dies with an access violation creating a native
|
||||
# wave64 compute pipeline in which that borrow predicates a subgroup shuffle's value
|
||||
# (docs/design.md, "Carry-out subtract of a register from itself").
|
||||
r = self.tmp()
|
||||
self.emit(f"{r} = OpISub %uint {self.cu(0)} {cin}")
|
||||
carry = cin
|
||||
else:
|
||||
self.emit(f"{s1} = OpIAddCarry %umul {x} {y}")
|
||||
r1 = self.tmp()
|
||||
self.emit(f"{r1} = OpCompositeExtract %uint {s1} 0")
|
||||
self.emit(f"{c1} = OpCompositeExtract %uint {s1} 1")
|
||||
self.emit(f"{s2} = {'OpISubBorrow' if sub else 'OpIAddCarry'} %umul {r1} {cin}")
|
||||
self.emit(f"{r} = OpCompositeExtract %uint {s2} 0")
|
||||
self.emit(f"{c2} = OpCompositeExtract %uint {s2} 1")
|
||||
self.emit(f"{carry} = OpBitwiseOr %uint {c1} {c2}")
|
||||
s1, c1, s2, c2, r, carry = (self.tmp() for _ in range(6))
|
||||
if sub:
|
||||
self.emit(f"{s1} = OpISubBorrow %umul {x} {y}")
|
||||
else:
|
||||
self.emit(f"{s1} = OpIAddCarry %umul {x} {y}")
|
||||
r1 = self.tmp()
|
||||
self.emit(f"{r1} = OpCompositeExtract %uint {s1} 0")
|
||||
self.emit(f"{c1} = OpCompositeExtract %uint {s1} 1")
|
||||
self.emit(f"{s2} = {'OpISubBorrow' if sub else 'OpIAddCarry'} %umul {r1} {cin}")
|
||||
self.emit(f"{r} = OpCompositeExtract %uint {s2} 0")
|
||||
self.emit(f"{c2} = OpCompositeExtract %uint {s2} 1")
|
||||
self.emit(f"{carry} = OpBitwiseOr %uint {c1} {c2}")
|
||||
carry_nz = self.tmp_bool_nz(carry)
|
||||
if "clamp" in mods:
|
||||
# Hardware saturates D (0xffffffff on add carry, 0 on sub borrow) while reporting the real carry/borrow.
|
||||
|
||||
Reference in New Issue
Block a user