Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/windows.yml
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,7 @@ jobs:
tests/startup_gfx2hlsl_interp_f16_check.py \
tests/startup_gfx2hlsl_sgpr_spill_check.py \
tests/startup_gfx2hlsl_mad_check.py \
tests/startup_gfx2hlsl_neg_check.py \
tests/startup_gfx2hlsl_compute_check.py \
tests/startup_compute_lds_b64_check.py \
tests/startup_compute_lds_b128_check.py \
Expand Down
1 change: 1 addition & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,7 @@ python3 -m venv out/pe-env
./out/pe-env/bin/python -B tests/startup_gfx2hlsl_scalar_arity_check.py
./out/pe-env/bin/python -B tests/startup_gfx2hlsl_scalar_table_arity_check.py
./out/pe-env/bin/python -B tests/startup_gfx2hlsl_mad_check.py
./out/pe-env/bin/python -B tests/startup_gfx2hlsl_neg_check.py
./out/pe-env/bin/python -B tests/startup_gfx2hlsl_compute_check.py
./out/pe-env/bin/python -B tests/startup_compute_image_store_check.py
./out/pe-env/bin/python -B tests/startup_compute_image_store_d16_check.py
Expand Down
8 changes: 8 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3525,6 +3525,14 @@ if(EXISTS "${INTAKE_PYTHON}")
set_tests_properties(startup_gfx2hlsl_fma_mix_dispatch_${adapter}
PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77)
endforeach()
add_test(NAME startup_gfx2hlsl_neg_controls COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_neg_check.py")
foreach(adapter IN ITEMS warp hardware)
add_test(NAME startup_gfx2hlsl_neg_dispatch_${adapter} COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_neg_check.py" dispatch "${DXC_EXECUTABLE}"
"$<TARGET_FILE:offscreen_check>" ${adapter})
set_tests_properties(startup_gfx2hlsl_neg_dispatch_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77)
endforeach()
# gfx2hlsl compute stage: entry registers, numthreads and the offen buffer store, dispatched on a plain device (#1412).
add_test(NAME startup_gfx2hlsl_compute_controls COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_compute_check.py")
Expand Down
4 changes: 3 additions & 1 deletion docs/experiments.md
Original file line number Diff line number Diff line change
Expand Up @@ -13940,7 +13940,9 @@ ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_cmp16_' -V
python -B tests/startup_gfx2hlsl_cmp16_check.py binary <llvm-mc> <llvm-objcopy>
```

`tools/startup/gfx2hlsl.py` also refuses the NEG bit of a VOP3 source that is a non-negative inline integer (0 to 64) or a literal. The disassembler prints inline 1 with NEG as `-1`, the same text as inline -1, so the text cannot tell the two encodings apart. The exception is the two data operands of `v_cndmask_b32_e64`, which model NEG as a flip of bit 31. The hardware behavior of NEG on integer sources is not measured. Check: `tests/startup_gfx2hlsl_refusals_check.py`.
`tools/startup/gfx2hlsl.py` refuses VOP3 NEG on a non-negative inline integer (0 to 64) or a literal in integer and unclassified source slots. The disassembler prints inline 1 with NEG as `-1`, the same text as inline -1, so the text cannot tell the two encodings apart. The two data operands of `v_cndmask_b32_e64` model NEG as a flip of bit 31. `tests/startup_gfx2hlsl_refusals_check.py` covers these rules.

For binary32 arithmetic and compare sources, the translator reads the inline integer (0 to 64) or literal dword from the VOP3 encoding, flips bit 31, and emits `F(0x........u)` using the existing `asfloat` macro. This follows LLVM AMDGPUAsmParser's immediate sign XOR and the RDNA 2 ISA's description of NEG as a float input modifier. The class mask and immediate ABS combined with NEG still refuse. RDNA hardware behavior for these immediate sources has not been measured. The D3D12 readback in `tests/startup_gfx2hlsl_neg_check.py` checks normal FMA and MED3 results, signed zero and normal MUL results, and allows signed flush-to-zero for subnormal MUL results.

## Startup translator: explicit-LOD image sampling

Expand Down
114 changes: 114 additions & 0 deletions tests/startup_gfx2hlsl_neg_check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
"""Translate encoded binary32 VOP3 NEG fixtures and optionally dispatch them on D3D12."""
import struct
import subprocess
import sys
import tempfile
from pathlib import Path

from startup_flat_param_check import root_blob
from startup_gfx2hlsl_bit_alu_check import G, POST_WORDS, PRE_WORDS, vs_words
from startup_gfx2hlsl_refusals_check import vop3

SIGN = 0x80000000
ONE = 0x3f800000
MIN_NORMAL = 0x00800000
# (encoded selector, optional literal dword)
IMMEDIATES = ((128, None), (129, None), (192, None), (255, 0x40a00000))
# (encoded opcode, arity, runtime src1, runtime src2, scalar reference)
OPS = {
'v_fma_f32': (0x14b, 3, ONE, SIGN | ONE, lambda a, b, c: a * b + c),
'v_mul_f32': (0x108, 2, ONE, 0, lambda a, b, c: a * b),
'v_med3_f32': (0x157, 3, SIGN | ONE, 0xc0000000, lambda a, b, c: sorted((a, b, c))[1]),
}


def float_value(word):
return struct.unpack('<f', struct.pack('<I', word))[0]


def float_word(value):
return struct.unpack('<I', struct.pack('<f', value))[0]


def reference(instruction, b, c, evaluate):
control, = struct.unpack_from('<I', instruction, 4)
selector = control & 0x1ff
word = struct.unpack_from('<I', instruction, 8)[0] if selector == 255 else selector - 128
if control & (1 << 29):
word ^= SIGN
return float_word(evaluate(float_value(word), float_value(b), float_value(c)))


def fixture(op):
opcode, arity, b, c, evaluate = OPS[op]
instructions = [
vop3(opcode, [selector, 260 + lane, 264 + lane if arity == 3 else 0],
vdst=12 + lane, neg=1, literal=literal)
for lane, (selector, literal) in enumerate(IMMEDIATES)
]
inputs = [(0, b, c)] * 4
hlsl = G.Pipeline(vs_words(inputs), PRE_WORDS + b''.join(instructions) + POST_WORDS, root_blob()).hlsl_ps()
for lane, word in enumerate((0x80000000, 0x80000001, 0x80000040, 0xc0a00000)):
statement = next(line for line in hlsl.splitlines() if line.strip().startswith(f'v{12 + lane} ='))
assert f'F(0x{word:08x}u)' in statement, (op, statement)
return hlsl, inputs, tuple(reference(code, b, c, evaluate) for code in instructions)


def dispatch(dxc, runner, adapter, hlsl, inputs, directory):
# Keep the other sources opaque to the compiler and use strict floating-point
# compilation so signed zero is observable.
fill = [(i + 1) * 0x9e3779b1 & 0xffffffff | 1 for i in range(16)]
words = [initial ^ value for initial, value in zip(fill, (row[arg] for arg in range(3) for row in inputs))]
params = '\n'.join(' i.fparam%d = data.Load4(%d) ^ uint4(%s);' %
(p, p * 16, ', '.join(f'0x{word:08x}u' for word in words[p * 4:p * 4 + 4]))
for p in range(3))
source = hlsl.replace('PSOut main(PSIn i)', 'PSOut translated(PSIn i)') + '''
RWByteAddressBuffer data : register(u0);
[numthreads(1, 1, 1)]
void main() {
PSIn i = (PSIn)0;
''' + params + '''
data.Store4(48, asuint(translated(i).mrt0));
}
'''
src, cso, output = (directory / name for name in ('neg.hlsl', 'neg.cso', 'neg.bin'))
src.write_text(source, encoding='ascii')
subprocess.run([dxc, '-T', 'cs_6_0', '-Gis', '-E', 'main', '-Fo', str(cso), str(src)], check=True)
run = subprocess.run([runner, adapter, '--raw-uav-dump', str(cso), '1', '64', str(output)],
capture_output=True, text=True)
print(run.stdout, end='')
if run.returncode == 77:
sys.exit(77)
if run.returncode or run.stderr:
raise AssertionError(run.stderr or f'raw UAV dump exited with {run.returncode}')
actual = struct.unpack('<16I', output.read_bytes())
assert actual[:12] == tuple(fill[:12]), 'operand region changed'
return actual[12:]


def check_dispatch(dxc, runner, adapter):
runner = str(Path(runner).resolve())
out = Path(__file__).resolve().parents[1] / 'out'
out.mkdir(exist_ok=True)
with tempfile.TemporaryDirectory(dir=out) as tmp:
for op in OPS:
hlsl, inputs, expected = fixture(op)
actual = dispatch(dxc, runner, adapter, hlsl, inputs, Path(tmp))
for lane, (got, want) in enumerate(zip(actual, expected)):
# FMA and MED3 always produce normals here. MUL produces exact -0
# for inline 0 and a normal for the literal. The two nonzero inline
# MUL results can flush to signed zero under the adapter's FTZ mode.
allowed = (want, want & SIGN) if 0 < (want & ~SIGN) < MIN_NORMAL else (want,)
assert got in allowed, (op, lane, f'{got:08x}', [f'{word:08x}' for word in allowed])
print(f'{op}: ' + ' '.join(f'{word:08x}' for word in actual))


if __name__ == '__main__':
if len(sys.argv) == 1:
for op in OPS:
fixture(op)
print('VOP3 NEG fixtures contain the encoded sign-flipped words')
elif len(sys.argv) == 5 and sys.argv[1] == 'dispatch':
check_dispatch(*sys.argv[2:])
else:
sys.exit('usage: startup_gfx2hlsl_neg_check.py [dispatch <dxc> <offscreen_check> <warp|hardware>]')
83 changes: 62 additions & 21 deletions tests/startup_gfx2hlsl_refusals_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,30 +114,45 @@ def check_neg_integer_sources():
cndmask = 0x101
accepted = [op for op in range(0x400) if not isinstance(translate_one(vop3(op, sentinels)), str)]
check('the sweep reaches the accepted VOP3 opcodes', len(accepted) > 100 and cndmask in accepted)
loose = []
mismatches = []
for op in accepted:
for slot in range(3):
srcs = list(sentinels)
srcs[slot] = inline(1)
plain = translate_one(vop3(op, srcs))
result = translate_one(vop3(op, srcs, neg=1 << slot))
modeled = op == cndmask and slot < 2
if isinstance(plain, str) or modeled:
continue
# Ops with their own, earlier refusal of NEG and ABS (the 16-bit compares, v_sad_*) keep it.
if not (isinstance(result, str) and ('NEG on an integer or literal source %d' % slot in result
or ' with neg/abs' in result)):
loose.append((hex(op), slot, result))
check('NEG on inline 1 is refused for every accepted opcode and slot except v_cndmask_b32_e64 data sources',
not loose)
if loose:
print(' first misses: %s' % loose[:4])
for source, literal, expected in ((inline(1), None, '0x80000001'), (255, 5, '0x80000005')):
srcs = list(sentinels)
srcs[slot] = source
code = vop3(op, srcs, literal=literal)
if literal is not None and G.D.decode_instruction(code, 0)[0] != len(code):
# An unused source field does not consume a literal dword.
continue
plain = translate_one(code)
if isinstance(plain, str) or (op == cndmask and slot < 2):
continue
result = translate_one(vop3(op, srcs, neg=1 << slot, literal=literal))
name = plain[0].split()[0].removesuffix('_e64')
compare = name.startswith(('v_cmp_', 'v_cmpx_')) and name.endswith('_f32')
float_slot = (name in G.VEC_F and slot < G.VEC_F[name][0]
or compare and slot < (1 if '_class_' in name else 2))
if float_slot:
# Always/never compares consume no source in the emitted predicate.
constant_compare = name.split('_')[-2] in ('t', 'f')
ok = (not isinstance(result, str) and expected in result[0]
and (constant_compare or expected + 'u' in ' '.join(result[1])))
else:
# Dedicated encoding refusals run before the general NEG check.
ok = (isinstance(result, str) and ('NEG on an integer or literal source %d' % slot in result
or ' with neg/abs' in result))
if not ok:
mismatches.append((hex(op), slot, expected, result))
check('VOP3 NEG on inline 1 and a literal follows the source type in every lowerable slot', not mismatches)
if mismatches:
print(' first misses: %s' % mismatches[:4])

def refused(code, slot):
text = translate_one(code)
return isinstance(text, str) and 'NEG on an integer or literal source %d' % slot in text

iadd, fadd, cmp_lt, add_co, shl64 = names['v_mad_u32_u24'], 0x103, 0x81, names['v_add_co_u32'], names['v_lshlrev_b64']
iadd, fadd, add_co, shl64 = names['v_mad_u32_u24'], 0x103, names['v_add_co_u32'], names['v_lshlrev_b64']
cmp_lt = next(op for op, entry in G.D.VOPC_OPS.items() if entry[0] == 'v_cmp_lt_f32_e32')
for slot in range(3):
srcs = list(sentinels)
srcs[slot] = inline(1)
Expand All @@ -150,10 +165,36 @@ def refused(code, slot):
check('literal with NEG refused', refused(vop3(iadd, [255, sentinels[1], sentinels[2]], neg=1, literal=5), 0))
check('literal without NEG translates', not isinstance(
translate_one(vop3(iadd, [255, sentinels[1], sentinels[2]], literal=5)), str))
check('v_add_f32_e64 with an integer inline and NEG refused', refused(vop3(fadd, [inline(1), v(12), 0], neg=1), 0))
check('compare with inline 1 and NEG refused', refused(vop3(cmp_lt, [inline(1), v(12), 0], sdst=4, neg=1), 0))
check('compare slot 1 with literal and NEG refused', refused(
vop3(cmp_lt, [v(10), 255, 0], sdst=4, neg=2, literal=7), 1))
def exact(code, word):
result = translate_one(code)
return not isinstance(result, str) and 'F(0x%08xu)' % word in ' '.join(result[1])

check('v_add_f32_e64 inline 0 with NEG is negative zero',
exact(vop3(fadd, [inline(0), v(12), 0], neg=1), 0x80000000))
check('v_add_f32_e64 inline 64 with NEG stays subnormal',
exact(vop3(fadd, [inline(64), v(12), 0], neg=1), 0x80000040))
check('v_add_f32_e64 NEG flips the sign of an encoded NaN payload',
exact(vop3(fadd, [255, v(12), 0], neg=1, literal=0xffc12345), 0x7fc12345))
check('v_add_f32_e64 immediate ABS with NEG is refused',
refused(vop3(fadd, [inline(1), v(12), 0], absolute=1, neg=1), 0))
word0, word1 = struct.unpack('<2I', vop3(fadd, [v(10), inline(1), 0], neg=2))
# The rewritten final operand must keep both supported and refused output modifiers.
clamp = translate_one(struct.pack('<2I', word0 | (1 << 15), word1))
check('rewriting the last source preserves clamp',
not isinstance(clamp, str) and 'saturate(F(v10) + F(0x80000001u))' in ' '.join(clamp[1]))
op_sel = translate_one(struct.pack('<2I', word0 | (1 << 11), word1))
check('rewriting the last source preserves the op_sel refusal',
isinstance(op_sel, str) and 'modifier op_sel' in op_sel)
check('float compare slot 0 with inline 1 and NEG reads its word',
exact(vop3(cmp_lt, [inline(1), v(12), 0], neg=1), 0x80000001))
check('float compare slot 1 with literal and NEG reads its word',
exact(vop3(cmp_lt, [v(10), 255, 0], neg=2, literal=7), 0x80000007))
check('class compare slot 0 with literal and NEG reads its word',
exact(vop3(0x88, [255, inline(1), 0], neg=1, literal=7), 0x80000007))
check('class compare slot 1 with literal and NEG is refused',
refused(vop3(0x88, [v(10), 255, 0], neg=2, literal=7), 1))
check('integer compare slot 0 with inline and NEG is refused',
refused(vop3(0x81, [inline(1), v(12), 0], neg=1), 0))
check('v_add_co_u32 (carry out) with inline 1 and NEG refused',
refused(vop3(add_co, [inline(1), v(12), 0], sdst=4, neg=1), 0))
check('v_lshlrev_b64 with NEG on the shift inline refused', refused(vop3(shl64, [inline(1), v(12), 0], neg=1), 0))
Expand Down
40 changes: 33 additions & 7 deletions tools/startup/gfx2hlsl.py
Original file line number Diff line number Diff line change
Expand Up @@ -411,19 +411,45 @@ def check_encoding(code, off, n, name, asm):
fields[i + 1] = operand[:len(operand) - len(operand.lstrip())] + '0x%08x' % (bits ^ 0x80000000)
asm = ','.join(fields)
if n >= 8 and struct.unpack_from('<I', code, off)[0] >> 26 == 0b110101:
# VOP3 NEG (w1[31:29], bit 29 + i for source i) on a non-negative inline integer (128..192) or a literal (255).
# The decoder prints inline 1 with NEG as `-1`, the text of the plain inline -1 (193), so both would translate to
# 0xffffffff, and a literal 5 would become 0xfffffffb. Only v_cndmask_b32_e64 models NEG on its two data
# sources (above, as the sign bit flipped). Inline floats, registers and negative inlines are not affected.
# ABS is not tested: on the VOP3b forms w0[10:8] is SDST, not a modifier.
word1, = struct.unpack_from('<I', code, off + 4)
# Read the word from the encoding: NEG on inline 1 is printed as `-1`, indistinguishable
# from the plain inline -1 selector.
# LLVM AMDGPUAsmParser::applyInputFPModifiers folds NEG into an immediate by XOR with the
# FP sign mask. RDNA 2 lists VOP3 NEG as a float input modifier. Hardware behavior for
# these immediate sources has not been measured.
word0, word1 = struct.unpack_from('<2I', code, off)
base = name.removesuffix('_e64')
float_sources = 0
if base in VEC_F:
float_sources = VEC_F[base][0]
elif re.fullmatch(r'v_cmpx?_\w+_f32', base):
float_sources = 1 if base in ('v_cmp_class_f32', 'v_cmpx_class_f32') else 2
rewritten = {}
for i in range(3):
if name == 'v_cndmask_b32_e64' and i < 2 or not word1 & (1 << (29 + i)):
continue
source = (word1 >> (9 * i)) & 0x1ff
if 128 <= source <= 192 or source == 255:
if not (128 <= source <= 192 or source == 255):
continue
# The selected float forms are VOP3A, where w0[10:8] holds ABS. Keep the
# refusal for NEG combined with ABS on this source.
if i >= float_sources or word0 & (1 << (8 + i)):
raise Unsupported('%s with NEG on an integer or literal source %d: the printed sign would read as inline -N'
% (name, i))
if source == 255:
if n != 12 or off + n > len(code):
raise Unsupported('%s missing literal dword' % name)
bits, = struct.unpack_from('<I', code, off + 8)
else:
bits = source - 128
# f() bitcasts this hex word through F(), the asfloat macro.
rewritten[i + 1] = '0x%08x' % (bits ^ 0x80000000)
if rewritten:
mnemonic, operands, mods = parse(asm)
if len(operands) <= max(rewritten):
raise Unsupported('malformed %s operands' % name)
for index, token in rewritten.items():
operands[index] = token
asm = ' '.join([mnemonic, ', '.join(operands), *mods])
return asm


Expand Down
Loading