Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/design.md
Original file line number Diff line number Diff line change
Expand Up @@ -368,7 +368,7 @@ How the generated SPIR-V expects the runtime to work:
| Dynamic typed-buffer stores | A seven-bit V# FORMAT selects one of the 77 existing encoders with a structured SPIR-V switch. Loads, bounds checks and stores share the element-size table. An unassigned code has size zero and leaves memory untouched. The hand-written `store_dynamic_vsharp.asm` fixture covers raw words for UINT and FLOAT, four FLOAT components, three unassigned codes and a sentinel past the destination. |
| Typed buffer formats | `Gen.FORMATS` holds all 77 GFX10 codes a V# or MTBUF can carry (a buffer's `FORMAT` is 7 bits; codes from 128 are image-only, and there are no 5_6_5, 1_5_5_5, 5_5_5_1 or 4_4_4_4 buffer formats): the 8/16-bit UINT, SINT, USCALED and SSCALED families (USCALED/SSCALED: the integer converted to float, not divided), 10_11_11 and 11_11_10 in all seven numeric formats (the FLOAT ones are unsigned floats: 5 exponent bits, bias 15, 6 or 5 mantissa bits, no sign; the first number is the top field, so 36 has x in bits 10:0 and a 10-bit z on top), and the 10_10_10_2 (44–49) and 2_10_10_10 (50–55) families. Codes outside the table decode to 0 and store nothing. **Stores**: UINT and SINT saturate; UNORM and SNORM round the exact product once (`Gen.encode_norm_bits`: 0.3 · 65535 stores 19661; nearest even, but a half rounds away from zero in a 2-bit SNORM field); a SCALED store converts as the matching NORM format; float stores (16_FLOAT and the small floats) **round toward zero, saturate to the largest finite value (65504), keep a NaN a NaN and give 0 for a negative number in an unsigned float** (`Gen.ufloat_encode_bits`); **a two-component format stored through a V# takes channel y as its second component when DST_SEL_Y is Y and DST_SEL_Z a constant (the runtime's X,Y,0,1), channel w otherwise (identity XYZW: `_xy` writes (x, 0))**, and `tbuffer_store_format_*` takes (x, y) whatever the V# says. The typed-store encode is emitted once per module (`Gen.format_encode_call`: one encode function and one element-size function, each store site a call, like the shared decode), because inlined every site carried every format. **How confirmed**: `tools/buffer_format_fuzz.py --oracle hw` runs raw `buffer_load_format_xyzw` / `buffer_store_format_xyzw` / `_xy` / `tbuffer_*_format_*` kernels and compares every result word with a CPU model (a distinct value in every register). **Radeon 880M (gfx1150, RDNA3.5; GFX11 numbers its formats differently, so formats are mapped by name)**: 1,390,400 elements over the 63 formats GFX11 has, 0 mismatches. **Real RDNA2, gfx1036, by @AwkGrep256 on the Linux DRM backend ([#2022](https://github.com/ItsNotRexed/Leonida/pull/2022))**: the same totals, 1,330,469 validated and 26,523 elements of the (x, w) routing, 0 mismatches, and 199,144 elements of the 14 codes GFX11 lacks (10_11_11 and 11_11_10 non-FLOAT, 10_10_10_2 USCALED/SSCALED), 0 mismatches. Per-format counts in [buffer_formats.md](buffer_formats.md); `--negative-control` catches a wrong V# format on all but one or two elements. The translated SPIR-V is held to the same model by `tests/semantic/test_buffer_formats_all.py` (every added format, loads through the V# and tbuffer, stores, every older format's store, hand-worked values) and by the GPU test `cs_fmt_all.asm` (32 loads and 20 stores, on an AMD Radeon 880M and an NVIDIA RTX 5070); `cs_store`, `cs_fmt_*`, `cs_oob_*` and `cs_tbuffer_store` pass on both too. Three older stores used to differ from the hardware (f16 format stores rounded to nearest and overflowed to infinity, NORM stores rounded an f32 product twice, a two-component V# store always took (x, y)) and follow it now. **Unmeasured**: the console's gfx1013, d16 forms of the new kinds and of the (x, w) routing, `_xyz` into a two-component format, selector sets that reorder channels. |
| No-op SOPP/SMEM (`s_icache_inv`, `s_ttracedata`, `s_ttracedata_imm`, `s_code_end`, `s_version`, `ds_nop`, `v_clrexcp`, `s_atc_probe`, `s_atc_probe_buffer`) | Instruction-cache invalidate, thread-trace data, end-of-code padding, the ISA version marker and the DS no-operation have no register, memory, SCC, VCC or EXEC effect, so they are in `NOOPS` with `s_nop` / `v_nop` / `v_pipeflush`. `v_clrexcp` clears the TRAPSTS exception bits, which nothing translated reads (`s_getreg_b32` is unsupported and there are no traps), so it is a no-op too (since 2026-11-22; before, both it and `ds_nop` raised `Unsupported`). `s_atc_probe` and `s_atc_probe_buffer` (SMEM) probe, that is prefetch, an address in the address translation cache: no data comes back and nothing is written, so they are no-ops too (since 2026-11-22). The data-cache invalidations (`buffer_gl0_inv`, `buffer_gl1_inv`, `s_dcache_inv`, `s_gl1_inv`) concern coherence between waves and stay `Unsupported`. Source: RDNA2 ISA SOPP/SOPK/SMEM/DS/VOP1. CPU-checked by `tests/semantic/test_sopp_noops.py` (values, SCC and VCC survive; the data-cache invalidations are still rejected). |
| No-op SOPP/SMEM (`s_icache_inv`, `s_ttracedata`, `s_ttracedata_imm`, `s_code_end`, `s_version`, `ds_nop`, `v_clrexcp`, `s_atc_probe`, `s_atc_probe_buffer`, `s_incperflevel`, `s_decperflevel`, `s_wakeup`) | Instruction-cache invalidate, thread-trace data, end-of-code padding, the ISA version marker and the DS no-operation have no register, memory, SCC, VCC or EXEC effect, so they are in `NOOPS` with `s_nop` / `v_nop` / `v_pipeflush`. `v_clrexcp` clears the TRAPSTS exception bits, which nothing translated reads (`s_getreg_b32` is unsupported and there are no traps), so it is a no-op too (since 2026-11-22; before, both it and `ds_nop` raised `Unsupported`). `s_atc_probe` and `s_atc_probe_buffer` (SMEM) probe, that is prefetch, an address in the address translation cache: no data comes back and nothing is written, so they are no-ops too (since 2026-11-22). `s_incperflevel` and `s_decperflevel` increment or decrement a performance counter (RDNA2 ISA SOPP, SIMM16[3:0]) and `s_wakeup` pings the other waves of the threadgroup out of an `s_sleep`, which is itself a no-op here; none writes a register, memory, SCC, VCC or EXEC, so they are no-ops too (since 2026-11-22). The data-cache invalidations (`buffer_gl0_inv`, `buffer_gl1_inv`, `s_dcache_inv`, `s_gl1_inv`) concern coherence between waves and stay `Unsupported`. Source: RDNA2 ISA SOPP/SOPK/SMEM/DS/VOP1. CPU-checked by `tests/semantic/test_sopp_noops.py` (values, SCC and VCC survive; the data-cache invalidations are still rejected). |
| No-op SOPP/SMEM (`s_icache_inv`, `s_ttracedata`, `s_ttracedata_imm`, `s_code_end`, `s_version`, `ds_nop`, `v_clrexcp`, `s_atc_probe`, `s_atc_probe_buffer`, `s_incperflevel`, `s_decperflevel`, `s_wakeup`) | Instruction-cache invalidate, thread-trace data, end-of-code padding, the ISA version marker and the DS no-operation have no register, memory, SCC, VCC or EXEC effect, so they are in `NOOPS` with `s_nop` / `v_nop` / `v_pipeflush`. `v_clrexcp` clears the TRAPSTS exception bits, which nothing translated reads (`s_getreg_b32` is unsupported and there are no traps), so it is a no-op too (since 2026-11-22; before, both it and `ds_nop` raised `Unsupported`). `s_atc_probe` and `s_atc_probe_buffer` (SMEM) probe, that is prefetch, an address in the address translation cache: no data comes back and nothing is written, so they are no-ops too (since 2026-11-22). `s_incperflevel` and `s_decperflevel` increment or decrement a performance counter (RDNA2 ISA SOPP, SIMM16[3:0]) and `s_wakeup` pings the other waves of the threadgroup out of an `s_sleep`, which is itself a no-op here; none writes a register, memory, SCC, VCC or EXEC, so they are no-ops too (since 2026-11-22). The data-cache invalidations (`buffer_gl0_inv`, `buffer_gl1_inv`, `s_dcache_inv`, `s_gl1_inv`) concern coherence between waves and stay `Unsupported`. Source: RDNA2 ISA SOPP/SOPK/SMEM/DS/VOP1. CPU-checked by `tests/semantic/test_sopp_noops.py` (values, SCC and VCC survive; the data-cache invalidations are still rejected). `s_sethalt` sets the wave's HALT bit to SIMM16[0] (RDNA2 ISA SOPP): 1 stops the wave until a debugger or the host clears it, which nothing does in a translated dispatch. `lower_final_halts` replaces `s_sethalt 1` immediately before `s_endpgm` with `s_endpgm` and `s_sethalt 0` with `s_nop`, retaining the original instruction PCs for branches and fall-through; `s_sethalt 1` with more code after it would hang the wave on the console and is refused (since 2026-11-25). In the 1.0.2.1 pipeline library one compute program (a 24-byte-prologue FSPX program, #583) has it, as `s_sethalt 1` right before `s_endpgm`; it was the library's last refusal. `tests/test_sethalt.py`. |
| Two-byte typed buffer load alignment | On gfx1036, MUBUF and MTBUF two-byte format loads at an odd effective byte address give zero for a fetched channel. A constant-one descriptor selector still gives one. Native wave32 and wave64 tests on AMD Radeon Graphics (Windows driver 32.0.21042.62) compared aligned and odd loads for every two-byte format (codes 7–19). Moving the base by one byte reversed which offsets returned data for 16_UINT. Regression fixture: `tests/semantic/fixtures/typed_load_alignment.asm`. |
| Buffer format store rounding and 2-component `DST_SEL` (SHADER-364) | UNORM/SNORM stores (`Gen.encode_norm_bits`) round the exact product `clamp(x) * scale` once in 64-bit integer arithmetic with ties away from zero, instead of double-rounding through `OpFMul` + `RoundEven` (`UNORM16(0.3)` stores 19661, not 19660; `SNORM2(±0.5)` stores ±1). MUBUF `buffer_store_format_*` (and `_d16_*`) into 2-component formats infer `COMP_SWAP` from V# `DST_SEL_X/Y/Z`: `use_y = (sy >= 4) and (sz < 4)`, `rev = (sx != 4) and (sy >= 4 or sz >= 4)` (`XY01` → `(x, y)`, `YX01` → `(y, x)`, `XYZW` → `(x, w)` so `_xy` writes `(x, 0)`, `YXZW`/`ZYXW` → `(w, x)`); MTBUF `tbuffer_store_format_*` ignores `DST_SEL` and always stores `(x, y)`. Measured natively on RDNA2 (`gfx1036`, AMD Ryzen 7 9800X3D iGPU, Linux AMDGPU DRM via `tools/hw_oracle`, wave32 and wave64) with `tools/buffer_store_probe.py`: 0 mismatches across 5 UNORM/SNORM formats (2,474 inputs × MUBUF/MTBUF × wave32/64 = 9,896 runs) + SNORM2 ties, all 12 2-component formats (`XY01` vs `XYZW`), and all 216 `(sx, sy, sz)` triples on `32_32_UINT`. Checked on CPU + `spirv-val` by `tests/semantic/test_buffer_store_rdna2.py` and `tests/test_buffer_store_probe.py`. |
| `_d16_hi_` typed buffer forms (SHADER-755) | Only the single-component forms are instructions. `buffer_load_format_d16_hi_x` and `buffer_store_format_d16_hi_x` are the `_x` forms of the d16 load and store with their one component in bits 31:16 instead of 15:0; #1885 (SHADER-320) adds them. The multi-component spellings (`buffer_load_format_d16_hi_xy`, `_xyz`, `_xyzw`, and `buffer_store_format_d16_hi_*`) name no RDNA instruction and stay `Unsupported`: AMD's machine-readable [RDNA1 and RDNA2 ISA XML](isa_coverage.md) lists `BUFFER_LOAD_FORMAT_D16_HI_X` and `BUFFER_STORE_FORMAT_D16_HI_X` (MUBUF opcodes 0x026 and 0x027) as the only format D16 high-half instructions, and the packed widths `BUFFER_*_FORMAT_D16_X` to `_XYZW` (0x080-0x087) have no high-half counterpart; LLVM's gfx10 to gfx12 MUBUF tables define the same two, and the console's gfx1013 decodes through the gfx10 table, so no listing can carry one (the 25,735-shader corpus has none, reported in #4084). CPU-checked by `tests/semantic/test_buffer_format_d16_hi_absent.py`: every multi-component spelling raises `Unsupported`, and the packed forms translate as a control. |
Expand Down
67 changes: 67 additions & 0 deletions tests/test_sethalt.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
"""s_sethalt in tools/rdna2spirv.py.

s_sethalt sets the wave's HALT bit to SIMM16[0] (RDNA2 ISA, SOPP). A halt right before s_endpgm ends the wave where
the s_endpgm would; s_sethalt 0 changes nothing; a halt with more code after it is refused. Hand-written listings
only: no game files, no llvm-mc, no GPU.
"""
import struct

import pytest

import rdna2spirv
from listing import EMPTY_DXBC
from semantic.test_loop_ballot_barrier import VSHARP, _translate_cs, run_compute_workgroup


def translate_cs(tmp_path, body, name="cs_sethalt"):
(tmp_path / "disasm").mkdir(exist_ok=True)
(tmp_path / f"{name}.dxbc").write_bytes(EMPTY_DXBC)
(tmp_path / "fssm").mkdir(exist_ok=True)
hdr = bytearray(0x148)
struct.pack_into("<4I", hdr, 0x138, 0x8c, 64, 1, 1) # COMPUTE_PGM_RSRC2 (4 user SGPRs, TGID_X), 64x1x1 threads
(tmp_path / "fssm" / f"{name}.fssm").write_bytes(bytes(hdr))
lines = [ln.strip() for ln in body.splitlines() if ln.strip()]
path = tmp_path / "disasm" / f"{name}.s"
path.write_text(f"; {name} code 0x0..0x100\n" + "".join("\t" + ln + "\n" for ln in lines))
return rdna2spirv.translate(str(path))


STORE = """
v_mov_b32 v0, s0
v_mov_b32 v1, s1
v_mov_b32 v2, 0x7fc00000
global_store_dword v[0:1], v2, off
"""


def test_halt_before_endpgm_keeps_the_store(tmp_path):
plain = translate_cs(tmp_path, STORE + "s_endpgm", name="cs_plain")
halted = translate_cs(tmp_path, STORE + "s_sethalt 1\ns_endpgm", name="cs_halted")
assert halted == plain.replace("cs_plain", "cs_halted")


def test_resume_is_a_no_op(tmp_path):
plain = translate_cs(tmp_path, STORE + "s_endpgm", name="cs_plain")
resumed = translate_cs(tmp_path, "s_sethalt 0\n" + STORE + "s_endpgm", name="cs_resumed")
assert resumed == plain.replace("cs_plain", "cs_resumed")


def test_halt_before_more_code_is_refused(tmp_path):
with pytest.raises(rdna2spirv.Unsupported, match="s_sethalt 1 before more code"):
translate_cs(tmp_path, "s_sethalt 1\n" + STORE + "s_endpgm")


@pytest.mark.parametrize("structured", [True, False])
@pytest.mark.parametrize("halt", [0, 1])
@pytest.mark.parametrize("target", [False, True])
def test_halt_keeps_branch_destination(structured, halt, target):
condition = "s_cbranch_scc0 stopped\ns_branch ok" if target else "s_cbranch_scc1 ok"
store = "v_lshlrev_b32_e32 v2, 2, v0\nv_mov_b32 v1, 0x5555\nbuffer_store_dword v1, v2, s[0:3], 0 offen\n"
stopped = "s_endpgm\n" if halt else store.replace("0x5555", "0x7777") + "s_endpgm\n"
program = f"s_cmp_eq_u32 s4, 0\n{condition}\nstopped:\ns_sethalt {halt}\n{stopped}ok:\n{store}s_endpgm"
asm, _ = _translate_cs("cs_halt_branch", [line for line in program.splitlines() if line], structured=structured)

def run(flag):
return run_compute_workgroup(asm, 64, 64, push_constants=[*VSHARP[:4], flag])
assert run(0) == {4 * lane: 0x5555 for lane in range(64)}
assert run(1) == ({} if halt else {4 * lane: 0x7777 for lane in range(64)})
28 changes: 28 additions & 0 deletions tools/rdna2spirv.py
Original file line number Diff line number Diff line change
Expand Up @@ -17905,6 +17905,33 @@ def fspx_wave_size(path, name):
return None if not isinstance(wave32, bool) else (32 if wave32 else 64)


def lower_final_halts(insns):
"""Lower supported s_sethalt forms in place in the instruction stream, preserving their PCs.

s_sethalt sets the wave's HALT bit to SIMM16[0] (RDNA2 ISA, SOPP): 1 stops issuing instructions until a debugger
or the host clears it, 0 lets it run. Nothing clears it in a translated dispatch, so a halt right before
s_endpgm ends the wave exactly where the s_endpgm would, after the same memory writes, and s_sethalt 0 does
nothing. A halt with more code after it would hang the wave on the console, which an invocation cannot do;
that one is refused.
"""
out = []
for k, ins in enumerate(insns):
if base_op(ins["op"]) != "s_sethalt":
out.append(ins)
continue
a = ins["args"]
value = a[0].get("v") if a and a[0].get("k") == "imm" else None
if not isinstance(value, int):
raise Unsupported("s_sethalt without an immediate")
nxt = insns[k + 1]["op"] if k + 1 < len(insns) else None
halts = value & 1
if halts and nxt != "s_endpgm":
raise Unsupported("s_sethalt 1 before more code")
# A branch can target this PC, and the PC can also be its fall-through block's leader.
out.append({**ins, "op": "s_endpgm" if halts else "s_nop", "args": [], "mods": ""})
return out


def fssm_wave_size(path, name):
"""32 or 64 from the FSSM header flags, or None when the program has no FSSM blob."""
try:
Expand Down Expand Up @@ -18025,6 +18052,7 @@ def translate(path):
raise Unsupported("reachable instruction with normalized encoding")
else:
check_printed_encodings(path, info)
insns = lower_final_halts(insns)
g = Gen(stage, hoist_reg_ptrs=True, cache_active=True)
g.vcc_scalar_pointer = any(i["op"].startswith("s_load_dword") and len(i["args"]) >= 2 and
i["args"][1].get("t") == "vcc" for i in insns)
Expand Down
Loading