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
1 change: 1 addition & 0 deletions .github/workflows/windows.yml
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,7 @@ jobs:
tests/startup_gfx2hlsl_sop2_complement_check.py \
tests/startup_gfx2hlsl_f32_lg_check.py \
tests/startup_gfx2hlsl_f32_nan_check.py \
tests/startup_gfx2hlsl_sopk_signext_check.py \
tests/startup_inline_sampler_check.py \
tests/startup_buffer_address_check.py \
tests/startup_smem_address_check.py \
Expand Down
1 change: 1 addition & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,7 @@ python3 -m venv out/pe-env
./out/pe-env/bin/python -B tests/startup_gfx2hlsl_vopc_sdwa_check.py
./out/pe-env/bin/python -B tests/startup_gfx2hlsl_f32_lg_check.py
./out/pe-env/bin/python -B tests/startup_gfx2hlsl_f32_nan_check.py
./out/pe-env/bin/python -B tests/startup_gfx2hlsl_sopk_signext_check.py
./out/pe-env/bin/python -B tests/run_checks_parallel_check.py
./out/pe-env/bin/python -B tests/startup_gfx2hlsl_handler_arity_check.py
```
Expand Down
3 changes: 3 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2255,6 +2255,9 @@ if(EXISTS "${INTAKE_PYTHON}")
# The scalar shift-and-add forms s_lshl1..4_add_u32 (Run 20 census #16).
add_test(NAME startup_gfx2hlsl_s_lshl_add COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_lshl_add_check.py")
# SOPK 16-bit immediates: s_movk_i32 and s_cmpk_*_i32 sign-extend, s_cmpk_*_u32 zero-extend.
add_test(NAME startup_gfx2hlsl_sopk_signext COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_sopk_signext_check.py")
# SDWA forms of the float-result conversions (#1727).
add_test(NAME startup_gfx2hlsl_sdwa_cvt COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_sdwa_cvt_check.py")
Expand Down
6 changes: 6 additions & 0 deletions docs/experiments.md
Original file line number Diff line number Diff line change
Expand Up @@ -6439,6 +6439,12 @@ symbolic descriptors and reserved scalar encodings stay refused. [Refs #1996](ht
one. Only the low five bits of the index are used. EXEC, VCC and SGPRs tracked
as lane masks are refused because their per-lane projections lose the other
bits. Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_s_bitcmp$' -V`.

**Scalar immediate comparisons.** The startup translator sign-extends the
16-bit field of `s_movk_i32` and `s_cmpk_*_i32`, and zero-extends the field
of `s_cmpk_*_u32`. The source-built check covers all six relations against
both signed and unsigned references and rejects values outside the encoded
range. Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_sopk_signext$' -V`.
The fixture evaluates the emitted expression on the CPU and checks both
operand positions for mask refusal. It does not execute a GPU draw.

Expand Down
108 changes: 108 additions & 0 deletions tests/startup_gfx2hlsl_sopk_signext_check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
"""SOPK 16-bit immediates in tools/startup/gfx2hlsl.py: s_movk_i32, s_cmpk_*_i32 and s_cmpk_*_u32.

usage: startup_gfx2hlsl_sopk_signext_check.py

RDNA 2 ISA, SOPK: S_MOVK_I32 is D.i32 = signext(SIMM16[15:0]); S_CMPK_{EQ,LG,GT,GE,LT,LE}_I32 compare S0.i32 with
signext(SIMM16[15:0]); the _U32 forms compare S0.u32 with SIMM16[15:0] zero-extended. LLVM 15 SOPInstructions.td agrees:
the _I32 forms take s16imm (isSignExt = 1), the _U32 forms u16imm (isSignExt = 0), and s_movk_i32 takes s16imm. The
disassembler prints the field as unsigned hex (0x8000, 0xffff). s_cmovk_i32 has no lowering and must stay refused.
The reference is plain Python arithmetic; the emitted text is evaluated on the CPU.
"""
import operator
import re
import sys
from pathlib import Path

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE.parent / 'tools' / 'startup'))
sys.path.insert(0, str(HERE.parent / 'tools'))
import gfx2hlsl as G # noqa: E402

failures = []


class Probe(G.Stage):
"""A Stage with no pipeline: enough state for single instructions to be translated."""

def __init__(self):
self.lines, self.sym = [], {}
self.used_s, self.used_v, self.uniform_v = set(), set(), set()
self.exec_known = True
self.masks = set()


def signed32(value):
value &= 0xffffffff
return value - (1 << 32) if value & 0x80000000 else value


def run(program, regs):
"""Translate each line, then evaluate the emitted assignments over regs; returns the final registers."""
stage = Probe()
for line in program:
stage.one(line.split(' ', 1)[0], line)
env = dict(regs)
for text in stage.lines:
target, _, expression = text.rstrip(';').partition(' = ')
expression = re.sub(r'\b(0x[0-9a-f]+|\d+)u\b', r'\1', expression)
env[target] = int(eval(expression, {'int': signed32, 'uint': lambda x: x & 0xffffffff}, env)) & 0xffffffff
return env


def check(label, got, want):
if got != want:
failures.append(label)
print('MISMATCH %s got=%r want=%r' % (label, got, want))


def signext16(word):
return ((word & 0xffff) ^ 0x8000) - 0x8000


IMMEDIATES = (0x0, 0x1, 0x7ffe, 0x7fff, 0x8000, 0x8001, 0xfffe, 0xffff)

# s_movk_i32: constant-tracking path (s0) and run-time path (m0), seen through a consumer comparison.
for imm in IMMEDIATES:
want = signext16(imm) & 0xffffffff
for dest in ('s0', 'm0'):
env = run(['s_movk_i32 %s, 0x%x' % (dest, imm)], {})
check('s_movk_i32 %s, %#x' % (dest, imm), env.get(dest), want)
for expected, label in ((want, 'equal'), (imm, 'zero-extended')):
env = run(['s_movk_i32 %s, 0x%x' % (dest, imm), 's_cmp_eq_u32 s3, %s' % dest], {'s3': expected})
check('s_movk_i32 %s, %#x consumer vs %s' % (dest, imm, label),
bool(env['scc']), expected == want)
# a negative decimal spelling is the same field
check('s_movk_i32 -1', run(['s_movk_i32 s0, -1'], {}).get('s0'), 0xffffffff)
check('s_movk_i32 -32768', run(['s_movk_i32 s0, -32768'], {}).get('s0'), 0xffff8000)

COMPARE = {'eq': operator.eq, 'lg': operator.ne, 'gt': operator.gt, 'ge': operator.ge, 'lt': operator.lt, 'le': operator.le}
WORDS = (0x0, 0x1, 0x7fff, 0x8000, 0xffff, 0x10000, 0x7fffffff, 0x80000000, 0xffff7fff, 0xffff8000, 0xffff8001, 0xffffffff)
cases = 0
for name, relation in COMPARE.items():
for imm in IMMEDIATES:
for word in WORDS:
for kind, rhs, lhs in (('i32', signext16(imm), signed32(word)), ('u32', imm, word)):
line = 's_cmpk_%s_%s s5, 0x%x' % (name, kind, imm)
check('%s s5=%#x' % (line, word), bool(run([line], {'s5': word})['scc']), relation(lhs, rhs))
cases += 1
# the issue case: 0 < -1 is false
check('s_cmpk_lt_i32 s0=0, 0xffff', bool(run(['s_cmpk_lt_i32 s5, 0xffff'], {'s5': 0})['scc']), False)
check('s_cmpk_lt_i32 s0=0, -1', bool(run(['s_cmpk_lt_i32 s5, -1'], {'s5': 0})['scc']), False)

# negative controls: the translator must refuse what the encoding cannot hold, and what has no lowering
refused = 0
for program in (['s_movk_i32'], ['s_movk_i32 s0, 0x10000'], ['s_movk_i32 s0, -0x8001'], ['s_movk_i32 s0, -32769'], ['s_movk_i32 s0, s1'],
['s_cmpk_lt_i32 s5, 0x10000'], ['s_cmpk_lt_i32 s5, -32769'], ['s_cmpk_lt_i32 s5, s6'],
['s_cmpk_lt_u32 s5, 0x10000'], ['s_cmpk_lt_u32 s5, -1'],
['s_cmovk_i32 s0, 0xffff']):
try:
run(program, {'s5': 0, 's1': 0, 's6': 0})
except G.Unsupported:
refused += 1
else:
failures.append(program[0])
print('ACCEPTED %s' % program[0])

print('sopk_signext: %s' % ('ok (%d compare cases, 2 movk paths x %d immediates, %d refusals)' % (cases, len(IMMEDIATES), refused)
if not failures else '%d mismatches' % len(failures)))
sys.exit(1 if failures else 0)
33 changes: 32 additions & 1 deletion tools/startup/gfx2hlsl.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,24 @@ class Unsupported(Exception):
'WORD_0': (0, 16), 'WORD_1': (16, 16), 'DWORD': (0, 32)}


def sopk_imm(token, signed):
"""The 32-bit word a SOPK 16-bit immediate stands for.

RDNA 2 ISA SOPK: s_movk_i32 and the s_cmpk_*_i32 forms use signext(SIMM16[15:0]) (LLVM s16imm); the s_cmpk_*_u32
forms use SIMM16[15:0] zero-extended (LLVM u16imm). The disassembler prints the field as unsigned hex."""
m = re.fullmatch(r'(-?)(?:0x([0-9a-f]+)|(\d+))', token)
if not m:
raise Unsupported('SOPK immediate %r' % token)
word = int(m.group(2), 16) if m.group(2) else int(m.group(3))
if m.group(1):
word = -word
if not (-0x8000 if signed else 0) <= word <= 0xffff:
raise Unsupported('SOPK immediate %r outside 16 bits' % token)
if signed:
word = ((word & 0xffff) ^ 0x8000) - 0x8000
return word & 0xffffffff


def sdwa_source(word, sel, sext):
"""The uint expression a source selection reads out of a 32-bit register."""
offset, width = SDWA_SEL[sel]
Expand Down Expand Up @@ -776,6 +794,8 @@ def sdwa(self, base, ops, mods):

# scalar ALU with descriptor-word bookkeeping
def scalar(self, base, ops):
if base == 's_movk_i32' and len(ops) != 2:
raise Unsupported('s_movk_i32 with %d operands, expected 2' % len(ops))
text, scc = SCA[base]
if base in SCC_UNMODELLED and self.tracks_uniformity():
self.scc_uniform = False
Expand All @@ -788,6 +808,8 @@ def low(tok):
return ('s%d' % r[1]) if r and r[0] == 's' and r[1] != r[2] else tok
srcs = [low(t) for t in srcs]
dname = low(ops[0])
if base == 's_movk_i32':
srcs = [str(sopk_imm(srcs[0], True))] # D.i32 = signext(SIMM16)
shift_add = base in SHIFT_ADD
word_complement = base in ('s_nand_b32', 's_nor_b32', 's_xnor_b32')
word_pack = base == 's_pack_hh_b32_b16'
Expand Down Expand Up @@ -1995,7 +2017,16 @@ def handler(self, ops, mods):
self.set_scc((cast % op).format(self.u(ops[0]), self.u(ops[1])))
return handler
setattr(Stage, 'op_s_cmp_%s_%s' % (_name, _typ), _make())
setattr(Stage, 'op_s_cmpk_%s_%s' % (_name, _typ), _make())
for _typ, _cast in (('i32', 'int({0}) %s int({1})'), ('u32', '{0} %s {1}')):
def _make_cmpk(op=_op, cast=_cast, signed=_typ == 'i32', name='s_cmpk_%s_%s' % (_name, _typ)):
def handler(self, ops, mods):
if len(ops) != 2:
raise Unsupported('%s with %d operands, expected 2' % (name, len(ops)))
if mods:
raise Unsupported('%s with modifiers' % name)
self.set_scc((cast % op).format(self.u(ops[0]), '0x%08xu' % sopk_imm(ops[1], signed)))
return handler
setattr(Stage, 'op_s_cmpk_%s_%s' % (_name, _typ), _make_cmpk())
# s_bitcmp1_b32 / s_bitcmp0_b32: SCC = S0[S1[4:0]] == 1 / == 0.
for _bit in (0, 1):
def _make_bitcmp(bit=_bit):
Expand Down
Loading