diff --git a/CMakeLists.txt b/CMakeLists.txt index 36e53d97f6..6f96c4b24f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3511,6 +3511,10 @@ if(EXISTS "${INTAKE_PYTHON}") # 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") + # v_frexp_mant_f32, v_frexp_exp_i32_f32, v_cvt_flr_i32_f32, v_cvt_rpi_i32_f32 and v_ldexp_f32 (#1723). + add_test(NAME startup_gfx2hlsl_frexp_cvt COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_frexp_cvt_check.py") + set_tests_properties(startup_gfx2hlsl_frexp_cvt PROPERTIES TIMEOUT 60) # The SDWA form of v_cndmask_b32: fixture and model controls; the draws are registered below. add_test(NAME startup_gfx2hlsl_sdwa_cndmask COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_sdwa_cndmask_check.py") @@ -4022,6 +4026,16 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter} $<$:${STARTUP_FXC}>) set_tests_properties(startup_gfx2hlsl_spill_wave64_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) endforeach() + # gfx2hlsl frexp, float-to-int conversions and ldexp (#1723): translation controls, then a desktop draw of each + # operation compared with a reference computed from Python doubles, with a mutated lowering that must differ. + add_test(NAME startup_gfx2hlsl_frexp_cvt_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_frexp_cvt_warp_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_frexp_cvt_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_frexp_cvt_warp_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_frexp_cvt_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + endforeach() # gfx2hlsl 24-bit multiplies, v_xnor_b32 and the funnel shifts: CPU evaluation of the translated text # against an independent reference built from unbounded integers. add_test(NAME startup_gfx2hlsl_mul24_align COMMAND "${INTAKE_PYTHON}" -B diff --git a/docs/experiments.md b/docs/experiments.md index 7faa600b90..e69569ece5 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -15888,6 +15888,19 @@ a store inside the loop, a live-out scalar that depends on the key (or is comput descriptor keeps an instruction-specific refusal. The fixtures include a key-independent live-out read after the loop (accepted, checked against a D3D12 WARP readback) and key-dependent live-outs (refused). +### Startup translator: frexp, float-to-int conversions and ldexp + +`tools/startup/gfx2hlsl.py` lowers five more operations: `v_frexp_mant_f32`, `v_frexp_exp_i32_f32`, `v_cvt_flr_i32_f32`, `v_cvt_rpi_i32_f32` and `v_ldexp_f32`. This is the startup path, separate from the `pixel_aot.py` helpers of the same names. `v_cvt_rpi_i32_f32` adds one to `floor(x)` when the exact fraction `x - floor(x)` is at least 0.5, because binary32 `x + 0.5` would round `0x3effffff` up to 1 and move `8388609.0`. A NaN reads `0x7fffffff` with its sign bit clear and `0x80000000` with it set, and values outside the int32 range saturate, matching `CVT_FLR_RPI_EXCEPTIONAL` in `tests/pixel_aot_check.py`. `v_frexp_exp_i32_f32` gives 0 for zero, denormals, infinity and NaN. Output modifiers and `clamp` on the two conversions and on `v_frexp_exp_i32_f32` are refused. + +`tests/startup_gfx2hlsl_frexp_cvt_check.py` is CPU only: it translates each operation, runs the emitted line on a small evaluator that rounds every binary32 add, subtract and multiply, and compares with an exact reference over 51 words per unary operation (including all six NaN spellings, both infinities and the saturation edges) and 736 `v_ldexp_f32` pairs. `tests/startup_gfx2hlsl_frexp_cvt_warp_check.py` draws the same operations through D3D12 and compares the read-back with that reference on WARP and on hardware. + +```bash +python3 -B tests/startup_gfx2hlsl_frexp_cvt_check.py +ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_frexp_cvt' -V +``` + +Not covered: denormal inputs and results of `v_ldexp_f32` (the denormal mode decides them), signalling-NaN payloads of `v_frexp_mant_f32`, and the console's own results. + ## Desktop audio render sink `startup_audio_output` drives a small WASAPI shared-mode render sink ([`audio_sink.h`](../src/startup_stubs/audio_sink.h)) with generated PCM blocks. It is the first slice of [issue #1145](https://github.com/R0Y00/Xbox2Windows/issues/1145). The sink takes `submit(format, frames, bytes)`, converts the block to the endpoint mix format (32-bit float or 16-bit PCM only) and records the first accepted block, the submitted format, per-block frame counts and peaks, consumed frames (submitted minus `GetCurrentPadding`), the `IAudioClock` position, the drained interval and the recovery. The fixture runs three cases in one process: no submission; eight 40 ms blocks with distinct amplitudes, one of them intentionally silent; and a producer that withholds the next block until the queue is empty, then resumes. diff --git a/tests/startup_gfx2hlsl_frexp_cvt_check.py b/tests/startup_gfx2hlsl_frexp_cvt_check.py new file mode 100644 index 0000000000..45042d70c1 --- /dev/null +++ b/tests/startup_gfx2hlsl_frexp_cvt_check.py @@ -0,0 +1,282 @@ +"""v_frexp_mant_f32, v_frexp_exp_i32_f32, v_cvt_flr_i32_f32, v_cvt_rpi_i32_f32 and v_ldexp_f32 in +tools/startup/gfx2hlsl.py (FRONTIER_NEXT_BATCH_3 item 7). + +usage: startup_gfx2hlsl_frexp_cvt_check.py (pure Python, no compiler) + +Each operation is lowered by the translator, then the emitted HLSL line is run on the CPU by a small evaluator +(binary32 rounding after every float multiply). The references follow the AMD RDNA 2 ISA reference: + frexp_mant: sign and mantissa in [0.5, 1) of a normal input; zero and denormal give a signed zero; inf and NaN + pass through. + frexp_exp: the matching exponent; 0 for zero, denormal, inf and NaN. + cvt_flr / cvt_rpi: floor(x) / floor(x + 0.5) in exact arithmetic, saturated to int32; a NaN reads 0x7fffffff + (sign clear) or 0x80000000 (sign set), as measured on RDNA 2 (CVT_FLR_RPI_EXCEPTIONAL). + ldexp: S0 * 2^S1 with S1 a signed integer. +Not covered: denormal inputs and results of v_ldexp_f32 (the denormal mode decides them) and signaling-NaN payloads. + +Profile this oracle states: the NORMAL domain only (normal inputs, normal results, zero, inf, NaN). The binary32 denormal +selection (MODE[5:4]) is not modelled by the startup translator: a write that selects it is accepted and changes no emitted +line, so the emitted code follows the desktop compiler's own denormal behaviour (flushing, as measured on WARP and one +desktop GPU). ref_cvt_flr and ref_ldexp compute denormal words exactly, ref_frexp_mant answers a signed zero; none of +these denormal rows is a guest guarantee, and a desktop result on them says nothing about the console. A guest profile +for denormals needs a source-built native reference that records the selected mode, the input and the output words. +""" +import math +import re +import struct +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / 'tools' / 'startup')) +import gfx2hlsl as G # noqa: E402 + +MASK = 0xffffffff +TOKEN = re.compile(r'0x[0-9a-fA-F]+u?|\d+\.\d+|\d+u?|[A-Za-z_]\w*|\|\||==|!=|<=|>=|>>|<<|[-+*/&|?:(),<>!~]') +BINARY = [['||'], ['|'], ['&'], ['==', '!='], ['<', '>', '<=', '>='], ['<<', '>>'], ['+', '-'], ['*', '/']] + + +def f32(x): + try: + return struct.unpack(' U() would change the word.""" + word = None + + +def bits(x): + if isinstance(x, F32) and x.word is not None: + return x.word + return struct.unpack('= 1 << 31 else x + + +FUNCS = { + 'U': bits, 'F': value, 'uint': lambda x: int(x) & MASK, 'int': to_int, 'float': float, + 'floor': lambda x: x if math.isinf(x) else float(math.floor(x)), 'max': max, 'exp2': lambda x: f32(2.0 ** x), + 'clamp': lambda x, lo, hi: min(max(x, lo), hi), 'saturate': lambda x: min(max(x, 0.0), 1.0), +} + + +def idiv(a, b): + return int(a / b) + + +def add(a, b): + return f32(a + b) if isinstance(a, float) or isinstance(b, float) else (a + b) & MASK + + +def sub(a, b): + return f32(a - b) if isinstance(a, float) or isinstance(b, float) else a - b + + +def mul(a, b): + return f32(a * b) if isinstance(a, float) or isinstance(b, float) else (a * b) & MASK + + +class Parser: + """C-precedence parser for the emitted subset; produces a Python expression string.""" + + def __init__(self, text): + self.t = TOKEN.findall(text) + assert ''.join(self.t) == re.sub(r'\s+', '', text), text + self.i = 0 + self.out = self.ternary() + assert self.i == len(self.t), text + + def peek(self): + return self.t[self.i] if self.i < len(self.t) else None + + def take(self): + self.i += 1 + return self.t[self.i - 1] + + def ternary(self): + cond = self.binary(0) + if self.peek() != '?': + return cond + self.take() + yes = self.ternary() + assert self.take() == ':' + return '(%s if %s else %s)' % (yes, cond, self.ternary()) + + def binary(self, level): + if level == len(BINARY): + return self.unary() + node = self.binary(level + 1) + while self.peek() in BINARY[level]: + op = self.take() + right = self.binary(level + 1) + if op == '||': + node = '(%s or %s)' % (node, right) + elif op == '/': + node = 'idiv(%s, %s)' % (node, right) + elif op == '*': + node = 'mul(%s, %s)' % (node, right) + elif op == '+': + node = 'add(%s, %s)' % (node, right) + elif op == '-': + node = 'sub(%s, %s)' % (node, right) + else: + node = '(%s %s %s)' % (node, op, right) + return node + + def unary(self): + token = self.take() + if token == '-': + return '(-%s)' % self.unary() + if token == '(': + node = self.ternary() + assert self.take() == ')' + return node + if token[0].isdigit(): + return repr(float(token)) if '.' in token else str(int(token.rstrip('u'), 0)) + if self.peek() != '(': + return token + self.take() + args = [self.ternary()] + while self.peek() == ',': + self.take() + args.append(self.ternary()) + assert self.take() == ')' + return '%s(%s)' % (token, ', '.join(args)) + + +def lowered(base, asm): + """The right-hand side of the one register write the translator emits for `asm`.""" + stage = G.Stage.__new__(G.Stage) + stage.sym, stage.used_s, stage.used_v, stage.uniform_v = {}, set(), set(), set() + stage.exec_known, stage.has_branches, stage.lines = True, False, [] + stage.one(base, asm) + assert len(stage.lines) == 1, stage.lines + match = re.fullmatch(r'v3 = (.*);', stage.lines[0]) + assert match, stage.lines + return match.group(1) + + +def run(text, **regs): + env = dict(FUNCS, idiv=idiv, mul=mul, add=add, sub=sub, **regs) + return eval(Parser(text).out, {'__builtins__': {}}, env) + + +# ---- references ---------------------------------------------------------------------------------------- +def ref_frexp_mant(w): + e = w >> 23 & 255 + if e == 255: + return w + if e == 0: + return w & 0x80000000 + mant, _ = math.frexp(value(w)) + return bits(mant) + + +def ref_frexp_exp(w): + e = w >> 23 & 255 + return 0 if e in (0, 255) else math.frexp(value(w))[1] & MASK + + +def saturate_int(x, word): + if x != x: + return 0x7fffffff + (word >> 31) + return max(-2 ** 31, min(2 ** 31 - 1, math.floor(x))) & MASK if not math.isinf(x) else ( + MASK >> 1 if x > 0 else 0x80000000) + + +def ref_cvt_flr(w): + return saturate_int(value(w), w) + + +def ref_cvt_rpi(w): + x = value(w) + return saturate_int(x if math.isinf(x) or x != x else math.floor(x + 0.5), w) + + +def ref_ldexp(a, n): + n = n - (1 << 32) if n >= 1 << 31 else n + x = value(a) + if x != x or math.isinf(x) or x == 0.0: + return a + try: + return bits(math.ldexp(x, max(-400, min(400, n)))) + except OverflowError: + return bits(math.copysign(math.inf, x)) + + +NAN, INF = 0x7fc00000, 0x7f800000 +FLOATS = [0.0, -0.0, 1.0, -1.0, 0.5, -0.5, 0.75, 1.5, -2.5, 3.0, 0.1, -0.1, 0.4999, 0.5001, -0.5001, 1e-5, + 123456.789, -98765.4, 1.0e20, -1.0e20, 2.0 ** -126, 2.0 ** 127, 1.7014118e38, 8388608.5, 2147483520.0, + -2147483648.0, 2.0 ** 31, -2.0 ** 33, 3.4028235e38, -3.4028235e38] +WORDS = [bits(x) for x in FLOATS] + [NAN, INF, INF | 0x80000000, 0x00000001, 0x80400000, 0x007fffff, + 0xffc00000, 0x7f800001, 0xff800001, 0x7fffffff, 0xffffffff, + 0x3effffff, 0xbf000001, 0x4b000001, 0xcb000001, 0x4b7fffff, 0x4effffff] +SHIFTS = [0, 1, -1, 5, -5, 24, -24, 100, -100, 126, -126, 127, -127, 200, -200, 299, 300, 301, -300, 1000, -1000, + 2 ** 31 - 1, -2 ** 31] + +failures = [] + + +def check(label, got, want, case): + if got != want: + failures.append(label) + print('%s: MISMATCH %s got 0x%08x want 0x%08x' % (label, case, got, want)) + + +def unary(label, name, ref): + for w in WORDS: + for suffix in ('e32', 'e64'): + got = run(lowered('%s_%s' % (name, suffix), '%s_%s v3, v1' % (name, suffix)), v1=w) + check('%s_%s' % (label, suffix), got & MASK, ref(w) & MASK, hex(w)) + print('%s: %d inputs' % (label, len(WORDS))) + + +def main(): + unary('v_frexp_mant_f32', 'v_frexp_mant_f32', ref_frexp_mant) + unary('v_frexp_exp_i32_f32', 'v_frexp_exp_i32_f32', ref_frexp_exp) + unary('v_cvt_flr_i32_f32', 'v_cvt_flr_i32_f32', ref_cvt_flr) + unary('v_cvt_rpi_i32_f32', 'v_cvt_rpi_i32_f32', ref_cvt_rpi) + count = 0 + for a in [bits(x) for x in FLOATS if x != 2.0 ** -126] + [NAN, INF, INF | 0x80000000]: + for n in SHIFTS: + got = run(lowered('v_ldexp_f32', 'v_ldexp_f32 v3, v1, v2'), v1=a, v2=n & MASK) + want = ref_ldexp(a, n & MASK) + if (got & MASK) != want and not (got != got and want != want): + check('v_ldexp_f32', got & MASK, want, '%s << %d' % (hex(a), n)) + count += 1 + print('v_ldexp_f32: %d inputs' % count) + # Source and output modifiers: negation reaches the operand, mul:2 scales the result, and the operations + # that cannot carry a modifier refuse it. + check('ldexp neg', run(lowered('v_ldexp_f32', 'v_ldexp_f32 v3, -v1, v2'), v1=bits(1.5), v2=2) & MASK, + bits(-6.0), 'neg') + check('ldexp mul:2', run(lowered('v_ldexp_f32', 'v_ldexp_f32 v3, v1, v2 mul:2'), v1=bits(1.5), v2=2) & MASK, + bits(12.0), 'mul:2') + for asm in ('v_cvt_flr_i32_f32_e64 v3, v1 clamp', 'v_cvt_rpi_i32_f32_e64 v3, v1 mul:2', + 'v_frexp_exp_i32_f32_e64 v3, v1 clamp'): + try: + lowered(asm.split()[0], asm) + except G.Unsupported: + continue + failures.append(asm) + print('accepted a modifier: ' + asm) + if failures: + print('FAILED: %d' % len(failures)) + return 1 + print('gfx2hlsl frexp/cvt/ldexp check passed') + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tests/startup_gfx2hlsl_frexp_cvt_warp_check.py b/tests/startup_gfx2hlsl_frexp_cvt_warp_check.py new file mode 100644 index 0000000000..7ac30e0f44 --- /dev/null +++ b/tests/startup_gfx2hlsl_frexp_cvt_warp_check.py @@ -0,0 +1,188 @@ +"""D3D12 draw check for v_frexp_mant_f32, v_frexp_exp_i32_f32, v_cvt_flr_i32_f32, v_cvt_rpi_i32_f32 and +v_ldexp_f32 in tools/startup/gfx2hlsl.py (Part of #1723). + + (no arguments) translation controls, pure Python + binary reassemble the fixture bodies and compare them with the words below + draw [fxc] + compile the translated pair with FXC ps_5_1 when given and with DXC ps_6_0, + draw one pixel per input chunk and compare the four result words + +The fixture reuses the flat-parameter pixel prologue of startup_gfx2hlsl_bit_alu_check.py: twelve words arrive in +v0..v11 and v12..v15 are exported. Each operation runs on four lanes per pixel (source words v0..v3, the ldexp +exponents v4..v7). + +The expected words come from the references of startup_gfx2hlsl_frexp_cvt_check.py (math.frexp, math.floor and +math.ldexp on Python doubles), not from the lowering. Each lowering has a mutation (a changed constant) whose draw +must read other words, so a draw that cannot see the difference fails the check. Denormal inputs and results are +left out: the denormal mode decides them. +""" +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +import startup_gfx2hlsl_frexp_cvt_check as R # noqa: E402 +from startup_flat_param_check import assemble, compile_hlsl, draw, root_blob # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import (POST_SOURCE, POST_WORDS, PRE_SOURCE, PRE_WORDS, # noqa: E402 + vs_source, vs_words) + +MASK = 0xffffffff +UNARY = ('v_frexp_mant_f32', 'v_frexp_exp_i32_f32', 'v_cvt_flr_i32_f32', 'v_cvt_rpi_i32_f32') +OPS = UNARY + ('v_ldexp_f32',) +REFERENCE = {'v_frexp_mant_f32': R.ref_frexp_mant, 'v_frexp_exp_i32_f32': R.ref_frexp_exp, + 'v_cvt_flr_i32_f32': R.ref_cvt_flr, 'v_cvt_rpi_i32_f32': R.ref_cvt_rpi} +# mnemonic -> (text the lowering must contain, replacement that changes the result) +MUTATION = {'v_frexp_mant_f32': ('0x3f000000u', '0x3f800000u'), + 'v_frexp_exp_i32_f32': ('- 126u', '- 127u'), + 'v_cvt_flr_i32_f32': ('floor(', 'ceil('), + 'v_cvt_rpi_i32_f32': ('>= 0.5', '>= 0.75'), + 'v_ldexp_f32': ('exp2(float(', '-exp2(float(')} +BODY_SOURCE = {op: ''.join('%s v%d, v%d\n' % (op, 12 + i, i) for i in range(4)) for op in UNARY} +BODY_SOURCE['v_ldexp_f32'] = ''.join('v_ldexp_f32 v%d, v%d, v%d\n' % (12 + i, i, 4 + i) for i in range(4)) + +# Normal, finite, inf and NaN inputs; the cvt inputs include the saturating ends. +UNARY_INPUTS = [R.bits(x) for x in (1.0, -1.0, 0.5, 0.75, -2.5, 3.0, 0.1, -0.1, 0.4999, 0.5001, 123456.789, + -98765.4, 1.0e20, -1.0e20, 2.0 ** 127, 8388608.5, 2147483520.0, + -2147483648.0, 2.0 ** 31, -2.0 ** 33, 3.4028235e38, 0.0, -0.0, 2.0 ** -126)] +UNARY_INPUTS += [R.INF, R.INF | 0x80000000, R.NAN, 0x7f7fffff, + 0xffc00000, 0x3effffff, 0x4b000001, 0xff800001] +LDEXP_INPUTS = [(R.bits(a), n & MASK) for a, n in ( + (1.0, 1), (1.5, -1), (-1.5, 5), (0.1, 24), (123456.789, -20), (-3.0, 100), (1.0, 127), (1.0, -126), + (1.0, 200), (-1.0, -200), (0.0, 5), (-0.0, -5), (1.0, 2 ** 31 - 1), (1.0, -2 ** 31), (2.0, 300), (1.5, 0))] +LDEXP_INPUTS += [(R.INF, 3), (R.INF | 0x80000000, -3 & MASK), (R.NAN, 7), (R.bits(3.0), 2)] + + +def chunks(op): + """(12 parameter words, 4 expected result words) per pixel.""" + out = [] + if op == 'v_ldexp_f32': + for i in range(0, len(LDEXP_INPUTS), 4): + part = LDEXP_INPUTS[i:i + 4] + out.append(([a for a, _ in part] + [n for _, n in part] + [0] * 4, [R.ref_ldexp(a, n) for a, n in part])) + else: + for i in range(0, len(UNARY_INPUTS), 4): + part = UNARY_INPUTS[i:i + 4] + out.append((part + [0] * 8, [REFERENCE[op](w) & MASK for w in part])) + return out + + +def mutate_text(op, text): + old, new = MUTATION[op] + mutated = text.replace(old, new) + assert mutated != text, op + return mutated + + +def sets_for(words): + """The four (src0, src1, src2) tuples vs_words() turns into parameter words 0..11 in order.""" + return [(words[lane], words[4 + lane], words[8 + lane]) for lane in range(4)] + + +def ps_words(op): + return PRE_WORDS + BODY_WORDS[op] + POST_WORDS + + +BODY_WORDS = { + 'v_frexp_mant_f32': bytes.fromhex('0081187e01811a7e02811c7e03811e7e'), + 'v_frexp_exp_i32_f32': bytes.fromhex('007f187e017f1a7e027f1c7e037f1e7e'), + 'v_cvt_flr_i32_f32': bytes.fromhex('001b187e011b1a7e021b1c7e031b1e7e'), + 'v_cvt_rpi_i32_f32': bytes.fromhex('0019187e01191a7e02191c7e03191e7e'), + 'v_ldexp_f32': bytes.fromhex('0c0062d7000902000d0062d7010b02000e0062d7020d02000f0062d7030f0200'), +} + + +def translate(op, mutate=False): + pipe = G.Pipeline(vs_words([(0, 0, 0)] * 4), ps_words(op), root_blob()) + text = pipe.hlsl_ps() + return pipe, mutate_text(op, text) if mutate else text + + +def check(label, ok): + print('%s: %s' % (label, 'ok' if ok else 'MISMATCH')) + if not ok: + raise AssertionError(label) + + +def controls(): + for op in OPS: + check('%s fixture has 12 words per pixel' % op, all(len(w) == 12 and len(e) == 4 for w, e in chunks(op))) + check('%s inputs fill every lane' % op, sum(len(e) for _, e in chunks(op)) == ( + len(LDEXP_INPUTS) if op == 'v_ldexp_f32' else len(UNARY_INPUTS))) + check('%s mutation changes the translation' % op, translate(op, True)[1] != translate(op)[1]) + + +def check_binary(llvm_mc): + for op, source in BODY_SOURCE.items(): + words = assemble(llvm_mc, source) + if op in BODY_WORDS and BODY_WORDS[op] != words: + raise AssertionError('%s: assembled %s, recorded %s' % (op, words.hex(), BODY_WORDS[op].hex())) + print(" '%s': bytes.fromhex('%s')," % (op, words.hex())) + for name, source, words in (('prologue', PRE_SOURCE, PRE_WORDS), ('export', POST_SOURCE, POST_WORDS)): + if assemble(llvm_mc, source) != words: + raise AssertionError('%s fixture differs from llvm-mc' % name) + for op in OPS: + for words, _ in chunks(op): + sets = sets_for(words) + if assemble(llvm_mc, vs_source(sets)) != vs_words(sets): + raise AssertionError('vertex fixture for %s differs from llvm-mc' % (sets,)) + print('fixture words match llvm-mc') + + +def words_text(values): + return ','.join('%08x' % v for v in values) + + +def check_draw(dxc, renderer, adapter, fxc=None): + controls() + compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + for op in OPS: + good_ps = compile_hlsl(compiler, kind, translate(op)[1], 'ps_%s_%s' % (op, kind), ps_profile, directory) + bad_ps = compile_hlsl(compiler, kind, translate(op, True)[1], 'mutated_%s_%s' % (op, kind), + ps_profile, directory) + caught = 0 + for index, (words, expected) in enumerate(chunks(op)): + vs = compile_hlsl(compiler, kind, G.Pipeline(vs_words(sets_for(words)), ps_words(op), + root_blob()).hlsl_vs(), + 'vs_%s_%d_%s' % (op, index, kind), vs_profile, directory) + want = words_text(expected) + run = draw(renderer, adapter, vs, good_ps, want) + if run.returncode: + raise AssertionError('%s %s pixel %d expected %s\n%s\n%s' % (kind, op, index, want, run.stdout, + run.stderr)) + print('%s %s pixel %d: %s' % (kind, op, index, want), flush=True) + run = draw(renderer, adapter, vs, bad_ps, want) + if run.returncode: + mismatch = f'startup_flat_param mismatch expected={want} actual=' + debug_ok = ('debug_layer=enabled' not in run.stdout + or 'debug_errors=0 debug_warnings=0' in run.stdout) + if run.returncode != 1 or mismatch not in run.stderr or not debug_ok: + raise AssertionError(f'{kind} {op} mutation failed before producing a readback\n' + f'{run.stdout}\n{run.stderr}') + caught += 1 + if not caught: + raise AssertionError('%s %s: no pixel told the mutated lowering from the reference' % (kind, op)) + print('%s %s mutation: %d pixels read other words' % (kind, op, caught), flush=True) + + +def main(): + if len(sys.argv) == 1: + controls() + print('gfx2hlsl frexp/cvt draw fixture: controls passed') + return + mode, *args = sys.argv[1:] + if mode == 'binary': + check_binary(*args) + elif mode == 'draw': + check_draw(*args) + else: + raise SystemExit(__doc__) + + +if __name__ == '__main__': + main() diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 5621c2bd8b..98ec09e124 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -7120,6 +7120,71 @@ def op_v_mbcnt_lo_u32_b32(self, ops, mods, high=False): def op_v_mbcnt_hi_u32_b32(self, ops, mods): self.op_v_mbcnt_lo_u32_b32(ops, mods, high=True) + def float_bits(self, tok): + """uint bits of a float source, with the inline neg/abs operand modifiers applied.""" + return 'U(%s)' % self.f(tok) + + def op_v_frexp_mant_f32(self, ops, mods): + # Sign and mantissa in [0.5, 1) of a normal input; zero and denormals read as a signed zero; + # infinity and NaN pass through unchanged (RDNA 2 ISA, V_FREXP_MANT_F32). + if len(ops) != 2: + raise Unsupported('v_frexp_mant_f32 with %d operands, expected 2' % len(ops)) + b = self.float_bits(ops[1]) + e = '((%s >> 23) & 255u)' % b + expr = 'F(%s == 255u ? %s : %s == 0u ? (%s & 0x80000000u) : ((%s & 0x807fffffu) | 0x3f000000u))' % ( + e, b, e, b, b) + self.set_vf(reg_range(ops[0])[1], expr, mods) + + def op_v_frexp_exp_i32_f32(self, ops, mods): + # Exponent e with input = mantissa * 2^e and mantissa in [0.5, 1). Zero, denormal, infinity and NaN give 0. + if mods: + raise Unsupported('v_frexp_exp_i32_f32 with modifiers') + if len(ops) != 2: + raise Unsupported('v_frexp_exp_i32_f32 with %d operands, expected 2' % len(ops)) + e = '((%s >> 23) & 255u)' % self.float_bits(ops[1]) + self.set_v(reg_range(ops[0])[1], '(%s == 0u || %s == 255u) ? 0u : (%s - 126u)' % (e, e, e)) + + def float_to_int(self, base, ops, mods, rpi): + # Saturating conversion. v_cvt_flr rounds toward -inf; v_cvt_rpi adds 1 to floor(x) when the exact + # fraction x - floor(x) is at least 0.5 (binary32 x + 0.5 would round 0x3effffff up and 2^23 + 1 off). + # A NaN reads 0x7fffffff with its sign bit clear and 0x80000000 with it set; a value at or above 2^31 + # reads INT_MAX and one below -2^31 reads INT_MIN (native RDNA 2 words, tests/pixel_aot_check.py). + if mods: + raise Unsupported('%s with modifiers' % base) + if len(ops) != 2: + raise Unsupported('%s with %d operands, expected 2' % (base, len(ops))) + x = self.f(ops[1]) + r = 'floor(%s)' % x + if rpi: + r = '(%s + (((%s) - %s) >= 0.5 ? 1.0 : 0.0))' % (r, x, r) + bits = self.float_bits(ops[1]) + self.set_v(reg_range(ops[0])[1], '((%s & 0x7fffffffu) > 0x7f800000u) ? (0x7fffffffu + (%s >> 31)) : ' + '(%s >= 2147483648.0) ? 0x7fffffffu : uint(int(clamp(%s, -2147483648.0, 2147483520.0)))' % ( + bits, bits, x, r)) + + def op_v_cvt_flr_i32_f32(self, ops, mods): + self.float_to_int('v_cvt_flr_i32_f32', ops, mods, False) + + def op_v_cvt_rpi_i32_f32(self, ops, mods): + self.float_to_int('v_cvt_rpi_i32_f32', ops, mods, True) + + def op_v_ldexp_f32(self, ops, mods): + # D = S0 * 2^S1 with S1 a signed integer, clamped to +-300 (the result is 0 or inf past that anyway). + # The scale is applied in three parts of at most 2^100 each, so that no factor overflows binary32 + # when the product is finite. + if len(ops) != 3: + raise Unsupported('v_ldexp_f32 with %d operands, expected 3' % len(ops)) + n = 'clamp(int(%s), -300, 300)' % self.u(ops[2]) + a = '(%s / 3)' % n + b = '((%s - %s) / 2)' % (n, a) + c = '(%s - %s - %s)' % (n, a, b) + # A NaN keeps its word: the product would give a payload the hardware chooses (an RTX 3070 Ti reads + # 0x7fc00000 * 2^k back as 0x7fffffff). + bits = self.float_bits(ops[1]) + expr = 'F(((%s & 0x7fffffffu) > 0x7f800000u) ? %s : U(((%s * exp2(float(%s))) * exp2(float(%s))) * exp2(float(%s))))' % ( + bits, bits, self.f(ops[1]), a, b, c) + self.set_vf(reg_range(ops[0])[1], expr, mods) + def proven_uniform_v(self, n): """VGPR n holds one value in every lane EXEC enables now. In the entry block EXEC is known; past it, a recomputable expression proves no join, EXEC write or overwrite lies between the definition and here."""