Skip to content
Open
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
10 changes: 10 additions & 0 deletions tests/cmake/startup_gfx2hlsl_late_gaps.cmake
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
if(EXISTS "${INTAKE_PYTHON}")
find_program(X2W_GFX_GAPS_LLVM_MC NAMES llvm-mc llvm-mc-19 llvm-mc-15)
if(X2W_GFX_GAPS_LLVM_MC)
foreach(family IN ITEMS dpp_quad_broadcast sgpr_spill)
add_test(NAME startup_gfx2hlsl_${family}_late_gaps COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_${family}_check.py"
late-gaps "${X2W_GFX_GAPS_LLVM_MC}")
endforeach()
endif()
endif()
32 changes: 32 additions & 0 deletions tests/startup_gfx2hlsl_dpp_quad_broadcast_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

(no arguments) translation controls and refusals, pure Python
binary <llvm-mc> assemble the pixel fixtures with llvm-mc (gfx1013) and compare the words
late-gaps <llvm-mc> assemble and translate reverse-subtract DPP controls
draw <dxc> <offscreen_check> <warp|hardware> [fxc]
compile the pixel fixtures with DXC ps_6_0, draw 16 x 16 pixels and compare
every pixel with a CPU reference (with fxc: also the FXC refusal). The vertex
Expand Down Expand Up @@ -304,6 +305,35 @@ def check_binary(llvm_mc):
check('llvm-mc assembles the %s fixture to the same words' % kind, assemble(llvm_mc, source) == words)


def check_late_gaps(llvm_mc):
prefix = ('s_wqm_b64 exec, exec\nv_cvt_f32_u32_e32 v1, v0\n'
'v_add_f32_e32 v2, 1.0, v1\n')
suffix = 'exp mrt0 v3, v3, v3, v3 done vm\ns_endpgm\n'
cases = (
('broadcast', '[0,0,0,0]', 's_mov_b64 exec, exec\n', 'QuadReadLaneAt(v1, 0u)',
'outside the entry prefix'),
('pair after a target', '[0,0,2,2]', 's_branch 1\ns_nop 0\ns_mov_b32 exec_lo, exec_lo\n',
'x2w_lane == 0u ? x2w_q0 : x2w_lane == 1u ? x2w_q0 : x2w_lane == 2u ? x2w_q2 : x2w_q2',
'outside straight-line pixel code with a whole-quad exec mask'),
)
for label, perm, middle, quad, refusal in cases:
op = 'v_subrev_f32_dpp v3, v1, v2 quad_perm:' + perm + DPP + ' bound_ctrl:1\n'
without_wqm = 'without s_wqm exec, exec' if label == 'broadcast' else refusal
for setup, body, expected in (
(prefix, middle, None),
(prefix, middle + 's_mov_b64 exec, 0\n', refusal),
(prefix.removeprefix('s_wqm_b64 exec, exec\n'), middle, without_wqm),
):
words = assemble(llvm_mc, setup + body + op + suffix)
try:
text = G.Pipeline(VS_WORDS, words, root_blob(), ps_hw_inputs=PACKED).hlsl_ps()
except G.Unsupported as why:
check(label + ' refusal matches the EXEC proof', expected is not None and expected in str(why), str(why))
else:
check(label + ' reads SRC0 from the quad and subtracts it from SRC1',
expected is None and quad in text and 'v3 = U(F(v2) - F(v256));' in text, text)


def words_file(directory, name, words):
path = directory / ('%s.bin' % name)
path.write_bytes(struct.pack('<%dI' % len(words), *words))
Expand Down Expand Up @@ -364,6 +394,8 @@ def main():
controls()
elif sys.argv[1] == 'binary':
check_binary(*sys.argv[2:])
elif sys.argv[1] == 'late-gaps':
check_late_gaps(*sys.argv[2:])
elif sys.argv[1] == 'draw':
check_draw(*sys.argv[2:])
else:
Expand Down
50 changes: 50 additions & 0 deletions tests/startup_gfx2hlsl_sgpr_spill_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

(no arguments) translation controls, pure Python
binary <llvm-mc> reassemble the fixture source and compare it with the words built here
late-gaps <llvm-mc> assemble and translate the alias, reuse and descriptor controls
draw <dxc> <offscreen_check> <warp|hardware> [fxc]
compile the translated pair, draw 16 x 16 pixels and compare every pixel
with the reference below
Expand Down Expand Up @@ -209,6 +210,53 @@ def check_binary(llvm_mc):
check('llvm-mc assembles the fixture to the same words', assemble(llvm_mc, FIXTURE_TEXT) == FIXTURE_WORDS)


def check_late_gaps(llvm_mc):
write8 = 'v_writelane_b32 v10, 3, 8\n'
read8 = 'v_readlane_b32 s4, v10, 8\n'
write40 = 'v_writelane_b32 v10, 5, 40\n'
read40 = 'v_readlane_b32 s5, v10, 40\n'
reloads = 'v_mov_b32_e32 v1, s4\nv_mov_b32_e32 v2, s5\n'
export = 'exp mrt0 v1, v2, v1, v2 done vm\ns_endpgm\n'
reuse = write8 + read8 + 'v_mov_b32_e32 v10, 11\n'
reuse_end = 'v_mov_b32_e32 v1, s4\nexp mrt0 v1, v10, v1, v10 done vm\ns_endpgm\n'
desc = 's_load_dwordx4 s[16:19], s[8:9], 0x20\ns_waitcnt lgkmcnt(0)\n'
spill_desc = ('v_writelane_b32 v10, s16, 3\ns_mov_b32 s16, 0\n'
'v_readlane_b32 s16, v10, 3\nbuffer_load_dword v1, off, s[16:19], 0\n'
's_waitcnt vmcnt(0)\nexp mrt0 v1, v1, v1, v1 done vm\ns_endpgm\n')

def translate(source):
return pipeline(assemble(llvm_mc, source))

text = translate(write8 + read8 + write40 + read40 + reloads + export).hlsl_ps()
check('aliasing lanes each reload their latest write in both wave sizes',
all(line in text for line in ('sp10_8 = 0x00000003u;', 'sp10_40 = 0x00000005u;',
's4 = sp10_8;', 's5 = sp10_40;')))
text = translate(reuse + reuse_end).hlsl_ps()
check('a spill VGPR is reused after a full overwrite', 's4 = sp10_8;' in text and 'v10 = 0x0000000bu;' in text)
pipe = translate(desc + spill_desc)
text = pipe.hlsl_ps()
check('a reloaded descriptor word keeps its table binding without a numeric slot assignment',
'srv 0 buf table 0 32' in pipe.manifest().splitlines() and
's16 = sp10_3;' not in text and 'sp10_3 = 0;' in text)

for label, source, reason in (
('alias clobbers a reload', write8 + write40 + read8 + read40 + reloads + export, 'one slot in wave32'),
('reload after vector overwrite', reuse + read8 + reuse_end, 'also used as a vector'),
('vector read before overwrite', write8 + read8 + 'v_mov_b32_e32 v2, v10\n' + reuse_end,
'also used as a vector'),
('EXEC can widen after overwrite', reuse + 's_wqm_b64 exec, exec\n' + reuse_end, 'also used as a vector'),
('copied descriptor word without local load proof',
desc + 's_mov_b32 s20, s16\n' + spill_desc.replace('v10, s16, 3', 'v10, s20, 3'),
'holds a lane mask or descriptor'),
):
try:
translate(source)
except G.Unsupported as why:
check(label, reason in str(why), str(why))
else:
check(label, False, 'accepted')


def words_file(directory, name, words):
path = directory / ('%s.bin' % name)
path.write_bytes(struct.pack('<%dI' % len(words), *words))
Expand Down Expand Up @@ -266,6 +314,8 @@ def main():
mode, *args = sys.argv[1:]
if mode == 'binary':
check_binary(*args)
elif mode == 'late-gaps':
check_late_gaps(*args)
elif mode == 'draw':
controls()
check_draw(*args)
Expand Down
70 changes: 54 additions & 16 deletions tools/startup/gfx2hlsl.py
Original file line number Diff line number Diff line change
Expand Up @@ -1111,6 +1111,11 @@ def writes_exec(name, ops):
return 'saveexec' in name or 'wrexec' in name or name.startswith(('v_cmpx', 's_movreld'))


def exec_self_move(name, ops, mods):
return not mods and ((name == 's_mov_b64' and ops == ['exec', 'exec']) or
(name == 's_mov_b32' and ops == ['exec_lo', 'exec_lo']))


# In wave32 VCC is vcc_lo alone and vcc_hi is a free scalar register that compilers allocate like any other (RDNA 2
# ISA, "VCC": in wave32 only VCC_LO is the condition mask). The translator models it as an ordinary SGPR the program
# never names, taken from the top of the 106 (beyond the user-data and system registers set at entry).
Expand Down Expand Up @@ -4951,8 +4956,8 @@ def quad_flow_refusals(self, branches, targets):
the wave as one: its scalar branches are wave-wide, and the quad is whole when EXEC is the s_wqm mask. A
read is kept when, on every path to it:
- the s_wqm exec, exec that proved whole-quad EXEC ran first: it sits before every branch and target;
- no other instruction that can write EXEC reaches it (so EXEC is still that mask and every VGPR write ran
on all four lanes, helper lanes included);
- no instruction that can change EXEC reaches it (so EXEC is still that mask and every VGPR write ran
on all four lanes, helper lanes included). A move of EXEC to itself leaves the mask intact;
- every conditional branch that reaches it is wave-uniform (SCC proven uniform by the translator), or an
execz/execnz branch, whose EXEC is the whole-quad mask by the rule above and so never taken. A vccz/vccnz
branch, or SCC from lane data, can split a quad, and the read is refused.
Expand Down Expand Up @@ -4981,6 +4986,7 @@ def reaches(src, dst):
# No branch or target (a dead read behind an early s_endpgm): nothing for the s_wqm to precede.
first = min([off for off, _ in branches] + list(targets), default=float('inf'))
writers = [off for off, _n, name, asm in self.ins if writes_exec(name, parse(asm)[1])
and not exec_self_move(*parse(asm))
and not (re.sub(r'_e(32|64)$', '', name) in ('s_wqm_b32', 's_wqm_b64')
and parse(asm)[1] in (['exec', 'exec'], ['exec_lo', 'exec_lo']))]
out = []
Expand Down Expand Up @@ -5218,6 +5224,8 @@ def _lower(self, base, asm, ops, mods):
ops[0] == 'exec_hi' or not (base in SCA or base.startswith('v_cmp') or
(base in ('s_cselect_b32', 's_cselect_b64') and ops[0] == 'exec'))):
raise Unsupported('%s into %s after a fetch call' % (base, ops[0]))
if getattr(self, 'kind', None) == 'ps' and exec_self_move(base, ops, mods):
return None # Neither EXEC nor SCC changes.
if base in ('s_wqm_b32', 's_wqm_b64'):
if ops[0] in ('exec', 'exec_lo') and ops[1:] == ops[:1] and getattr(self, 'exec_known', False):
self.wqm_exec = True # every lane of a touched quad is now active, helper lanes included
Expand Down Expand Up @@ -9391,10 +9399,11 @@ def op_v_readfirstlane_b32(self, ops, mods):
# and `v_readlane_b32 sD, vN, k` reads it back (AMD RDNA 2 ISA reference, VOP3 lane ops; LLVM 15
# AMDGPU spill lowering). Both ignore EXEC. With a constant k and a VGPR that no other instruction
# touches, vN is only a table of scalar slots, so one scalar variable per (vN, k) is an exact model
# and no other lane is ever read. Anything else keeps the one-lane model out of reach and is refused.
# and no other lane is ever read. Straight-line pixel code can also reuse the register after a full overwrite
# at an unchanged EXEC mask, once no lane reads or writes remain.
# Lanes 0..63 cover a wave64 program. A wave32 program uses only bits 4:0 of the lane select (RDNA 2 ISA,
# v_readlane/v_writelane: the lane is taken modulo the wave size), so k and k + 32 name one slot there and two in
# wave64; the translator does not know the wave size, so a VGPR whose lanes include such a pair is refused.
# wave64. With unknown wave size, each reload of either lane must reach the same write in both sizes.
# Slot 57 mesh is wave64 (#2127). Vertex stages use the same model: the two instructions touch no other lane and no stage input.
#
# With branches the slot variable is assigned on the pixel's own path, while the hardware slot holds the last
Expand All @@ -9408,6 +9417,7 @@ def op_v_readfirstlane_b32(self, ops, mods):
# Compute stages (cs) use the same proof, branches included. A spilled descriptor or pointer word (SPILL_SYMBOLS) is a
# symbol with no run-time value: the slot carries the symbol, the reload restores it, and the word keeps the
# provenance the formatted loads require (formatted_descriptor_from_block follows a reload to the writes that supply it).
# Straight-line pixel stages can spill descriptor words whose local table load passes that same proof.
# Lane masks (compute only). The translator models a lane mask (vcc_lo, or an SGPR in self.masks) per invocation
# as that invocation's own bit: `vcc` / `sN` hold bit 0 of the wave mask, and a v_cmp stores `w` (all lanes active)
# or `exec & w`, so an inactive lane's bit is already 0 in the variable. `v_writelane_b32 vN, M, k` copies the whole
Expand Down Expand Up @@ -9558,34 +9568,58 @@ def spill_operands(self, name, ops, mods):
return vreg[1], sreg, lane

def require_spill_lanes_apart(self, n, name):
"""Refuse when two lanes of spill VGPR v<n> differ by 32: one slot in wave32, two in wave64."""
lanes = set()
"""For a pair that may alias, prove in straight-line code that its last write matches each read."""
lanes, observed, ambiguous = set(), set(), set()
last_write = {}
for _, _, op, asm in getattr(self, 'ins', ()):
if re.sub(r'_e(32|64)$', '', op) not in ('v_writelane_b32', 'v_readlane_b32'):
base = re.sub(r'_e(32|64)$', '', op)
if base not in ('v_writelane_b32', 'v_readlane_b32'):
continue
ops = parse(asm)[1]
if len(ops) == 3 and n in [r[1] for r in map(reg_range, ops[:2]) if r and r[0] == 'v']:
try:
lanes.add(int(ops[2], 0))
lane = int(ops[2], 0)
except ValueError:
continue # a register lane is refused where it is read
lanes.add(lane)
slot = lane & 31
if base == 'v_writelane_b32':
last_write[slot] = lane
elif last_write.get(slot) == lane:
observed.add(slot)
else:
ambiguous.add(slot)
for lane in lanes:
if lane + 32 in lanes:
# Keep refusing colliding pairs with no observed reload to prove.
if lane + 32 in lanes and (not self.quad_flow_straight() or lane not in observed or lane in ambiguous):
raise Unsupported('%s: v%d lanes %d and %d are one slot in wave32 and two in wave64'
% (name, n, lane, lane + 32))

def require_spill_only(self, n, name):
"""Refuse unless every instruction naming v<n> is a lane write or read of it."""
"""Keep the slot model isolated from any ordinary vector reads of the spilled values."""
# Mesh: scan the pre-skeleton program. The accepted group-memory exchanges rewrite to
# x2w_mesh_* / s_nop, which would hide ordinary use of exchange VGPRs (v5 and temps).
source = getattr(self, 'mesh_source_ins', None) or getattr(self, 'ins', ())
first_vector = None
for _, _, op, asm in source:
if re.sub(r'_e(32|64)$', '', op) in ('v_writelane_b32', 'v_readlane_b32'):
refs = re.findall(r'\bv\[(\d+):(\d+)\]|\bv(\d+)\b', asm)
if not any(int(lo or single) <= n <= int(hi or single) for lo, hi, single in refs):
continue
for lo, hi, single in re.findall(r'\bv\[(\d+):(\d+)\]|\bv(\d+)\b', asm):
a, b = (int(lo), int(hi)) if lo else (int(single), int(single))
if a <= n <= b:
raise Unsupported('%s: v%d is also used as a vector (%s)' % (name, n, op))
base = re.sub(r'_e(32|64)$', '', op)
if base in ('v_writelane_b32', 'v_readlane_b32'):
if first_vector is not None:
break
elif first_vector is None:
first_vector = op
_, ops, mods = parse(asm)
# The first ordinary use must overwrite every lane that later vector instructions can observe.
if (self.kind != 'ps' or not self.quad_flow_straight() or base != 'v_mov_b32' or mods or
len(ops) != 2 or ops[0] != 'v%d' % n or re.search(r'\bv(?:\d|\[)', ops[1]) or
any(writes_exec(other, parse(text)[1]) for _, _, other, text in source)):
break
else:
return
raise Unsupported('%s: v%d is also used as a vector (%s)' % (name, n, first_vector))

def op_v_writelane_b32(self, ops, mods):
n, src, lane = self.spill_operands('v_writelane_b32', ops, mods)
Expand All @@ -9605,6 +9639,10 @@ def op_v_writelane_b32(self, ops, mods):
else:
held = self.sym.get(src[1]) or ('',)
carried = held[0] in self.SPILL_SYMBOLS and getattr(self, 'kind', None) == 'cs'
if (self.kind == 'ps' and held[0] == 'desc' and held[1][0] == 'table' and names_one_value(held)
and self.quad_flow_straight() and not getattr(self, 'past_entry', True)
and self.formatted_descriptor_from_block(src, held)):
carried = True
mask = self.spills_lane_masks() and src[1] in self.masks
if mask:
if src[1] in self.join_masks:
Expand All @@ -9613,7 +9651,7 @@ def op_v_writelane_b32(self, ops, mods):
elif not carried and (self.is_lane_mask(ops[1]) or held[0] not in ('', 'const', 'ud', 'fixed_buffer_word')):
raise Unsupported('v_writelane_b32 source s%d holds a lane mask or descriptor' % src[1])
elif carried:
# A descriptor or pointer word of a compute stage: the slot holds the symbol itself, so the reload
# The slot holds the descriptor or pointer symbol itself, so the reload
# restores the same word. Nothing is emitted: the translation has no run-time value for it.
if not names_one_value(held):
raise Unsupported('v_writelane_b32 source s%d holds a modified descriptor or pointer word' % src[1])
Expand Down
Loading