From 8e0ef1488c8ea151fe24d84f8d357dc8353a646f Mon Sep 17 00:00:00 2001 From: JB2WIN Date: Wed, 25 Nov 2026 01:45:09 +0100 Subject: [PATCH 1/2] startup: sign-extend the SOPK i32 immediates in gfx2hlsl gfx2hlsl decoded the 16-bit SOPK immediate with int(token, 0) and no sign extension. s_movk_i32 s0, 0x8000 produced 0x00008000 instead of 0xffff8000, and s_cmpk_*_i32 compared against the zero-extended field, so s_cmpk_lt_i32 s0, 0xffff with s0 = 0 set SCC (0 < 65535) where the hardware compares against -1 and clears it. Semantics: RDNA 2 ISA SOPK, S_MOVK_I32 and S_CMPK_*_I32 use signext(SIMM16[15:0]); S_CMPK_*_U32 use SIMM16[15:0] zero-extended. LLVM 15 SOPInstructions.td agrees: the _I32 forms and s_movk_i32 take s16imm (isSignExt = 1), the _U32 forms take u16imm (isSignExt = 0). The _U32 forms were already correct and stay zero-extended. One helper, sopk_imm(), now decodes the field for s_movk_i32 (constant and run-time paths) and for both s_cmpk families, and refuses values outside 16 bits and non-literal operands, as pixel_aot already does. s_cmovk_i32 has no lowering here and is still refused. The new check evaluates the emitted text against a Python reference (1152 compare cases, both movk paths, 10 refusals). It fails on main (130 mismatches) and passes with this change; removing the sign extension or applying it to the _U32 forms turns it red again. AI-assisted (Claude Code). Co-Authored-By: Claude Opus 5.5 --- .github/workflows/windows.yml | 1 + AGENTS.md | 1 + CMakeLists.txt | 3 + tests/startup_gfx2hlsl_sopk_signext_check.py | 108 +++++++++++++++++++ tools/startup/gfx2hlsl.py | 31 +++++- 5 files changed, 143 insertions(+), 1 deletion(-) create mode 100644 tests/startup_gfx2hlsl_sopk_signext_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 211fb504f1..1863e417fc 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -222,6 +222,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 \ diff --git a/AGENTS.md b/AGENTS.md index 07b8089849..c1f02ffc16 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -182,6 +182,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 ``` diff --git a/CMakeLists.txt b/CMakeLists.txt index 8149ad8ed1..77ea13d460 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2235,6 +2235,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") diff --git a/tests/startup_gfx2hlsl_sopk_signext_check.py b/tests/startup_gfx2hlsl_sopk_signext_check.py new file mode 100644 index 0000000000..43a93d441a --- /dev/null +++ b/tests/startup_gfx2hlsl_sopk_signext_check.py @@ -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 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) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 6491fa63bd..5223ac5595 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -29,6 +29,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] @@ -783,6 +801,10 @@ 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': + if len(srcs) != 1: + raise Unsupported('s_movk_i32 with %d operands' % len(srcs)) + 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' @@ -1978,7 +2000,14 @@ 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'): + def handler(self, ops, mods): + if len(ops) != 2 or mods: + raise Unsupported('s_cmpk requires a register and a 16-bit immediate') + 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): From 02f358b1d328a30ea8a436144c094ccd1b02fa00 Mon Sep 17 00:00:00 2001 From: Royoo <3230853833@qq.com> Date: Wed, 25 Nov 2026 09:16:06 +0800 Subject: [PATCH 2/2] startup: keep scalar arity refusals when lowering SOPK immediates --- docs/experiments.md | 6 ++++++ tests/startup_gfx2hlsl_sopk_signext_check.py | 2 +- tools/startup/gfx2hlsl.py | 12 +++++++----- 3 files changed, 14 insertions(+), 6 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index e9303dd71d..a040cdc1bb 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -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. diff --git a/tests/startup_gfx2hlsl_sopk_signext_check.py b/tests/startup_gfx2hlsl_sopk_signext_check.py index 43a93d441a..4a1c0805a3 100644 --- a/tests/startup_gfx2hlsl_sopk_signext_check.py +++ b/tests/startup_gfx2hlsl_sopk_signext_check.py @@ -91,7 +91,7 @@ def signext16(word): # negative controls: the translator must refuse what the encoding cannot hold, and what has no lowering refused = 0 -for program in (['s_movk_i32 s0, 0x10000'], ['s_movk_i32 s0, -0x8001'], ['s_movk_i32 s0, -32769'], ['s_movk_i32 s0, s1'], +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']): diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index f3da0a5f3b..61504378b1 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -794,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 @@ -807,8 +809,6 @@ def low(tok): srcs = [low(t) for t in srcs] dname = low(ops[0]) if base == 's_movk_i32': - if len(srcs) != 1: - raise Unsupported('s_movk_i32 with %d operands' % len(srcs)) 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') @@ -2018,10 +2018,12 @@ def handler(self, ops, mods): return handler setattr(Stage, 'op_s_cmp_%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'): + 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 or mods: - raise Unsupported('s_cmpk requires a register and a 16-bit immediate') + 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())