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
3 changes: 3 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -1686,6 +1686,9 @@ 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")
# A negated source on the vector select flips that source's sign bit (#1709).
add_test(NAME startup_gfx2hlsl_cndmask_neg COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_cndmask_neg_check.py")
# Output modifiers on float-result conversions (#1705).
add_test(NAME startup_gfx2hlsl_vcvt_omod COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_vcvt_omod_check.py")
Expand Down
10 changes: 10 additions & 0 deletions docs/experiments.md
Original file line number Diff line number Diff line change
Expand Up @@ -5737,6 +5737,16 @@ control mismatching. The D3D12 debug layer was unavailable.
[Leonida RDNA2 measurements](https://github.com/ItsNotRexed/Leonida/pull/1685) ·
[AMD RDNA 2 instruction set](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf)

**Negated sources on the vector select.** A VOP3 `v_cndmask_b32` can carry the `-` source modifier,
which in an integer instruction is that source's sign bit flipped. The select handler passed the printed
operand to the uint helper, so `v_cndmask_b32_e64 v31, v30, -v30` was refused - 2 of the 29 refused
shaders in the first main-game loading-screen cache (#870, issue #1709). The select now reads both sources
through a helper that flips the sign bit for a `-` operand and emits the same text as before when there is
none. Plain negative constants retain the existing bit pattern. NEG on inline or literal constants is
refused from the encoded source fields, because plain inline -1 and inline 1 with NEG both disassemble
as `-1`. Another integer instruction carrying the same register modifier still refuses it. Run
`ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_cndmask_neg$' -V`.

**Output modifiers on float-result conversions.** The float-result conversions (`v_cvt_f32_i32`,
`v_cvt_f32_u32`, `v_cvt_f32_ubyte0..3`, `v_cvt_f32_f16`) sat in the uint-result table, whose dispatch
refused every modifier, so `v_cvt_f32_i32_e64 v1, v1 mul:2` did not translate - 5 of the 29 refused
Expand Down
140 changes: 140 additions & 0 deletions tests/startup_gfx2hlsl_cndmask_neg_check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
"""Negated sources on the vector select in tools/startup/gfx2hlsl.py (issue #1709).

usage: startup_gfx2hlsl_cndmask_neg_check.py

A VOP3 `v_cndmask_b32` can carry the `-` source modifier, which in an integer instruction is the source's
sign bit flipped. The select handler passed the printed operand straight to the uint helper, so
`v_cndmask_b32_e64 v31, v30, -v30` was refused with `Unsupported: operand '-v30'` - 2 of the 29 refused
shaders in the first main-game loading-screen cache (#870).

The instruction bytes are **constructed here** from the field layout the checked-in decoder reads
(`tools/disasm_rdna2.py`, VOP3A branch):
w0: [31:26] = 0b110101, [25:16] opcode (VOP2 e64 = 0x100 + VOP2 opcode), [7:0] vdst
w1: [8:0] src0, [17:9] src1, [28:27] omod, [31:29] neg
"""
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)


VOP2_E64_BASE = 0x100
CNDMASK = 0x01
AND_B32 = 0x1b
V30 = 256 + 30 # VGPR operands are encoded from 256 upwards


def encode_vop2_e64(op, vdst, src0, src1, *, neg0=0, neg1=0, clamp=0, omod=0):
"""Encode a VOP2 instruction in its VOP3A (e64) form."""
w0 = ((0b110101 << 26) | ((VOP2_E64_BASE + op) << 16) | ((clamp & 1) << 15) | (vdst & 0xff))
w1 = ((src0 & 0x1ff) | ((src1 & 0x1ff) << 9) | ((omod & 0x3) << 27) | ((neg0 & 1) << 29) | ((neg1 & 1) << 30))
return struct.pack('<II', w0, w1)


class Pipeline:
"""Just enough pipeline state for one vector instruction."""

def __init__(self):
self.resources, self.notes, self.modified, self.sampler_heap = {}, set(), set(), False


class Stage(G.Stage):
"""A Stage with no pipeline: enough state for a decoded instruction to be translated."""

def __init__(self):
self.lines, self.sym = [], {}
self.used_s, self.used_v, self.uniform_v = set(), set(), set()
self.exec_known = True
self.exports = {}
self.pipe = Pipeline()


def translate(code):
decoded = G.decode(code)
stage = Stage()
for _offset, _size, name, asm in decoded:
stage.one(name, asm)
return [asm for _o, _s, _n, asm in decoded], ' '.join(stage.lines)


def refused(code):
try:
translate(code)
except G.Unsupported:
return True
return False


# 1. The encoder produces the form the decoder reads; a layout change shows up here first.
asm, emitted = translate(encode_vop2_e64(CNDMASK, 31, V30, V30, neg1=1))
check('encodes and decodes the negated select',
asm == ['v_cndmask_b32_e64 v31, v30, -v30, s0'], repr(asm))

# 2. A negation is the source's sign bit, and it applies to the source it is printed on.
check('negated source flips its sign bit',
emitted == 'v31 = (s0 & 1) ? (v30 ^ 0x80000000u) : v30;', emitted)

asm, emitted = translate(encode_vop2_e64(CNDMASK, 31, V30, V30, neg0=1))
check('negation on the other source',
'v31 = (s0 & 1) ? v30 : (v30 ^ 0x80000000u);' in emitted, emitted)

asm, emitted = translate(encode_vop2_e64(CNDMASK, 31, V30, V30, neg0=1, neg1=1))
check('both sources negated', emitted.count('0x80000000u') == 2, emitted)

# 3. A select without a negation emits exactly what it did before.
asm, emitted = translate(encode_vop2_e64(CNDMASK, 31, V30, V30))
check('no negation is unchanged', emitted == 'v31 = (s0 & 1) ? v30 : v30;', emitted)

# 4. The negation is only modelled where the handler asks for it: another integer instruction carrying the
# same modifier stays refused rather than silently flipping a bit. (`llvm-mc` rejects `-v30` on
# `v_and_b32_e64`, so this encoding is not one an assembler produces; the property under test is that the
# decoder's negated text is refused by a handler that does not model it.)
check('a negation on another integer op stays refused',
refused(encode_vop2_e64(AND_B32, 1, V30, V30, neg1=1)))

# Plain negative inline constants keep their bit patterns even when the printed spelling is identical.
asm, emitted = translate(encode_vop2_e64(CNDMASK, 31, 193, V30))
check('plain inline -1 still translates',
asm == ['v_cndmask_b32_e64 v31, -1, v30, s0'] and
'v31 = (s0 & 1) ? v30 : 0xffffffffu;' in emitted, emitted)
asm, emitted = translate(encode_vop2_e64(CNDMASK, 31, 243, V30))
check('plain inline -1.0 still translates',
asm == ['v_cndmask_b32_e64 v31, -1.0, v30, s0'] and
'v31 = (s0 & 1) ? v30 : 0xbf800000u;' in emitted, emitted)
check('NEG on inline integer remains refused', refused(encode_vop2_e64(CNDMASK, 31, 129, V30, neg0=1)))
check('NEG on inline float remains refused', refused(encode_vop2_e64(CNDMASK, 31, V30, 242, neg1=1)))
check('NEG on literal remains refused', refused(encode_vop2_e64(CNDMASK, 31, V30, 255, neg1=1)
+ struct.pack('<I', 0x12345678)))
# 6. Every edge of the refused immediate ranges, plus the constants just inside them: a mutation moving a
# range boundary by one has to fail one of these.
for edge in (128, 208, 240, 248):
check('NEG on the immediate at %d is refused' % edge,
refused(encode_vop2_e64(CNDMASK, 31, edge, V30, neg0=1)))
asm, emitted = translate(encode_vop2_e64(CNDMASK, 31, 240, V30))
check('plain 0.5 still translates',
asm == ['v_cndmask_b32_e64 v31, 0.5, v30, s0'] and '0x3f000000u' in emitted, emitted)

# 7. The select takes no output modifier; one that reaches it is refused rather than dropped from the text.
check('a clamp on the select is refused', refused(encode_vop2_e64(CNDMASK, 31, V30, V30, clamp=1)))
check('a mul:2 on the select is refused', refused(encode_vop2_e64(CNDMASK, 31, V30, V30, omod=1)))

if failures:
print('FAIL')
for text in failures:
print(' ' + text)
sys.exit(1)
print('PASS')
26 changes: 25 additions & 1 deletion tools/startup/gfx2hlsl.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,16 @@ def decode(code):
raise Unsupported('image_load_mip tfe')
if word1 & (1 << 30):
raise Unsupported('image_load_mip a16')
if name == 'v_cndmask_b32_e64':
# The printed -1 is ambiguous: it can be plain inline -1 or inline 1 with NEG.
# Preserve plain immediates and refuse NEG on immediate data operands by encoding.
word1, = struct.unpack_from('<I', code, off + 4)
for i in range(2):
if not word1 & (1 << (29 + i)):
continue
source = (word1 >> (9 * i)) & 0x1ff
if 128 <= source <= 208 or 240 <= source <= 248 or source == 255:
raise Unsupported('v_cndmask_b32_e64 NEG on an immediate')
out.append((off, n, name, asm))
off += n
last = max((i for i, x in enumerate(out) if x[2] == 's_endpgm'), default=len(out) - 1)
Expand Down Expand Up @@ -217,6 +227,15 @@ def u(self, tok):
except ValueError:
raise Unsupported('operand %r' % tok)

def u_src(self, tok):
"""uint expression for an integer-context source that the disassembler may print negated."""
# In an integer instruction the `-` modifier is the source's sign bit flipped: the same bit
# pattern a float negation produces. Only handlers that model it ask for this; other integer
# sources keep using u(), so an unexpected negation stays a refusal rather than a silent flip.
if tok.startswith('-') and not re.match(r'-[\d.]', tok):
return '(%s ^ 0x80000000u)' % self.u(tok[1:])
return self.u(tok)

def f(self, tok):
"""float expression, with the inline neg/abs operand modifiers."""
neg = False
Expand Down Expand Up @@ -883,8 +902,13 @@ def op_v_mov_b32(self, ops, mods):
self.set_v(reg_range(ops[0])[1], self.u(ops[1]))

def op_v_cndmask_b32(self, ops, mods):
# The select takes no output modifier: a clamp or mul on it would change the value, so a
# modifier that reaches here is refused rather than dropped from the emitted text.
if mods:
raise Unsupported('v_cndmask_b32 with %s' % mods)
mask = self.u(ops[3]) if len(ops) > 3 else 'vcc'
self.set_v(reg_range(ops[0])[1], '(%s & 1) ? %s : %s' % (mask, self.u(ops[2]), self.u(ops[1])))
self.set_v(reg_range(ops[0])[1],
'(%s & 1) ? %s : %s' % (mask, self.u_src(ops[2]), self.u_src(ops[1])))

def op_v_interp_p1_f32(self, ops, mods):
self.note_attr(ops[2], 'linear')
Expand Down
Loading