diff --git a/docs/experiments/native-direct-add-sub-sat.md b/docs/experiments/native-direct-add-sub-sat.md new file mode 100644 index 0000000000..2e269e4e58 --- /dev/null +++ b/docs/experiments/native-direct-add-sub-sat.md @@ -0,0 +1,31 @@ +# Signed and saturating 32-bit add/sub in the direct C++ compute path (#3009) + +The direct compute frontend refused the VOP3-only `v_add_nc_i32` and `v_sub_nc_i32` with `direct DXIL lowering for +`, and the `clamp` forms of `v_add_nc_u32`, `v_sub_nc_u32` and `v_subrev_nc_u32` with `direct ALU operand +modifiers`. It now lowers them: + +- without `clamp`, the signed forms wrap modulo 2^32 like the unsigned ones; +- with `clamp`, `v_*_nc_i32` saturates to the i32 range (an overflow saturates toward the sign of S0) and + `v_*_nc_u32` saturates to 0 or 0xffffffff. + +LLVM 15.0.7 selects exactly these clamp forms for `llvm.sadd.sat.i32`, `llvm.ssub.sat.i32`, `llvm.uadd.sat.i32` and +`llvm.usub.sat.i32` (`clang -nogpulib -target amdgcn-- -mcpu=gfx1013 -O2 -S`). `tools/startup/gfx2hlsl.py` has no +lowering for these forms. `tools/compute_store_aot.py` lowers the unclamped signed forms the same way (wrap) and +refuses clamp (`tests/compute_store_check.py`, `vadd_nc_i32_controls`). Overflow is detected with 32-bit sign tests, so the module needs no 64-bit integers. +Source negation or abs, omod, op_sel, SDWA and DPP forms are refused. + +## Fixture + +`tests/native_add_sub_sat_check.py controls|hardware` (`ctest --preset dev --no-tests=error -R '^native_add_sub_sat_' +-V`). The VOP3 words were assembled with LLVM 15.0.7 (`clang -cc1as -triple amdgcn -target-cpu gfx1013 -filetype asm +-show-encoding`). Four cases set S0 and S1 by `v_mov` literals at the i32 and u32 edges: 0x7fffffff + 1, +0x80000000 - 1, -1 + 0x80000000 and 0x7fffffff - (-1). Every lane of two groups stores the seven results of each case. + +The controls compile the program and check the module for the add, sub and select. They check that a neg modifier on +S0 is refused. They also check that three references each differ from the expected words: unclamped, signedness +swapped, saturation toward the sign of S1, and `v_subrev_nc_u32` without the operand swap. The log of this run is +`out/logs/addsub_ctest.log` (not committed). + +Measured on 27.11.2026, `cpp-migration` `e0d83759` plus this change, Windows 10.0.26100, with an NVIDIA Quadro M1000M +(driver 32.0.15.7371, debug layer unavailable). The controls passed. The readback reported a skip (77) because it needs +shader model 6.6 with wave32. The readback is not measured. diff --git a/src/gfx1013_direct_compute.inl b/src/gfx1013_direct_compute.inl index 7375533562..f0f2368657 100644 --- a/src/gfx1013_direct_compute.inl +++ b/src/gfx1013_direct_compute.inl @@ -1600,6 +1600,34 @@ struct DirectCompute { vector_write(i.dst, i.clamp ? saturated_add(dot, acc, sign) : dot); return; } + const bool signed_add_sub = n == "v_add_nc_i32" || n == "v_sub_nc_i32"; + if (signed_add_sub || (i.clamp && (n == "v_add_nc_u32" || n == "v_sub_nc_u32" || n == "v_subrev_nc_u32"))) { + // AMD RDNA 2 ISA: the VOP3-only signed forms wrap like the unsigned ones, and clamp saturates the + // result: signed for v_*_nc_i32, unsigned for v_*_nc_u32. LLVM 15 selects these clamp forms for + // llvm.sadd.sat, llvm.ssub.sat, llvm.uadd.sat and llvm.usub.sat (#3009). + if ((signed_add_sub && !i.wide) || i.subword || i.dpp_control || permuted || i.abs || i.neg || i.scale || + (i.a & 0x7800)) + refuse(i.pc, "unsupported " + string(n) + " operand modifiers"); + auto a = operand32(i, i.src[0]), b = operand32(i, i.src[1]); + if (n == "v_subrev_nc_u32") std::swap(a, b); + const bool add = n.substr(0, 5) == "v_add"; + auto result = ir.binary(add ? "add" : "sub", a, b); + if (i.clamp) { + if (signed_add_sub) { + // Overflow when the operands' signs make the true result leave the i32 range; it saturates + // toward the sign of the first operand. + auto overflow = add ? ir.binary("and", ir.binary("xor", a, result), ir.binary("xor", b, result)) + : ir.binary("and", ir.binary("xor", a, b), ir.binary("xor", a, result)); + result = select(cmp("slt", overflow, "0"), + select(cmp("slt", a, "0"), "2147483648", "2147483647"), result); + } else if (add) + result = select(cmp("ult", result, a), "4294967295", result); + else + result = select(cmp("ult", a, b), "0", result); + } + vector_write(i.dst, result); + return; + } if (n == "v_mad_u32_u16" || n == "v_mad_i32_i16") { // AMD RDNA 2 ISA, VOP3A opcodes 883/885. Only the two // multiplicands are halfwords. The addend and result are dwords. diff --git a/tests/cmake/native_add_sub_sat.cmake b/tests/cmake/native_add_sub_sat.cmake new file mode 100644 index 0000000000..4cbe684db0 --- /dev/null +++ b/tests/cmake/native_add_sub_sat.cmake @@ -0,0 +1,13 @@ +# Direct C++ compute: v_add_nc_i32, v_sub_nc_i32 and the clamp forms of the u32 adds (#3009). The controls compile and check the +# reference's mutants; the readback needs shader model 6.6 with wave32 and otherwise reports a skip (77). +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_add_sub_sat_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_add_sub_sat_check.py" controls + "$" "${DXC_BIN_DIR}") + set_tests_properties(native_add_sub_sat_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_add_sub_sat_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_add_sub_sat_check.py" hardware + "$" "${DXC_BIN_DIR}") + set_tests_properties(native_add_sub_sat_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/native_add_sub_sat_check.py b/tests/native_add_sub_sat_check.py new file mode 100644 index 0000000000..7ab26985c7 --- /dev/null +++ b/tests/native_add_sub_sat_check.py @@ -0,0 +1,143 @@ +"""v_add_nc_i32, v_sub_nc_i32 and the clamp forms of v_add_nc_u32, v_sub_nc_u32 and v_subrev_nc_u32 in the direct +compute path (#3009). + + native_add_sub_sat_check.py controls + native_add_sub_sat_check.py hardware + +The signed forms wrap like the unsigned ones; clamp saturates, signed for v_*_nc_i32 and unsigned for v_*_nc_u32. +LLVM 15.0.7 selects exactly these clamp forms for llvm.sadd.sat, llvm.ssub.sat, llvm.uadd.sat and llvm.usub.sat +(clang -nogpulib -target amdgcn-- -mcpu=gfx1013 -O2 -S). The VOP3 words were assembled with LLVM 15.0.7 +(clang -cc1as, gfx1013); the first prologue words follow native_dpp_quad_check.py, with v8 = 128 * lane and s7 = 4096 * group (32 words +per lane), and the store words follow native_lane_access_check.py. + +Each case sets S0 and S1 by v_mov literals and stores seven results; every lane of two groups stores all cases. +Unclamped, sign-swapped (unsigned saturation for the signed forms and the reverse), saturate-toward-S1 and +unswapped-subrev references must each differ from the expected words. +""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_dpp_quad_check import request + +CASES = [ + (0x7FFFFFFF, 0x00000001), + (0x80000000, 0x00000001), + (0xFFFFFFFF, 0x80000000), + (0x7FFFFFFF, 0xFFFFFFFF), +] +PROLOGUE = [0xBE940304, 0xBE950380, 0xF408080A, 0xFA000020, 0x8F078C05, 0x34100087, 0x4A101007, 0xBF8CC07F] +# v_add_nc_i32 v4 / v_add_nc_i32 v5 clamp / v_sub_nc_i32 v6 / v_sub_nc_i32 v7 clamp / v_add_nc_u32_e64 v9 clamp / +# v_sub_nc_u32_e64 v10 clamp / v_subrev_nc_u32_e64 v11 clamp, each with S0 = v1 and S1 = v2. +OPS = [('add_i32', 0xD77F0004, 4), ('add_i32 clamp', 0xD77F8005, 5), ('sub_i32', 0xD7760006, 6), + ('sub_i32 clamp', 0xD7768007, 7), ('add_u32 clamp', 0xD5258009, 9), ('sub_u32 clamp', 0xD526800A, 10), + ('subrev_u32 clamp', 0xD527800B, 11)] +SOURCES = 0x00020501 +NEG_SOURCES = 0x20020501 # the same operands with neg on S0 +SENTINEL = 0x69696969 +GUARD_WORDS = 8 +OUTPUT_WORDS = 2064 +MASK = 0xFFFFFFFF + + +def program(sources=SOURCES): + code = list(PROLOGUE) + for index, (a, b) in enumerate(CASES): + code += [0x7E0202FF, a, 0x7E0402FF, b] + for _, word, _ in OPS: + code += [word, sources] + for slot, (_, _, vgpr) in enumerate(OPS): + code += [0xE0701000 | (32 * index + 4 * slot), 0x80080008 | vgpr << 8] + return code + [0xBF810000] + + +def signed(x): + return x - (1 << 32) if x & 0x80000000 else x + + +def op(name, a, b, clamp=True, swap_sign=False, toward_b=False, subrev_swap=True): + sat = name.endswith('clamp') and clamp + is_signed = name.endswith('i32') or name.endswith('i32 clamp') + if swap_sign: + is_signed = not is_signed + if name.startswith('subrev') and subrev_swap: + a, b = b, a + if is_signed: + x, y = signed(a), signed(b) + true = x + y if name.startswith('add') else x - y + if sat and not -(1 << 31) <= true < (1 << 31): + sign = (b if toward_b else a) & 0x80000000 + return 0x80000000 if sign else 0x7FFFFFFF + return true & MASK + true = a + b if name.startswith('add') else a - b + if sat and true > MASK: + return MASK + if sat and true < 0: + return 0 + return true & MASK + + +def reference(**mutation): + expected = [SENTINEL] * OUTPUT_WORDS + for lane in range(64): + base = GUARD_WORDS + lane * 32 + for index, (a, b) in enumerate(CASES): + for slot, (name, _, _) in enumerate(OPS): + expected[base + 8 * index + slot] = op(name, a, b, **mutation) + return expected + + +def compile_program(cli, sdk, work, root, code, name): + marker = request(work, root, code) + output = marker.with_suffix(name) + return subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True), output + + +def controls(cli, sdk, work, root): + result, output = compile_program(cli, sdk, work, root, program(), '.cso') + assert result.returncode == 0 and output.is_file(), (result.stdout, result.stderr) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', output], capture_output=True, text=True, check=True).stdout + assert 'add i32' in dump and 'sub i32' in dump and 'select i1' in dump, dump + result, _ = compile_program(cli, sdk, work, root, program(NEG_SOURCES), '.neg.cso') + assert result.returncode != 0 and 'v_add_nc_i32 operand modifiers' in result.stdout + result.stderr, ( + result.stdout, result.stderr) + expected = reference() + for label, mutation in (('unclamped', {'clamp': False}), ('signedness swapped', {'swap_sign': True}), + ('saturated toward S1', {'toward_b': True}), + ('subrev without the swap', {'subrev_swap': False})): + assert reference(**mutation) != expected, label + print('compiled seven add/sub forms with saturating selects; a neg modifier is refused; the unclamped, ' + 'signedness-swapped, saturate-toward-S1 and unswapped-subrev references differ') + return 0 + + +def hardware(replay, sdk, work, root): + marker = request(work, root, program()) + output = work / 'out.bin' + result = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if result.returncode == 77: + return 77 + result.check_returncode() + actual = list(struct.unpack(f'<{OUTPUT_WORDS}I', output.read_bytes())) + expected = reference() + diff = [(i, hex(x), hex(y)) for i, (x, y) in enumerate(zip(actual, expected)) if x != y] + assert not diff, diff[:10] + print('seven add/sub forms: all 2064 words matched') + return 0 + + +def main(mode, tool, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return {'controls': controls, 'hardware': hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:]))