From 9127b60a5d9c9b066f1cbb80233045f85c45fe4e Mon Sep 17 00:00:00 2001 From: ChazY11 <246129015+ChazY11@users.noreply.github.com> Date: Wed, 25 Nov 2026 08:07:54 +0800 Subject: [PATCH 1/3] startup: lower v_cmp_class_f16 and v_cmpx_class_f16 (issue #1855) The binary16 class comparison had no lowering, so the census form `v_cmp_class_f16_e64 s14, 0x7c01, v0` was refused (#870). `tools/pixel_aot.py` already carried the ten-class half helper; it is ported into `Pipeline.common()` as `class16`, next to `class32`, and the class-compare branch dispatches on the mnemonic. The half classes follow bits [15:0] (exponent 5 bits, mantissa 10, quiet bit 0x0200), so the value is the raw operand word rather than a converted float, and `abs`/`neg` act on bit 15. The decoder prints an absolute source as `|v4|` and a negated one as `-v4`, so both spellings are accepted alongside `abs(...)`. v_cmp_class_f16_e64 s14, 0x7c01, v0 -> s14 = (((class16(0x00007c01u) & v0) != 0u) ? 1u : 0u); v_cmpx_class_f16_e64 vcc_lo, v0, -1 -> exec = (((class16(v0) & 0xffffffffu) != 0u) ? 1u : 0u); v_cmpx_class_f16_e32 v0, v5 -> exec = (((class16(v0) & v5) != 0u) ? 1u : 0u); v_cmp_class_f16_e64 s14, |v0|, v1 -> s14 = (((class16((v0 & 0x7fffu)) & v1) != 0u) ? 1u : 0u); v_cmp_class_f16_e64 s14, -v0, v1 -> s14 = (((class16((v0 ^ 0x8000u)) & v1) != 0u) ? 1u : 0u); A float-printed operand is refused by name, because it would otherwise be lowered as its binary32 bit pattern. The test builds the VOPC-in-VOP3 encodings from the checked-in decoder's layout, decodes, translates, then checks the emitted text for each form above, the float-operand refusal, and - value level - a binary16 classifier written from the IEEE half layout against the emitted helper body evaluated over all 65,536 halves. Fail-first, three category-bit mutations (each fails the value check while the text checks pass): swap -inf/+inf bits -> the emitted helper disagrees (exit 1) swap quiet/signaling NaN -> the emitted helper disagrees (exit 1) swap -subnormal/+subnormal -> the emitted helper disagrees (exit 1) Not established here: that the emitted HLSL compiles or computes the right predicate on a device. The value check evaluates the helper text in Python; DXC and WARP were not run for this change. --- tests/startup_gfx2hlsl_cmp_class_f16_check.py | 283 ++++++++++++++++++ tools/startup/gfx2hlsl.py | 42 ++- 2 files changed, 321 insertions(+), 4 deletions(-) create mode 100644 tests/startup_gfx2hlsl_cmp_class_f16_check.py diff --git a/tests/startup_gfx2hlsl_cmp_class_f16_check.py b/tests/startup_gfx2hlsl_cmp_class_f16_check.py new file mode 100644 index 0000000000..6ca7ee01e5 --- /dev/null +++ b/tests/startup_gfx2hlsl_cmp_class_f16_check.py @@ -0,0 +1,283 @@ +"""`v_cmp_class_f16` and `v_cmpx_class_f16` in tools/startup/gfx2hlsl.py (issue #1855). + +usage: startup_gfx2hlsl_cmp_class_f16_check.py + +The binary16 class comparison had no lowering, so the census form `v_cmp_class_f16_e64 s14, 0x7c01, v0` was +refused (#870). `tools/pixel_aot.py` already carries the ten-class half helper; this port lowers the compare +through it. The half classes follow bits [15:0] (exponent 5 bits, mantissa 10, quiet bit 0x0200) and abs/neg +act on bit 15, so the value is the raw operand word rather than a converted float. + +The instruction bytes are **constructed here** from the field layout the checked-in decoder reads +(`tools/disasm_rdna2.py`, VOP3A branch): prefix `0b110101`, opcode in `w0[25:16]`, scalar destination in +`w0[7:0]`, src0 in `w1[8:0]`, src1 in `w1[17:9]`, and source 255 followed by a literal dword. +""" +import os +import re +import struct +import sys + +here = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(here, '..', 'tools')) +sys.path.insert(0, os.path.join(here, '..', 'tools', 'startup')) +import gfx2hlsl as G # noqa: E402 + +failures = [] + + +def check(label, condition, detail=''): + print(f"{label}: {'ok' if condition else 'MISMATCH'}") + if not condition: + failures.append(label) + if detail: + print(' ' + detail) + + +VOPC_CMP_CLASS_F16 = 0x8F +VOPC_CMPX_CLASS_F16 = 0x9F +VCC_LO = 106 +V0, V4 = 0x100, 0x104 +INLINE_MINUS_ONE = 193 # inline constant -1, the mask the census shader uses +LITERAL_SOURCE = 255 + + +def encode_vopc_e32(op, src0, vsrc1, literal=None): + """Encode a VOPC comparison in its 32-bit form; a cmpx writes EXEC implicitly.""" + w0 = ((0b0111110 << 25) | ((op & 0xFF) << 17) | ((vsrc1 & 0xFF) << 9) | (src0 & 0x1FF)) + code = struct.pack('> 15) & 1 + exponent = (bits >> 10) & 0x1F + mantissa = bits & 0x3FF + if exponent == 0x1F: + if mantissa == 0: + return 0x4 if sign else 0x200 + return 0x2 if mantissa & 0x200 else 0x1 + if exponent == 0: + if mantissa == 0: + return 0x20 if sign else 0x40 + return 0x10 if sign else 0x80 + return 0x8 if sign else 0x100 + + +TOKEN = re.compile(r'\s*(0x[0-9a-fA-F]+u?|\d+u?|[A-Za-z_]\w*|>=|<=|==|!=|&&|\|\||[&|<>?:()!~^+-])') + + +def tokens(source): + out, position = [], 0 + while position < len(source): + match = TOKEN.match(source, position) + if not match: + raise ValueError('cannot tokenise %r' % source[position:position + 20]) + out.append(match.group(1)) + position = match.end() + return out + + +class Expr: + """A recursive-descent evaluator for the subset of HLSL the helper uses (32-bit integer bits).""" + + LEVELS = [('||',), ('&&',), ('|',), ('^',), ('&',), ('==', '!='), ('>=', '<=', '>', '<'), ('+', '-')] + + def __init__(self, source, variables): + self.items, self.at, self.vars = tokens(source), 0, variables + + def peek(self): + return self.items[self.at] if self.at < len(self.items) else '' + + def take(self): + item = self.peek() + self.at += 1 + return item + + def ternary(self): + condition = self.binary(0) + if self.peek() == '?': + self.take() + yes = self.ternary() + if self.take() != ':': + raise ValueError('missing :') + return yes if condition else self.ternary() + return condition + + def binary(self, level): + if level == len(self.LEVELS): + return self.unary() + value = self.binary(level + 1) + while self.peek() in self.LEVELS[level]: + operator = self.take() + rhs = self.binary(level + 1) + if operator == '&': + value &= rhs + elif operator == '|': + value |= rhs + elif operator == '^': + value ^= rhs + elif operator == '==': + value = int(value == rhs) + elif operator == '!=': + value = int(value != rhs) + elif operator == '>=': + value = int(value >= rhs) + elif operator == '<=': + value = int(value <= rhs) + elif operator == '>': + value = int(value > rhs) + elif operator == '<': + value = int(value < rhs) + elif operator == '&&': + value = int(bool(value) and bool(rhs)) + elif operator == '||': + value = int(bool(value) or bool(rhs)) + elif operator == '+': + value = (value + rhs) & 0xFFFFFFFF + elif operator == '-': + value = (value - rhs) & 0xFFFFFFFF + return value + + def unary(self): + item = self.take() + if item == '!': + return int(not self.unary()) + if item == '~': + return (~self.unary()) & 0xFFFFFFFF + if item == '(': + value = self.ternary() + if self.take() != ')': + raise ValueError('missing )') + return value + if re.fullmatch(r'0x[0-9a-fA-F]+u?', item): + return int(item.rstrip('u'), 16) + if re.fullmatch(r'\d+u?', item): + return int(item.rstrip('u')) + return self.vars[item] + + +def evaluate_helper(helper, bits): + """Run the emitted helper body for one bit pattern, so what is checked is the value it returns.""" + body = helper[helper.index('{') + 1:helper.rindex('}')] + variables = {'bits': bits} + for statement in (piece.strip() for piece in body.split(';')): + if not statement: + continue + if statement.startswith('uint '): + for part in statement[4:].split(','): + name, expr = (piece.strip() for piece in part.split('=', 1)) + variables[name] = Expr(expr, variables).ternary() & 0xFFFFFFFF + elif statement.startswith('bool '): + name, expr = (piece.strip() for piece in statement[5:].split('=', 1)) + variables[name] = int(bool(Expr(expr, variables).ternary())) + elif statement.startswith('if ') and ') return ' in statement: + condition, consequence = statement[3:].split(') return ', 1) + if Expr(condition[1:], variables).ternary(): + return Expr(consequence, variables).ternary() & 0xFFFFFFFF + elif statement.startswith('return '): + return Expr(statement[7:], variables).ternary() & 0xFFFFFFFF + raise ValueError('the helper returned nothing for %#x' % bits) + + +class16_text = [entry for entry in pipe.common() if 'uint class16(' in entry][0] +mismatches = [] +for _bits in range(1 << 16): + if evaluate_helper(class16_text, _bits) != ref_class16(_bits): + mismatches.append((_bits, ref_class16(_bits), evaluate_helper(class16_text, _bits))) +check('the emitted helper agrees with the binary16 classifier on all 65536 halves', + not mismatches, repr(mismatches[:4])) + +if failures: + print('startup gfx2hlsl half class compare checks: %d failed' % len(failures)) + sys.exit(1) +print('startup gfx2hlsl half class compare checks: ok') diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 98d7d8d42e..ac685e2cec 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -1624,8 +1624,12 @@ def compare(self, base, ops, mods=()): # v_cmp_class_f32 / v_cmpx_class_f32 test the binary32 class of the value in SRC0 against the # class-bit mask in SRC1 (the ISA order: the float operand first, the integer mask second). name = base.removesuffix('_sdwa') - if name in ('v_cmp_class_f32', 'v_cmpx_class_f32'): - writes_exec = name == 'v_cmpx_class_f32' + if name in ('v_cmp_class_f32', 'v_cmpx_class_f32', 'v_cmp_class_f16', 'v_cmpx_class_f16'): + # The half form (issue #1855) takes the raw binary16 pattern in the low half of the operand + # word: its classes follow the half layout (exponent 5 bits, mantissa 10, quiet bit 0x0200) + # and abs/neg act on bit 15, so the value is never converted to float here. + f16 = name.endswith('_f16') + writes_exec = name in ('v_cmpx_class_f32', 'v_cmpx_class_f16') sdwa = name != base if sdwa: self.check_compare_sdwa_destination(base, writes_exec, ops) @@ -1637,10 +1641,31 @@ def compare(self, base, ops, mods=()): else: raise Unsupported('%s with %d operands' % (base, len(ops))) if sdwa: - value, mask = self.compare_sdwa_sources(base, 'u32', [value, mask], mods, float_src0=True) + value, mask = self.compare_sdwa_sources(base, 'u32', [value, mask], mods, float_src0=f16 is False) + elif f16: + # abs() and - apply to bit 15 of the half, before the class test. + # The decoder prints an absolute source as |v4| and a negated one as -v4, so both + # spellings are accepted here as well as abs(...). + token = value + negative = token.startswith('-') + if negative: + token = token[1:] + absolute = (token.startswith('|') and token.endswith('|')) or ( + token.startswith('abs(') and token.endswith(')')) + if absolute: + token = token[4:-1] if token.startswith('abs(') else token[1:-1] + if token in FLOATS: + # A float-printed operand would otherwise be lowered as its binary32 bit pattern. + raise Unsupported('%s source %s: f16 class compares need the raw half' % (base, value)) + bits = self.u(token) + if absolute: + bits = '(%s & 0x7fffu)' % bits + if negative: + bits = '(%s ^ 0x8000u)' % bits + value, mask = bits, self.u(mask) else: value, mask = self.f(value), self.u(mask) - cond = '(class32(%s) & %s) != 0u' % (value, mask) + cond = '(%s(%s) & %s) != 0u' % ('class16' if f16 else 'class32', value, mask) predicate = '((%s) ? 1u : 0u)' % cond # A narrowed EXEC must stay narrowed: intersect with it, as the generic compare path does. if not self.exec_known: @@ -2055,6 +2080,15 @@ def common(self): ' if (magnitude >= 0x00800000u) return negative ? 0x8u : 0x100u;' ' if (magnitude != 0u) return negative ? 0x10u : 0x80u;' ' return negative ? 0x20u : 0x40u; }', + # The ten binary16 classes v_cmp_class_f16 tests, from the raw encoding (issue #1855): + # signaling NaN, quiet NaN, -inf, -normal, -denormal, -0, +0, +denormal, +normal, +inf. + 'uint class16(uint bits) { uint h = bits & 0xffffu, magnitude = h & 0x7fffu;' + ' bool negative = h >= 0x8000u;' + ' if (magnitude > 0x7c00u) return (h & 0x0200u) != 0u ? 0x2u : 0x1u;' + ' if (magnitude == 0x7c00u) return negative ? 0x4u : 0x200u;' + ' if (magnitude >= 0x0400u) return negative ? 0x8u : 0x100u;' + ' if (magnitude != 0u) return negative ? 0x10u : 0x80u;' + ' return negative ? 0x20u : 0x40u; }', # The 64-bit shifts (issue #1815): a pair of words, so the count never reaches 32 in a 32-bit # shift and an in-place destination keeps the original value (the caller passes both words in). 'uint2 shl64(uint lo, uint hi, uint sh) { sh &= 63u; uint sb = sh & 31u, sc = (32u - sb) & 31u;' From 4b15ae0930e6872c7b3bc52258d0183bfa6fd9d2 Mon Sep 17 00:00:00 2001 From: ChazY11 <246129015+ChazY11@users.noreply.github.com> Date: Wed, 25 Nov 2026 08:09:14 +0800 Subject: [PATCH 2/3] startup: register startup_gfx2hlsl_cmp_class_f16 beside the binary32 sibling --- CMakeLists.txt | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CMakeLists.txt b/CMakeLists.txt index 94084d41e9..1ae89a8d05 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2190,6 +2190,9 @@ if(EXISTS "${INTAKE_PYTHON}") # The binary32 class comparison (#1795). add_test(NAME startup_gfx2hlsl_cmp_class COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_cmp_class_check.py") + # The binary16 class comparison (#1855). + add_test(NAME startup_gfx2hlsl_cmp_class_f16 COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_cmp_class_f16_check.py") # op_sel on a translated float operation is refused, not dropped (#1735). add_test(NAME startup_gfx2hlsl_opsel COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_opsel_check.py") From 3177daed67f193330f1df9431c95669cf19aa800 Mon Sep 17 00:00:00 2001 From: Royoo <3230853833@qq.com> Date: Wed, 25 Nov 2026 08:28:36 +0800 Subject: [PATCH 3/3] shader: bound startup binary16 class comparisons to proven operands --- docs/experiments.md | 10 ++++++++++ tests/startup_gfx2hlsl_cmp_class_f16_check.py | 13 +++++++++++++ tools/startup/gfx2hlsl.py | 15 ++++++++++++--- 3 files changed, 35 insertions(+), 3 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 85af08e39b..251069eb70 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -6236,6 +6236,16 @@ operand (the census form uses the inline `-1`, i.e. every class) and the value a `_e64` spellings share the path, and the `v_cmpx_` form writes EXEC and clears the straight-line assumption. Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_cmp_class$' -V`. +**The startup binary16 class comparison.** The e32 and e64 forms classify the +low 16 raw bits of SRC0 and compare the resulting class bit against integer +SRC1. The e64 source modifiers change the half's sign bit. The literal +`0x7c01` reaches the helper unchanged. The EXEC-writing form intersects the +new predicate with a previously narrowed EXEC. SDWA and ambiguous signed +inline source spellings remain refused in this path. The fixture checks all +65,536 inputs against an independent binary16 classification and runs decoded +source-word and refusal controls. Run +`ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_cmp_class_f16$' -V`. + **An `op_sel` the lowering does not model is refused.** `set_vf()` used to accept an `op_sel` modifier and emit the same text as without it. `op_sel` selects which half of a packed source the operation reads, so dropping it silently changes the operand; the float path now refuses it (#1754). The same test pins the exact shift, diff --git a/tests/startup_gfx2hlsl_cmp_class_f16_check.py b/tests/startup_gfx2hlsl_cmp_class_f16_check.py index 6ca7ee01e5..87ce2c8a77 100644 --- a/tests/startup_gfx2hlsl_cmp_class_f16_check.py +++ b/tests/startup_gfx2hlsl_cmp_class_f16_check.py @@ -126,6 +126,19 @@ def translate(code): except G.Unsupported as reason: check('a float-printed operand is refused', 'need the raw half' in str(reason), str(reason)) +for asm, expected in ( + ('v_cmp_class_f16_e64 s14, -1, v0', 'ambiguous signed inline half'), + ('v_cmp_class_f16_e64 s14, v4, 1.0', 'expected an integer class mask'), + ('v_cmp_class_f16_e64 null, v4, v0', 'into null'), + ('v_cmp_class_f16_sdwa vcc_lo, v4, v0 src0_sel:WORD_1 src1_sel:DWORD', 'SDWA form'), +): + stage = Stage() + try: + stage.one(asm.split()[0], asm) + check(f'refused: {asm}', False, ' '.join(stage.lines)) + except G.Unsupported as reason: + check(f'refused: {asm}', expected in str(reason), str(reason)) + # 8. The helper is in the preamble the generated shader is built with, with the ten half classes. pipe = object.__new__(G.Pipeline) pipe.uds, pipe.resources, pipe.samplers, pipe.uses_sampler_heap = [], {}, {}, False diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index ac685e2cec..6938e677f1 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -1631,6 +1631,8 @@ def compare(self, base, ops, mods=()): f16 = name.endswith('_f16') writes_exec = name in ('v_cmpx_class_f32', 'v_cmpx_class_f16') sdwa = name != base + if f16 and sdwa: + raise Unsupported('SDWA form of %s' % name) if sdwa: self.check_compare_sdwa_destination(base, writes_exec, ops) if len(ops) == 3: @@ -1641,12 +1643,14 @@ def compare(self, base, ops, mods=()): else: raise Unsupported('%s with %d operands' % (base, len(ops))) if sdwa: - value, mask = self.compare_sdwa_sources(base, 'u32', [value, mask], mods, float_src0=f16 is False) + value, mask = self.compare_sdwa_sources(base, 'u32', [value, mask], mods, float_src0=True) elif f16: # abs() and - apply to bit 15 of the half, before the class test. # The decoder prints an absolute source as |v4| and a negated one as -v4, so both # spellings are accepted here as well as abs(...). token = value + if re.fullmatch(r'-[1-9]\d*', token): + raise Unsupported('%s source %s: ambiguous signed inline half' % (base, value)) negative = token.startswith('-') if negative: token = token[1:] @@ -1654,7 +1658,7 @@ def compare(self, base, ops, mods=()): token.startswith('abs(') and token.endswith(')')) if absolute: token = token[4:-1] if token.startswith('abs(') else token[1:-1] - if token in FLOATS: + if token in FLOATS or re.fullmatch(r'-[1-9]\d*', token): # A float-printed operand would otherwise be lowered as its binary32 bit pattern. raise Unsupported('%s source %s: f16 class compares need the raw half' % (base, value)) bits = self.u(token) @@ -1662,6 +1666,8 @@ def compare(self, base, ops, mods=()): bits = '(%s & 0x7fffu)' % bits if negative: bits = '(%s ^ 0x8000u)' % bits + if mask in FLOATS: + raise Unsupported('%s mask %s: expected an integer class mask' % (base, mask)) value, mask = bits, self.u(mask) else: value, mask = self.f(value), self.u(mask) @@ -1676,7 +1682,10 @@ def compare(self, base, ops, mods=()): elif dst in ('vcc', 'vcc_lo'): self.emit('vcc = %s;' % predicate) else: - d = reg_range(dst)[1] + reg = reg_range(dst) + if not reg or reg[0] != 's': + raise Unsupported('%s into %s' % (base, dst)) + d = reg[1] self.set_s(d, predicate) self.masks.add(d) return None