From ed12196da719687dca5f87799851481dd500d058 Mon Sep 17 00:00:00 2001 From: triggered02 <153171514+triggered02@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:19:33 +0530 Subject: [PATCH 1/4] startup: lower the binary32 class comparison Fixes #1797. v_cmp_class_f32 and v_cmpx_class_f32 had no lowering, so both census forms were refused - 2 of the remaining refused shaders in the loading-screen cache (#870). The ten-class helper is ported from tools/pixel_aot.py into the shader preamble, and compare() lowers the predicate to (class32(value) & mask) != 0u with the mask read as an integer operand and the value as a float. The non-exec form writes VCC; the v_cmpx_ form writes EXEC and clears the straight-line assumption. Test builds VOPC-in-VOP3 encodings, decodes, then translates: both spellings, a literal mask, a register mask, and the helper's presence and NaN distinction in the common preamble. Fail-first: & -> | fails 'a register mask is read as an integer'; renaming the helper fails 'the class helper is emitted in the common preamble'. Both presets pass. --- CMakeLists.txt | 3 + docs/experiments.md | 9 ++ tests/startup_gfx2hlsl_cmp_class_check.py | 111 ++++++++++++++++++++++ tools/startup/gfx2hlsl.py | 27 ++++++ 4 files changed, 150 insertions(+) create mode 100644 tests/startup_gfx2hlsl_cmp_class_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index a5fd85c46a..98df49d32e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1718,6 +1718,9 @@ if(EXISTS "${INTAKE_PYTHON}") # lowering of the same selections. add_test(NAME startup_gfx2hlsl_sdwa COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_sdwa_check.py") + # 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") # 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/docs/experiments.md b/docs/experiments.md index 32155c94f4..c8f5c8a0ab 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -5777,6 +5777,15 @@ uint-result table, so every `v_cvt_f32_*_sdwa` was refused until it was pointed restored path keeps the source selection, the `dst_sel`/`dst_unused` write and the `U(...)` wrapper, and a conversion's output modifier inside an SDWA form is still refused rather than dropped. +**The binary32 class comparison.** `v_cmp_class_f32` and `v_cmpx_class_f32` had no lowering, so both census +forms were refused - 2 of the remaining refused shaders in the first main-game loading-screen cache (#870, +issue #1797). They now lower to a ten-class helper carried in the shader preamble (ported from +`tools/pixel_aot.py`), testing `class32(value) & mask`: the class bits are, in encoding order, signaling NaN, +quiet NaN, -inf, -normal, -denormal, -0, +0, +denormal, +normal and +inf. The mask is read as an integer +operand (the census form uses the inline `-1`, i.e. every class) and the value as a float; the `_e32` and +`_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`. + ## Pixel color without a texture sample For an unsampled pixel program, a matched P1/P2 interpolation in the entry mask can supply attr0.x/y/z/w from a four-component TEXCOORD0. The profile binds entry v0/v1 to the barycentric pair and the observed m0 source to the interpolation base. Each completed P2 produces a distinct value, including when the destination overwrites v0. The test vertex shader varies all four channels across a full-screen triangle. CPU references check all four output words at 1,024 pixel centers; an incorrect channel at an interior pixel must fail. Run `ctest --preset dev --no-tests=error -R '^pixel_aot_attribute_'`. diff --git a/tests/startup_gfx2hlsl_cmp_class_check.py b/tests/startup_gfx2hlsl_cmp_class_check.py new file mode 100644 index 0000000000..49e9774011 --- /dev/null +++ b/tests/startup_gfx2hlsl_cmp_class_check.py @@ -0,0 +1,111 @@ +"""`v_cmp_class_f32` in tools/startup/gfx2hlsl.py (issue #1797). + +usage: startup_gfx2hlsl_cmp_class_check.py + +The binary32 class comparison had no lowering, so both census forms were refused - `v_cmp_class_f32_e64 s32, +-1, v4` and the `_e32` spelling - 2 of the remaining refused shaders in the main-game loading-screen cache +(#870). `tools/pixel_aot.py` already carries the ten-class helper; this port lowers the compare through it. + +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 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_F32 = 0x88 +VOPC_CMPX_CLASS_F32 = 0x98 +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(op, sdst, src0, src1, literal=None): + """Encode a VOPC comparison in its VOP3A form; a source of 255 is followed by its literal dword.""" + w0 = (0b110101 << 26) | ((op & 0x3FF) << 16) | (sdst & 0xFF) + w1 = (src0 & 0x1FF) | ((src1 & 0x1FF) << 9) + code = struct.pack('= 0x80000000u;' + ' if (magnitude > 0x7f800000u) return (bits & 0x00400000u) != 0u ? 0x2u : 0x1u;' + ' if (magnitude == 0x7f800000u) return negative ? 0x4u : 0x200u;' + ' if (magnitude >= 0x00800000u) return negative ? 0x8u : 0x100u;' + ' if (magnitude != 0u) return negative ? 0x10u : 0x80u;' + ' return negative ? 0x20u : 0x40u; }', 'uint ldu(ByteAddressBuffer b, uint a) { uint k = (a & 3) * 8, lo = b.Load(a & ~3u); if (k == 0) return lo; ' 'return (lo >> k) | (b.Load((a & ~3u) + 4) << (32 - k)); }', 'cbuffer entry : register(b0) { %s };' % ' '.join('uint ud%d;' % i for i in range(len(self.uds)))] From 05bce5c0511fed9e6fb79180d3251c3d31efd7c3 Mon Sep 17 00:00:00 2001 From: triggered02 <153171514+triggered02@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:28:29 +0530 Subject: [PATCH 2/4] startup: fix the class-compare operand order, exec mask and e32 form Review on #1798 (1 P1, 2 P2). (P1) The ISA order is value in SRC0 and class-bit mask in SRC1; the branch had them swapped, so 'v_cmp_class_f32 vcc, v4, 0x200' tested class(mask) against the value instead of classifying v4 for +inf. (P2) A narrowed EXEC must stay narrowed: the predicate is now intersected with exec when exec_known is false, as the generic compare path does. (P2) The _e32 cmpx spelling prints no destination because it writes EXEC implicitly, so the two-operand form is accepted and routed to EXEC. The test now encodes the ISA operand order, adds the e32 exec-mask form, and asserts the intersection with a narrowed EXEC. Fail-first: swapping the operands back, removing the intersection, and rejecting the two-operand form each fail the test. --- tests/startup_gfx2hlsl_cmp_class_check.py | 34 +++++++++++++++++++---- tools/startup/gfx2hlsl.py | 15 +++++++--- 2 files changed, 40 insertions(+), 9 deletions(-) diff --git a/tests/startup_gfx2hlsl_cmp_class_check.py b/tests/startup_gfx2hlsl_cmp_class_check.py index 49e9774011..8a8fbff93a 100644 --- a/tests/startup_gfx2hlsl_cmp_class_check.py +++ b/tests/startup_gfx2hlsl_cmp_class_check.py @@ -38,6 +38,14 @@ def check(label, condition, detail=''): 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(' Date: Wed, 25 Nov 2026 00:49:37 +0530 Subject: [PATCH 3/4] startup: check the class helper by value, not by text Review on #1798 (P2): every class check was a substring match on the emitted text, so a wrong class bit passed. The test now carries a Python classifier written from the IEEE binary32 layout (sign, exponent, mantissa) and a small recursive-descent evaluator for the integer HLSL the helper emits; it runs the emitted helper body over 68626 bit patterns (18 edge cases plus every exponent with mantissa boundaries, plus a strided sweep of the whole 32-bit space) and requires the returned class bits to match the classifier. Fail-first: swapping the -inf/+inf bits, the quiet/signaling NaN bits, or the subnormal bits each fail this check while the old text checks still passed. Also added the abs/neg SRC0 cases: those modifiers arrive as operand text (|v4|, -v4) rather than a modifier list, so the helper must see the modified bits. --- tests/startup_gfx2hlsl_cmp_class_check.py | 177 +++++++++++++++++++++- 1 file changed, 174 insertions(+), 3 deletions(-) diff --git a/tests/startup_gfx2hlsl_cmp_class_check.py b/tests/startup_gfx2hlsl_cmp_class_check.py index 8a8fbff93a..712fdfb109 100644 --- a/tests/startup_gfx2hlsl_cmp_class_check.py +++ b/tests/startup_gfx2hlsl_cmp_class_check.py @@ -11,6 +11,7 @@ `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 @@ -46,10 +47,11 @@ def encode_vopc_e32(op, src0, vsrc1, literal=None): code += struct.pack('> 31) & 1 + exponent = (bits >> 23) & 0xFF + mantissa = bits & 0x7FFFFF + if exponent == 0xFF: + if mantissa == 0: + return 0x4 if sign else 0x200 + return 0x2 if mantissa & 0x400000 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')) + if item == 'asuint': + return self.call() + return self.vars[item] + + def call(self): + if self.take() != '(': + raise ValueError('missing (') + value = self.ternary() + if self.take() != ')': + raise ValueError('missing )') + return value & 0xFFFFFFFF + + +def evaluate_class32(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 = {'value': 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) + + +_pipe = object.__new__(G.Pipeline) +_pipe.uds, _pipe.resources, _pipe.samplers, _pipe.uses_sampler_heap = [], {}, {}, False +class32_text = [entry for entry in _pipe.common() if 'uint class32(' in entry][0] +grid = [0x00000000, 0x80000000, 0x00000001, 0x80000001, 0x007FFFFF, 0x807FFFFF, 0x00800000, + 0x80800000, 0x7F7FFFFF, 0xFF7FFFFF, 0x7F800000, 0xFF800000, 0x7F800001, 0xFF800001, + 0x7FC00000, 0xFFC00000, 0x7FFFFFFF, 0xFFFFFFFF] +for _sign in (0, 1): + for _exponent in range(256): + for _mantissa in (0, 1, 0x3FFFFF, 0x400000, 0x7FFFFE, 0x7FFFFF): + grid.append((_sign << 31) | (_exponent << 23) | _mantissa) +grid += list(range(0, 1 << 32, 0x10001)) +_mismatches = [(bits, ref_class32(bits), evaluate_class32(class32_text, bits)) for bits in grid + if evaluate_class32(class32_text, bits) != ref_class32(bits)] +check('the emitted helper agrees with the binary32 classifier on %d patterns' % len(grid), + not _mismatches, repr(_mismatches[:4])) + if failures: print('FAIL') for text in failures: From 7187e51d483bab89ae0d671c091567968feee431 Mon Sep 17 00:00:00 2001 From: triggered02 <153171514+triggered02@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:09:22 +0530 Subject: [PATCH 4/4] startup: lower the binary16 class comparison Fixes #1855. v_cmp_class_f16 and v_cmpx_class_f16 had no lowering, so the census form v_cmp_class_f16_e64 s14, 0x7c01, v0 was refused. tools/pixel_aot.py already carried the binary16 helper; it is ported into Pipeline.common() as class16, and the class-compare branch dispatches on the mnemonic: the value is the raw binary16 bits in the low half of the word, abs/neg act on bit 15, and a float-printed operand is refused (it would be lowered as its binary32 bits). The _e32/_e64 and cmpx shapes share the binary32 path now with a generic v_cmpx_ check. Test builds VOPC encodings, decodes then translates, and checks the helper by value: a Python binary16 classifier against the emitted helper evaluated over all 65536 patterns; the three class-bit mutations fail it. Stacked on #1798 (class-compare branch not on main yet). --- CMakeLists.txt | 3 + docs/experiments.md | 7 + tests/startup_gfx2hlsl_cmp_class_f16_check.py | 270 ++++++++++++++++++ tools/startup/gfx2hlsl.py | 36 ++- 4 files changed, 312 insertions(+), 4 deletions(-) create mode 100644 tests/startup_gfx2hlsl_cmp_class_f16_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 98df49d32e..94ec0ca85f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1718,6 +1718,9 @@ if(EXISTS "${INTAKE_PYTHON}") # lowering of the same selections. add_test(NAME startup_gfx2hlsl_sdwa COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_sdwa_check.py") + # The binary16 class comparison (#1823). + add_test(NAME startup_gfx2hlsl_cmp_class_f16 COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_cmp_class_f16_check.py") # 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") diff --git a/docs/experiments.md b/docs/experiments.md index c8f5c8a0ab..1d26b73af3 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -5786,6 +5786,13 @@ 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 binary16 class comparison.** `v_cmp_class_f16` and `v_cmpx_class_f16` share the class-compare +branch with the binary32 form but read the value as raw binary16 bits in the low half of the operand word: +`class16(bits) & mask`, with the ten class bits of the half format and the quiet bit at 0x0200. The census +form `v_cmp_class_f16_e64 s14, 0x7c01, v0` now lowers. An `abs`/`neg` modifier on the value acts on bit 15 +of the half, not bit 31, and a float-printed operand is refused because it would be lowered as its +binary32 bits. Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_cmp_class_f16$' -V`. + ## Pixel color without a texture sample For an unsampled pixel program, a matched P1/P2 interpolation in the entry mask can supply attr0.x/y/z/w from a four-component TEXCOORD0. The profile binds entry v0/v1 to the barycentric pair and the observed m0 source to the interpolation base. Each completed P2 produces a distinct value, including when the destination overwrites v0. The test vertex shader varies all four channels across a full-screen triangle. CPU references check all four output words at 1,024 pixel centers; an incorrect channel at an interior pixel must fail. Run `ctest --preset dev --no-tests=error -R '^pixel_aot_attribute_'`. 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..bcf087e0cb --- /dev/null +++ b/tests/startup_gfx2hlsl_cmp_class_f16_check.py @@ -0,0 +1,270 @@ +"""`v_cmp_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, issue #1855). `tools/pixel_aot.py` already carries the ten-class binary16 helper; this port +reuses the class-compare branch that handles the binary32 form. + +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 +S14, V0, VCC_LO = 14, 0x100, 106 +INLINE_MINUS_ONE = 193 +INLINE_ONE_FLOAT = 242 +LITERAL_SOURCE = 255 + + +def encode_vopc(op, sdst, src0, src1, literal=None, abs_src0=0, neg_src0=0): + """Encode a VOPC comparison in its VOP3A form; source 255 is followed by its literal dword.""" + w0 = ((0b110101 << 26) | ((op & 0x3FF) << 16) | (sdst & 0xFF) | ((abs_src0 & 1) << 8)) + w1 = (src0 & 0x1FF) | ((src1 & 0x1FF) << 9) | ((neg_src0 & 1) << 29) + 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 integer HLSL the class16 helper emits.""" + + 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 value(self): + return self.ternary() + + 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_class16(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).value() & 0xFFFFFFFF + elif statement.startswith('bool '): + name, expr = (piece.strip() for piece in statement[5:].split('=', 1)) + variables[name] = int(bool(Expr(expr, variables).value())) + elif statement.startswith('if ') and ') return ' in statement: + condition, consequence = statement[3:].split(') return ', 1) + if Expr(condition[1:], variables).value(): + return Expr(consequence, variables).value() & 0xFFFFFFFF + elif statement.startswith('return '): + return Expr(statement[7:], variables).value() & 0xFFFFFFFF + raise ValueError('the helper returned nothing for %#x' % bits) + + +_pipe = object.__new__(G.Pipeline) +_pipe.uds, _pipe.resources, _pipe.samplers, _pipe.uses_sampler_heap = [], {}, {}, False +class16_text = [entry for entry in _pipe.common() if 'uint class16(' in entry][0] +grid = list(range(0x10000)) +_mismatches = [(bits, ref_class16(bits), evaluate_class16(class16_text, bits)) for bits in grid + if evaluate_class16(class16_text, bits) != ref_class16(bits)] +check('the emitted helper agrees with the binary16 classifier on all 65536 patterns', + not _mismatches, repr(_mismatches[:4])) + +if failures: + print('FAIL') + for text in failures: + print(' ' + text) + sys.exit(1) +print('PASS') \ No newline at end of file diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 8143a28803..bd4465d5b9 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -961,20 +961,39 @@ def op_v_cvt_pkrtz_f16_f32(self, ops, mods): def compare(self, base, ops): # 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). - if base in ('v_cmp_class_f32', 'v_cmpx_class_f32'): + if base in ('v_cmp_class_f32', 'v_cmpx_class_f32', 'v_cmp_class_f16', 'v_cmpx_class_f16'): + f16 = base.endswith('_f16') if len(ops) == 3: dst, value, mask = ops - elif base == 'v_cmpx_class_f32' and len(ops) == 2: + elif base.startswith('v_cmpx_') and len(ops) == 2: # The _e32 spelling writes EXEC implicitly and prints no destination. dst, (value, mask) = 'exec', ops else: raise Unsupported('%s with %d operands' % (base, len(ops))) - cond = '(class32(%s) & %s) != 0u' % (self.f(value), self.u(mask)) + if f16: + # The helper classifies the raw binary16 bits in the low half of the word, so the value is + # read as an integer and an abs/neg modifier flips bit 15 (not 31). A float-printed + # operand would be lowered as its binary32 bits, so it is refused instead. + operand = value + if operand.startswith('-') and not re.match(r'-[\d.]', operand): + operand = operand[1:] + elif operand.startswith('|') and operand.endswith('|'): + operand = operand[1:-1] + if operand in FLOATS or re.fullmatch(r'-?\d+\.\d+', operand): + raise Unsupported('binary16 class operand %s' % value) + bits = self.u(operand) + if value.startswith('-') and not re.match(r'-[\d.]', value): + bits = '(%s ^ 0x8000u)' % bits + elif value.startswith('|') and value.endswith('|'): + bits = '(%s & 0x7fffu)' % bits + cond = '(class16(%s) & %s) != 0u' % (bits, self.u(mask)) + else: + cond = '(class32(%s) & %s) != 0u' % (self.f(value), self.u(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: predicate = '(exec & %s)' % predicate - if base == 'v_cmpx_class_f32' or dst in ('exec', 'exec_lo'): + if base.startswith('v_cmpx_') or dst in ('exec', 'exec_lo'): self.exec_known = False self.emit('exec = %s;' % predicate) elif dst in ('vcc', 'vcc_lo'): @@ -1304,6 +1323,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 for v_cmp_class_f16, from bits [15:0] of the operand word + # (ported from tools/pixel_aot.py): sNaN qNaN -inf -normal -subnormal -0 +0 +subnormal +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; }', 'uint ldu(ByteAddressBuffer b, uint a) { uint k = (a & 3) * 8, lo = b.Load(a & ~3u); if (k == 0) return lo; ' 'return (lo >> k) | (b.Load((a & ~3u) + 4) << (32 - k)); }', 'cbuffer entry : register(b0) { %s };' % ' '.join('uint ud%d;' % i for i in range(len(self.uds)))]