mirror of
https://github.com/ProjectLeonida/mandy.git
synced 2026-12-06 13:58:43 +00:00
d3d12/vulkan + rdna2spirv: staged VRAM arena, DMA readback batching, parallel shadows, stream-pool fix & wave64 perf (RT-ARENA-DEVICE-LOCAL-STAGED)
729 lines
34 KiB
Python
729 lines
34 KiB
Python
"""Which scalar registers hold a lane mask?
|
|
|
|
On hardware a lane mask is one register for the whole wave, a bit per lane. The translator runs one invocation
|
|
per lane and keeps only that lane's bit in the register (all ones or zero), which is all that and/or/not, selects
|
|
and EXEC need. A few instructions look at the mask as a whole instead: s_bcnt1 (how many lanes), s_ff1 (the first
|
|
lane), v_mbcnt (how many lanes below this one). For those the translator has to collect the other lanes' bits.
|
|
The same instructions also run on plain 64-bit data, such as a light mask read from a buffer, and nothing in the
|
|
instruction says which of the two it has, so this module works it out from what wrote the register.
|
|
|
|
masks, writes = analyse(blocks, succ) # blocks: lists of instructions; succ: successor block numbers per block
|
|
masks[id(ins)] # dict mapping each register holding a lane mask on every path to ins
|
|
# (SGPR number, "vcc", ("lane", vgpr, lane) parked in a VGPR lane, or
|
|
# ("v", vgpr) passing through a VGPR) to its kind (MASK, MASK_LO, MASK_HI)
|
|
id(ins) in writes # ins computes a mask into a VGPR (a plain copy does not count)
|
|
|
|
A register counts as a mask only if every path to the instruction wrote a mask to it. Anything else is treated
|
|
as data, which is what the translator did for all of them before.
|
|
|
|
Parked masks: a shader that runs out of SGPRs moves some into single lanes of a spare VGPR (v_writelane_b32) and
|
|
fetches them back later (v_readlane_b32). When the SGPR is a saved EXEC, the value that comes back has to be this
|
|
lane's bit again, not the bit of the lane it was parked in.
|
|
|
|
Masks through a VGPR: the compiler does some scalar work in the vector unit, such as an OR of three SGPRs
|
|
(v_mov_b32 / v_or3_b32, then v_readfirstlane_b32 to get the scalar back). On hardware every lane computes the same
|
|
whole mask and the first lane's copy is read. Here each lane computes its own bit, so it has to read its own
|
|
copy, and it has to compute it whether or not it is active. A plain copy of a mask (v_mov_b32) is different:
|
|
it moves an already-computed value, so it is an ordinary VALU write and inactive lanes keep the old VGPR
|
|
(SHADER-21 part 2).
|
|
"""
|
|
|
|
MASK = "mask" # full lane mask (64-bit pair, vcc, or wave32 single register)
|
|
MASK_LO = "mask_lo" # low 32-bit half of a 64-bit lane mask (lanes 0-31)
|
|
MASK_HI = "mask_hi" # high 32-bit half of a 64-bit lane mask (lanes 32-63)
|
|
MASK_KINDS = (MASK, MASK_LO, MASK_HI)
|
|
EITHER = "either" # a constant 0 or -1: no lanes or all lanes, and the same bits when read as data
|
|
# Absent from the state: data.
|
|
|
|
COPIES = ("s_mov_b", "s_not_b", "s_wqm_b")
|
|
BITWISE = ("s_and_b", "s_or_b", "s_xor_b", "s_andn2_b", "s_orn2_b", "s_nand_b", "s_nor_b", "s_xnor_b",
|
|
"s_cselect_b")
|
|
NO_DESTINATION = ( # their first operand (if any) is a source, not a written register
|
|
"s_cmp", "s_bitcmp", "v_cmpx", "s_set", "s_rfe",
|
|
"s_store_", "s_buffer_store_", "s_dcache_", "s_icache_",
|
|
"s_sendmsg", "s_branch", "s_cbranch", "s_waitcnt", "s_nop", "s_sleep", "s_barrier", "s_endpgm",
|
|
"exp",
|
|
"buffer_store", "tbuffer_store", "global_store", "flat_store", "image_store", "ds_write",
|
|
)
|
|
DS_HAS_DST = ("ds_read", "ds_swizzle", "ds_permute", "ds_bpermute",
|
|
"ds_append", "ds_consume", "ds_ordered_count", "ds_nop")
|
|
VGPR_REL_DST = ("v_movreld_b32", "v_movrelsd_b32", "v_movrelsd_2_b32", "v_swaprel_b32")
|
|
SGPR_REL_DST = ("s_movreld_b32", "s_movreld_b64", "s_movrelsd_2_b32")
|
|
VECTOR_BITWISE = ("v_mov_b32", "v_or3_b32", "v_or_b32", "v_and_b32", "v_and_or_b32",
|
|
"v_xor_b32", "v_xor3_b32", "v_xnor_b32", "v_bfi_b32", "v_not_b32")
|
|
|
|
|
|
def base_op(op):
|
|
for suffix in ("_e32", "_e64", "_sdwa", "_dpp"):
|
|
if op.endswith(suffix):
|
|
return op[:-len(suffix)]
|
|
return op
|
|
|
|
|
|
def kind(state, a, wave64=True):
|
|
if a["k"] == "special":
|
|
t = a.get("t", "")
|
|
if t in ("exec_lo", "exec_hi", "exec"):
|
|
if not wave64:
|
|
return MASK
|
|
return MASK_LO if t == "exec_lo" else (MASK_HI if t == "exec_hi" else MASK)
|
|
if t == "vcc" or (not wave64 and t == "vcc_lo"):
|
|
return state.get("vcc")
|
|
if not wave64 and t == "vcc_hi":
|
|
return state.get("vcc_hi")
|
|
if t in ("vcc_lo", "vcc_hi"):
|
|
vk = state.get("vcc")
|
|
if vk in MASK_KINDS:
|
|
return MASK_LO if t == "vcc_lo" else MASK_HI
|
|
return vk if t == "vcc_lo" else None
|
|
return None
|
|
if a["k"] == "sgpr":
|
|
n = a.get("n", 1)
|
|
ks = [state.get(a["r"] + i) for i in range(n)]
|
|
if None in ks:
|
|
return None
|
|
if n == 2 and any(k in MASK_KINDS for k in ks):
|
|
return MASK
|
|
return ks[0] if len(set(ks)) == 1 else None
|
|
if a["k"] == "vgpr" and a.get("n", 1) == 1:
|
|
return state.get(("v", a["r"]))
|
|
if a["k"] == "imm" and a["v"] in (0, -1):
|
|
return EITHER
|
|
return None
|
|
|
|
|
|
def put(state, a, k, wave64=True):
|
|
if a["k"] == "sgpr":
|
|
n = a.get("n", 1)
|
|
if k == MASK and n == 2:
|
|
state[a["r"]] = MASK_LO
|
|
state[a["r"] + 1] = MASK_HI
|
|
return
|
|
regs = [a["r"] + i for i in range(n)]
|
|
elif a["k"] == "slist":
|
|
regs = [
|
|
r if isinstance(r, int) else ("vcc_hi" if (r == "vcc_hi" and not wave64) else "vcc")
|
|
for r in a["r"]
|
|
]
|
|
elif a["k"] == "special" and (a.get("t") == "vcc" or (not wave64 and a.get("t") == "vcc_lo")):
|
|
regs = ["vcc"]
|
|
elif a["k"] == "special" and not wave64 and a.get("t") == "vcc_hi":
|
|
regs = ["vcc_hi"]
|
|
elif a["k"] == "special" and a.get("t") in ("vcc_lo", "vcc_hi"):
|
|
# A mask / 0 / -1 half-write updates that half of %vcc in wave64 (put_mask), keeping VCC a lane mask;
|
|
# a plain-data half-write (k is None) ends VCC's life as one lane mask.
|
|
if k is not None and state.get("vcc") in MASK_KINDS:
|
|
state["vcc"] = MASK
|
|
elif a.get("t") == "vcc_lo" and k is not None:
|
|
state["vcc"] = k
|
|
else:
|
|
state.pop("vcc", None)
|
|
return
|
|
else:
|
|
return
|
|
for r in regs:
|
|
if k is None:
|
|
state.pop(r, None)
|
|
else:
|
|
state[r] = k
|
|
|
|
|
|
def _maskable_b32(x):
|
|
return x["k"] in ("sgpr", "imm") or (
|
|
x["k"] == "special" and (x.get("t", "").startswith(("exec", "vcc")) or x.get("t") in ("null", "m0", "scc", "src_scc"))
|
|
)
|
|
|
|
|
|
def lane_slot(vgpr, lane, wave64=True):
|
|
"""State key for a mask parked in one lane of a VGPR, or None unless both operands are plain."""
|
|
if vgpr["k"] != "vgpr" or vgpr.get("n", 1) != 1 or lane["k"] != "imm":
|
|
return None
|
|
if vgpr.get("abs") or vgpr.get("neg") or lane.get("abs") or lane.get("neg"):
|
|
return None
|
|
return ("lane", vgpr["r"], lane["v"] & (63 if wave64 else 31))
|
|
|
|
|
|
def wave32_vcc_pair_op(op, args):
|
|
"""Data moves between a scalar pair and VCC, or their 64-bit XOR into VCC."""
|
|
if op not in ("s_mov_b64", "s_xor_b64"):
|
|
return False
|
|
pairs = [a.get("k") == "sgpr" and a.get("n") == 2 for a in args]
|
|
vcc = [a.get("t") == "vcc" for a in args]
|
|
if op == "s_mov_b64":
|
|
return len(args) == 2 and ((vcc[0] and pairs[1]) or (pairs[0] and vcc[1]))
|
|
return len(args) == 3 and vcc[0] and ((vcc[1] and pairs[2]) or (pairs[1] and vcc[2]))
|
|
|
|
|
|
def step(state, ins, wave64=True):
|
|
"""Update `state` (register -> MASK | MASK_LO | MASK_HI | EITHER) for one instruction. True if it writes a mask to a VGPR.
|
|
|
|
`wave64` False: the program runs in 32-lane waves, where a 64-bit s_bfm_b64 result can't be a lane mask."""
|
|
op, a = base_op(ins["op"]), ins["args"]
|
|
if not a or op.startswith(NO_DESTINATION):
|
|
return
|
|
if op == TO_DATA: # the wave's bits of a mask: data, the same in every lane
|
|
put(state, a[0], None, wave64)
|
|
return
|
|
if ins.get("vcc_data_pair"):
|
|
# Gen materializes both scalar words (including a source mask's lane bits).
|
|
put(state, a[0], None, wave64)
|
|
if a[0].get("t") == "vcc":
|
|
state.pop("vcc_hi", None)
|
|
return
|
|
mods = ins.get("mods", ())
|
|
if op.startswith(("buffer_load", "tbuffer_load")) and "lds" in mods:
|
|
return
|
|
if op.startswith(("buffer_atomic", "global_atomic", "flat_atomic", "image_atomic",
|
|
"s_atomic", "s_buffer_atomic")) and "glc" not in mods:
|
|
return
|
|
if op.startswith("ds_") and not op.startswith(DS_HAS_DST) and "_rtn" not in op:
|
|
return
|
|
if op == "v_readfirstlane_b32" and len(a) == 2: # sD = vS, the same in every lane
|
|
put(state, a[0], kind(state, a[1], wave64), wave64)
|
|
return
|
|
if op == "v_writelane_b32" and len(a) == 3: # vD[lane] = sS
|
|
slot = lane_slot(a[0], a[2], wave64)
|
|
if slot is not None:
|
|
state.pop(("v", a[0]["r"]), None)
|
|
k = kind(state, a[1], wave64)
|
|
if k is None:
|
|
state.pop(slot, None)
|
|
else:
|
|
state[slot] = k
|
|
return
|
|
if op == "v_readlane_b32" and len(a) == 3: # sD = vS[lane]
|
|
put(state, a[0], state.get(lane_slot(a[1], a[2], wave64)), wave64)
|
|
return
|
|
if op.startswith("v_cmp"):
|
|
# Handle v_cmp before VGPR clobber (defensive for 2-operand forms with implicit vcc).
|
|
put(state, {"k": "special", "t": "vcc"} if len(a) == 2 else a[0], MASK, wave64)
|
|
return
|
|
if op == "v_swap_b32":
|
|
written = set()
|
|
for x in a[:2]:
|
|
if x["k"] == "vgpr":
|
|
written.update(range(x["r"], x["r"] + x.get("n", 1)))
|
|
for key in [k for k in state if isinstance(k, tuple) and k[1] in written]:
|
|
del state[key]
|
|
return
|
|
if op in VGPR_REL_DST:
|
|
bases = [x["r"] for x in (a[:2] if op == "v_swaprel_b32" else a[:1]) if x["k"] == "vgpr"]
|
|
if bases:
|
|
lo = min(bases)
|
|
for key in [k for k in state if isinstance(k, tuple) and k[1] >= lo]:
|
|
del state[key]
|
|
return
|
|
if op in SGPR_REL_DST:
|
|
if a[0]["k"] == "sgpr":
|
|
lo = a[0]["r"]
|
|
for key in [k for k in state if isinstance(k, int) and k >= lo]:
|
|
del state[key]
|
|
return
|
|
if a[0]["k"] == "vgpr": # any other write to a VGPR ends what was parked in it
|
|
# A mask only when every source is one (or a constant 0 / -1) on every path: no EITHER for VGPRs, whose
|
|
# plain writes skip inactive lanes. The sources are looked at first: the destination can be one of them.
|
|
# SDWA/DPP or modified forms alter sub-dwords or read other lanes, so they are never plain mask ops.
|
|
plain_valu = (op in VECTOR_BITWISE and a[0].get("n", 1) == 1
|
|
and not ins["op"].endswith(("_sdwa", "_dpp", "_dpp8"))
|
|
and not mods
|
|
and not any(x.get("neg") or x.get("abs") or x.get("sext") for x in a[1:]))
|
|
kinds = [kind(state, x, wave64) for x in a[1:]] if plain_valu else [None]
|
|
written = range(a[0]["r"], a[0]["r"] + a[0].get("n", 1))
|
|
for key in [k for k in state if isinstance(k, tuple) and k[1] in written]:
|
|
del state[key]
|
|
if None not in kinds and any(k in MASK_KINDS for k in kinds):
|
|
ms = {k for k in kinds if k in MASK_KINDS}
|
|
state[("v", a[0]["r"])] = ms.pop() if len(ms) == 1 else MASK
|
|
# A plain copy (v_mov_b32) is an ordinary VALU write: inactive lanes keep the old
|
|
# VGPR (SHADER-21 part 2). Only per-lane mask computations take the all-lanes store,
|
|
# because whole-wave readers (wave_mask, v_readfirstlane) read every lane's bit.
|
|
return op != "v_mov_b32"
|
|
if "_saveexec_b" in op or "_wrexec_b" in op:
|
|
put(state, a[0], MASK_LO if (wave64 and op.endswith("_b32")) else MASK, wave64)
|
|
elif wave64 and op == "s_bitreplicate_b64_b32" and a[0].get("t") == "vcc":
|
|
put(state, a[0], MASK, wave64)
|
|
elif op == "s_bfm_b64":
|
|
# In wave32 code it is 64-bit data, e.g. the first two words of an S# built in place (the pipeline library's
|
|
# wave32 compute programs: s_bfm_b64 s[88:89], 2, 54); rdna2spirv computes the value there.
|
|
put(state, a[0], MASK if wave64 else None, wave64)
|
|
elif op.startswith(COPIES) and len(a) > 1:
|
|
k = kind(state, a[1], wave64)
|
|
dst_t = a[0].get("t") if a[0]["k"] == "special" else None
|
|
if k in (None, EITHER) and op.endswith("b64") and dst_t in ("vcc", "vcc_lo") and a[1]["k"] == "imm":
|
|
k = MASK
|
|
elif op == "s_not_b32" and dst_t in ("vcc", "vcc_lo") and _maskable_b32(a[1]):
|
|
k = MASK
|
|
elif op == "s_not_b32" and dst_t == "vcc_hi" and wave64 and state.get("vcc") in MASK_KINDS and _maskable_b32(a[1]):
|
|
return
|
|
put(state, a[0], k, wave64)
|
|
elif op.startswith(BITWISE):
|
|
kinds = [kind(state, x, wave64) for x in a[1:]]
|
|
ms = {k for k in kinds if k in MASK_KINDS}
|
|
dst_t = a[0].get("t") if a[0]["k"] == "special" else None
|
|
if None not in kinds:
|
|
if op.endswith("b32") and dst_t == "vcc_hi" and wave64 and state.get("vcc") in MASK_KINDS:
|
|
return
|
|
fallback = MASK if op.endswith("b64") and dst_t in ("vcc", "vcc_lo") else EITHER
|
|
put(state, a[0], (ms.pop() if len(ms) == 1 else MASK) if ms else fallback, wave64)
|
|
elif op.endswith("b64") and (ms or dst_t in ("vcc", "vcc_lo")) and \
|
|
all(k is not None or x["k"] == "imm" for k, x in zip(kinds, a[1:])):
|
|
put(state, a[0], (ms.pop() if len(ms) == 1 else MASK) if ms else MASK, wave64)
|
|
elif op.endswith("b32") and dst_t in ("vcc", "vcc_lo") and all(_maskable_b32(x) for x in a[1:]):
|
|
put(state, a[0], MASK, wave64)
|
|
elif op.endswith("b32") and dst_t == "vcc_hi" and wave64 and state.get("vcc") in MASK_KINDS and \
|
|
all(_maskable_b32(x) for x in a[1:]):
|
|
return
|
|
else:
|
|
put(state, a[0], None, wave64)
|
|
elif op in ("s_bitset0_b32", "s_bitset1_b32"):
|
|
dk = kind(state, a[0], wave64)
|
|
dst_t = a[0].get("t") if a[0]["k"] == "special" else None
|
|
if dk in MASK_KINDS:
|
|
if wave64 and dst_t in ("vcc_lo", "vcc_hi") and state.get("vcc") in MASK_KINDS:
|
|
return
|
|
put(state, a[0], dk, wave64)
|
|
else:
|
|
put(state, a[0], None, wave64)
|
|
else:
|
|
put(state, a[0], None, wave64)
|
|
if ((op.startswith("v_") and "_co_" in op)
|
|
or op in ("v_mad_u64_u32", "v_mad_i64_i32", "v_div_scale_f32", "v_div_scale_f64")) and len(a) > 1:
|
|
put(state, a[1], MASK, wave64) # carry/sign/scale lane mask of VOP3b ops
|
|
|
|
|
|
def parked(blocks, masks, wave64=True):
|
|
"""The (vgpr, lane) slots some v_readlane_b32 fetches a mask from, given analyse()'s result."""
|
|
found = set()
|
|
for blk in blocks:
|
|
for ins in blk:
|
|
a = ins["args"]
|
|
if base_op(ins["op"]) == "v_readlane_b32" and len(a) == 3:
|
|
slot = lane_slot(a[1], a[2], wave64)
|
|
if slot in masks.get(id(ins), ()):
|
|
found.add(slot[1:])
|
|
return sorted(found)
|
|
|
|
|
|
VGPR_MOVREL = ("v_movrels_b32", "v_movreld_b32", "v_movrelsd_b32", "v_movrelsd_2_b32", "v_swaprel_b32")
|
|
|
|
|
|
def scalar_spills(blocks, succ=None, wave64=True):
|
|
"""The (vgpr, lane) slots of pure scalar-spill VGPRs: VGPRs touched only by constant-lane v_writelane_b32
|
|
(non-VGPR source) and constant-lane v_readlane_b32, never read or written as a vector operand, never aliased by
|
|
v_movrel*/v_swaprel_b32, and with every v_readlane_b32 lane definitely written on all paths before it is read.
|
|
|
|
On RDNA2 hardware v_writelane_b32 / v_readlane_b32 ignore EXEC and access physical lane K even when lane K is
|
|
inactive (e.g. a small triangle launching fewer than 32 fragment lanes or after a dither/alpha discard). In
|
|
Vulkan SPIR-V, OpGroupNonUniformShuffle from an inactive invocation is undefined and reads stale VGPR bits.
|
|
Parking these slots in the %sgpr array makes every wave32/wave64 stage exact regardless of active lanes."""
|
|
mask = 63 if wave64 else 31
|
|
written = {}
|
|
disqualified = set()
|
|
movrel_min = None
|
|
for blk in blocks:
|
|
for ins in blk:
|
|
op = base_op(ins["op"])
|
|
a = ins["args"]
|
|
if op in VGPR_MOVREL:
|
|
for x in a:
|
|
if x.get("k") == "vgpr":
|
|
movrel_min = x["r"] if movrel_min is None else min(movrel_min, x["r"])
|
|
if (op == "v_writelane_b32" and len(a) == 3
|
|
and a[0].get("k") == "vgpr" and a[0].get("n", 1) == 1
|
|
and a[2].get("k") == "imm" and not (a[2].get("neg") or a[2].get("abs"))
|
|
and a[1].get("k") != "vgpr"):
|
|
written.setdefault(a[0]["r"], set()).add(a[2]["v"] & mask)
|
|
continue
|
|
if (op == "v_readlane_b32" and len(a) == 3
|
|
and a[0].get("k") != "vgpr"
|
|
and a[1].get("k") == "vgpr" and a[1].get("n", 1) == 1
|
|
and a[2].get("k") == "imm" and not (a[2].get("neg") or a[2].get("abs"))):
|
|
continue
|
|
for x in a:
|
|
k = x.get("k")
|
|
if k == "vgpr":
|
|
disqualified.update(range(x["r"], x["r"] + x.get("n", 1)))
|
|
elif k == "vlist":
|
|
disqualified.update(x["r"])
|
|
candidates = {vr for vr in written if vr not in disqualified and (movrel_min is None or vr < movrel_min)}
|
|
if not candidates:
|
|
return []
|
|
# Must-def check over CFG: every v_readlane_b32 of (vr, lane) must be dominated by v_writelane_b32 of (vr, lane)
|
|
# on every path from entry, so entry-populated input VGPRs read before write are never misclassified.
|
|
if succ is None:
|
|
succ = [[i + 1] if i + 1 < len(blocks) else [] for i in range(len(blocks))]
|
|
entry = [None] * len(blocks)
|
|
if blocks:
|
|
entry[0] = set()
|
|
work = [0] if blocks else []
|
|
while work:
|
|
n = work.pop()
|
|
st = set(entry[n])
|
|
for ins in blocks[n]:
|
|
op, a = base_op(ins["op"]), ins["args"]
|
|
if op == "v_writelane_b32" and len(a) == 3 and a[0].get("k") == "vgpr" and a[0]["r"] in candidates:
|
|
st.add((a[0]["r"], a[2]["v"] & mask))
|
|
for s in succ[n]:
|
|
merged = set(st) if entry[s] is None else (entry[s] & st)
|
|
if entry[s] is None or merged != entry[s]:
|
|
entry[s] = merged
|
|
work.append(s)
|
|
for n, blk in enumerate(blocks):
|
|
if entry[n] is None:
|
|
continue
|
|
st = set(entry[n])
|
|
for ins in blk:
|
|
op, a = base_op(ins["op"]), ins["args"]
|
|
if op == "v_writelane_b32" and len(a) == 3 and a[0].get("k") == "vgpr" and a[0]["r"] in candidates:
|
|
st.add((a[0]["r"], a[2]["v"] & mask))
|
|
elif op == "v_readlane_b32" and len(a) == 3 and a[1].get("k") == "vgpr" and a[1]["r"] in candidates:
|
|
if (a[1]["r"], a[2]["v"] & mask) not in st:
|
|
candidates.discard(a[1]["r"])
|
|
return sorted((vr, lane) for vr in candidates for lane in written[vr])
|
|
|
|
|
|
def definite_spill_reads(blocks, succ=None, wave64=True):
|
|
"""Per-instruction definite constant-lane scalar spill reloads (works on mixed VGPRs too).
|
|
|
|
Returns (read_ins_ids, slots) where `read_ins_ids` is the set of `id(ins)` for every constant-lane
|
|
`v_readlane_b32 sD, vR, K` where `(vR, K)` was definitely written by a constant-lane `v_writelane_b32 vR, sS, K`
|
|
(non-VGPR source) on every path from entry with no intervening write to `vR` (other than constant-lane
|
|
`v_writelane_b32` to a different lane). `slots` is the sorted list of `(vR, K)` slots needed by those reads.
|
|
|
|
Parking those slots in `%sgpr` avoids `OpGroupNonUniformShuffle` on lanes that may be absent (partial fragment
|
|
waves, discards, or wave64 lanes >= 32 on 32-wide subgroups) even when the VGPR is reused as a vector register
|
|
elsewhere in the shader.
|
|
"""
|
|
mask = 63 if wave64 else 31
|
|
|
|
def _const_lane(a):
|
|
return a.get("k") == "imm" and not (a.get("neg") or a.get("abs"))
|
|
|
|
def _kill_vgprs(st, regs):
|
|
if not regs or not st:
|
|
return
|
|
for key in [k for k in st if k[0] in regs]:
|
|
st.discard(key)
|
|
|
|
def _step_spills(st, ins):
|
|
op, a = base_op(ins["op"]), ins["args"]
|
|
if op in ("s_swappc_b64", "s_setpc_b64", "s_call_b64"):
|
|
st.clear()
|
|
return
|
|
if not a or op.startswith(NO_DESTINATION):
|
|
return
|
|
mods = ins.get("mods", ())
|
|
if op.startswith(("buffer_load", "tbuffer_load")) and "lds" in mods:
|
|
return
|
|
if op.startswith(("buffer_atomic", "global_atomic", "flat_atomic", "image_atomic",
|
|
"s_atomic", "s_buffer_atomic")) and "glc" not in mods:
|
|
return
|
|
if op.startswith("ds_") and not op.startswith(DS_HAS_DST) and "_rtn" not in op:
|
|
return
|
|
if op.startswith("v_cmp") or op == "v_readlane_b32":
|
|
return
|
|
if op == "v_writelane_b32" and len(a) == 3 and a[0].get("k") == "vgpr":
|
|
vr = a[0]["r"]
|
|
if a[0].get("n", 1) == 1 and _const_lane(a[2]) and a[1].get("k") != "vgpr":
|
|
st.add((vr, a[2]["v"] & mask))
|
|
else:
|
|
_kill_vgprs(st, range(vr, vr + a[0].get("n", 1)))
|
|
return
|
|
if op == "v_swap_b32":
|
|
written = set()
|
|
for x in a[:2]:
|
|
if x.get("k") == "vgpr":
|
|
written.update(range(x["r"], x["r"] + x.get("n", 1)))
|
|
_kill_vgprs(st, written)
|
|
return
|
|
if op in VGPR_REL_DST:
|
|
bases = [x["r"] for x in (a[:2] if op == "v_swaprel_b32" else a[:1]) if x.get("k") == "vgpr"]
|
|
if bases:
|
|
lo = min(bases)
|
|
for key in [k for k in st if k[0] >= lo]:
|
|
st.discard(key)
|
|
return
|
|
k0 = a[0].get("k")
|
|
if k0 == "vgpr":
|
|
_kill_vgprs(st, range(a[0]["r"], a[0]["r"] + a[0].get("n", 1)))
|
|
elif k0 == "vlist":
|
|
_kill_vgprs(st, set(a[0]["r"]))
|
|
|
|
if not blocks:
|
|
return set(), []
|
|
if succ is None:
|
|
succ = [[i + 1] if i + 1 < len(blocks) else [] for i in range(len(blocks))]
|
|
entry = [None] * len(blocks)
|
|
entry[0] = set()
|
|
work = [0]
|
|
while work:
|
|
n = work.pop()
|
|
st = set(entry[n])
|
|
for ins in blocks[n]:
|
|
_step_spills(st, ins)
|
|
for s in succ[n]:
|
|
merged = set(st) if entry[s] is None else (entry[s] & st)
|
|
if entry[s] is None or merged != entry[s]:
|
|
entry[s] = merged
|
|
work.append(s)
|
|
read_ids = set()
|
|
slots = set()
|
|
for n, blk in enumerate(blocks):
|
|
if entry[n] is None:
|
|
continue
|
|
st = set(entry[n])
|
|
for ins in blk:
|
|
op, a = base_op(ins["op"]), ins["args"]
|
|
if (op == "v_readlane_b32" and len(a) == 3
|
|
and a[0].get("k") != "vgpr"
|
|
and a[1].get("k") == "vgpr" and a[1].get("n", 1) == 1
|
|
and _const_lane(a[2])):
|
|
slot = (a[1]["r"], a[2]["v"] & mask)
|
|
if slot in st:
|
|
read_ids.add(id(ins))
|
|
slots.add(slot)
|
|
_step_spills(st, ins)
|
|
return read_ids, sorted(slots)
|
|
|
|
|
|
TO_DATA = "s_mask_to_data_b32" # the translator's own: sD = the real bits of the lane-mask word in sD
|
|
|
|
|
|
def _fixpoint(blocks, succ, wave64):
|
|
"""Each block's state on entry (None where it is not reached), as analyse() works it out."""
|
|
entry = [None] * len(blocks)
|
|
if blocks:
|
|
entry[0] = {}
|
|
work = [0] if blocks else []
|
|
while work:
|
|
n = work.pop()
|
|
state = dict(entry[n])
|
|
for ins in blocks[n]:
|
|
step(state, ins, wave64)
|
|
for s in succ[n]:
|
|
merged = dict(state) if entry[s] is None else _merge(entry[s], state)
|
|
if merged != entry[s]:
|
|
entry[s] = merged
|
|
work.append(s)
|
|
return entry
|
|
|
|
|
|
def _merge(a, b):
|
|
"""A mask on both paths, or a mask on one and 0 / -1 on the other; anything else is data (left out)."""
|
|
merged = {}
|
|
for r in a.keys() & b.keys():
|
|
a_k, b_k = a[r], b[r]
|
|
if a_k == b_k:
|
|
merged[r] = a_k
|
|
elif a_k == EITHER:
|
|
merged[r] = b_k
|
|
elif b_k == EITHER:
|
|
merged[r] = a_k
|
|
else:
|
|
merged[r] = MASK
|
|
return merged
|
|
|
|
|
|
ALL = "all" # an instruction that may read any SGPR (s_movrels / s_movrelsd: the register comes from M0)
|
|
|
|
|
|
def _sgprs(x):
|
|
if x.get("k") == "sgpr":
|
|
return set(range(x["r"], x["r"] + x.get("n", 1)))
|
|
if x.get("k") == "slist":
|
|
return {r for r in x["r"] if isinstance(r, int)}
|
|
return set()
|
|
|
|
|
|
def _reads_writes(ins):
|
|
"""The SGPR numbers `ins` reads and the ones it surely writes (a destination it may leave alone is read too)."""
|
|
op, a = base_op(ins["op"]), ins["args"]
|
|
if op.startswith(("s_movrels", "s_movreld", "s_swappc", "s_setpc", "s_call", "s_cbranch_g_fork")):
|
|
return ALL, set()
|
|
if not a:
|
|
return set(), set()
|
|
if op.startswith(NO_DESTINATION):
|
|
reads = set()
|
|
for x in a:
|
|
if x is not None:
|
|
reads |= _sgprs(x)
|
|
return reads, set()
|
|
reads = set()
|
|
for x in a[1:]:
|
|
if x is not None:
|
|
reads |= _sgprs(x)
|
|
# A SOPK read-modify-write, a 16-bit or SDWA/DPP partial write, or a VOP3b carry-out pair: the first operand is
|
|
# taken as read too, which only ever keeps a register live. (A compare writes its whole mask in any encoding.)
|
|
if op in ("s_addk_i32", "s_mulk_i32", "s_cmovk_i32") or op.startswith("s_cmov") or "_co_" in op or \
|
|
(ins["op"].endswith(("_sdwa", "_dpp", "_dpp8")) and not op.startswith("v_cmp")):
|
|
reads |= _sgprs(a[0])
|
|
return reads, set()
|
|
return reads, _sgprs(a[0])
|
|
|
|
|
|
def _is_mask_operand(x, masks):
|
|
if x is None:
|
|
return False
|
|
if x.get("k") == "special":
|
|
return x.get("t", "").startswith(("exec", "vcc"))
|
|
return x.get("k") == "sgpr" and any(x["r"] + i in masks for i in range(x.get("n", 1)))
|
|
|
|
|
|
# The scalar ops that read a register as a whole word of lane bits: the first or last set bit, or how many there are.
|
|
WORD_SCANS = ("s_ff0_i32_b", "s_ff1_i32_b", "s_bcnt0_i32_b", "s_bcnt1_i32_b", "s_flbit_i32")
|
|
|
|
|
|
def _numeric_reads(ins, masks):
|
|
"""(reads, through) for insert_data_merges: the SGPR numbers `ins` scans as a whole word of lane bits
|
|
(WORD_SCANS), which a register taken as data must hold the wave's bits for. `through`: a scalar copy or
|
|
bitwise op of data, whose sources count only where its result is scanned in turn (`s_xor_b32 s35, s32, s26`
|
|
then `s_mov_b32 s26, s35`). Other reads are left out. As a mask (EXEC, a bitwise op with a mask, v_cndmask)
|
|
this lane's 0 / ~0 is exact: the translator takes bit L of a data register there (rdna2spirv's mask_src).
|
|
`masks`: the registers holding a mask before `ins` (analyse())."""
|
|
reads, _ = _reads_writes(ins)
|
|
if reads is ALL:
|
|
return ALL, False
|
|
op, a = base_op(ins["op"]), ins["args"]
|
|
if not a:
|
|
return set(), False
|
|
if op.startswith(WORD_SCANS):
|
|
return reads, False
|
|
if op.startswith(("s_mov_b", "s_not_b") + BITWISE) and a[0].get("k") == "sgpr" and not any(_is_mask_operand(x, masks) for x in a[1:]):
|
|
return reads, True
|
|
return set(), False
|
|
|
|
|
|
def _numeric_live_in(blocks, succ, masks_before):
|
|
"""The SGPR numbers each block may read as a number before writing them (ALL for every one), following scalar
|
|
copies and bitwise ops of data to where their results are read (_numeric_reads)."""
|
|
info = [[(_reads_writes(ins)[1], *_numeric_reads(ins, masks_before.get(id(ins), {}))) for ins in blk]
|
|
for blk in blocks]
|
|
|
|
def through(n, live):
|
|
for w, reads, via in reversed(info[n]):
|
|
if reads is ALL:
|
|
return ALL
|
|
needed = not via or bool(w & live)
|
|
live = live - w
|
|
if needed:
|
|
live = live | reads
|
|
return live
|
|
|
|
live = [set() for _ in blocks]
|
|
changed = True
|
|
while changed:
|
|
changed = False
|
|
for n in range(len(blocks) - 1, -1, -1):
|
|
if live[n] is ALL:
|
|
continue
|
|
out = set()
|
|
for s in succ[n]:
|
|
if live[s] is ALL:
|
|
out = ALL
|
|
break
|
|
out |= live[s]
|
|
new = ALL if out is ALL else through(n, out)
|
|
if new != live[n]:
|
|
live[n] = new
|
|
changed = True
|
|
return live
|
|
|
|
|
|
def insert_data_merges(blocks, succ, branches, wave64=True):
|
|
"""In place: where an SGPR holds a lane mask at the end of a block but is data where a successor begins (a
|
|
mask on one path to it, a number on another), insert a TO_DATA instruction for it before the block's branch.
|
|
|
|
The two kinds of value are kept differently: a mask as this lane's bit (all ones or zero), data as the same
|
|
number in every lane. Where they meet the register is taken as data, which the path that wrote the mask does
|
|
not hold. The compiler makes such a merge when it walks the lanes of a ballot with a scalar loop:
|
|
`s_and_b64 s[26:27], vcc, exec`, then s_ff1_i32_b32 / s_xor_b32 of s26 and `s_mov_b32 s26, sN` on the back
|
|
edge. The loop's s26 was this lane's 0 / ~0 on the first pass, so each lane found its own first bit and took
|
|
its own number of passes, where the wave takes one. TO_DATA gathers the wave's real bits into the register
|
|
(rdna2spirv's lane_mask_word), so the loop sees on every path what the hardware has.
|
|
|
|
A register is converted only when every successor takes it as data (one that still reads it as a mask keeps
|
|
this lane's bit) and some successor may scan its lane bits before writing it (s_ff0 / s_ff1 / s_bcnt0 /
|
|
s_bcnt1 / s_flbit, also through scalar copies of it: _numeric_reads). The gather is a cross-lane step (a
|
|
barrier round under --wave64-emulate), and most such merges are only ever read as masks again (written back to
|
|
EXEC, ANDed with it), where this lane's 0 / ~0 is already exact: the translator takes bit L of a data register
|
|
for lane L there (rdna2spirv's mask_src). Other number reads of such a merge (an add, a compare) would need the
|
|
gather too; none is known in a shader, and they are left as they were to keep the change to the lane loops.
|
|
TO_DATA itself writes data (step), so a second run finds nothing left to insert.
|
|
|
|
Under --wave64-emulate the gather is an exchange round that both halves of the wave must join, so it relies on
|
|
its block being reached by the whole wave, through scalar (wave-uniform) branches, as the compiler's lane loops
|
|
are; wave64_emulate_opt keeps it out of lane-local regions (_MASK_WORD_READERS).
|
|
`branches`: the opcodes that end a block. Returns how many instructions were inserted."""
|
|
inserted = 0
|
|
before, _ = analyse(blocks, succ, wave64=wave64)
|
|
live = _numeric_live_in(blocks, succ, before)
|
|
for _ in range(len(blocks) + 1): # each round only takes masks away, so this ends
|
|
entry = _fixpoint(blocks, succ, wave64)
|
|
added = 0
|
|
for n, blk in enumerate(blocks):
|
|
if entry[n] is None or not succ[n]:
|
|
continue
|
|
state = dict(entry[n])
|
|
for ins in blk:
|
|
step(state, ins, wave64)
|
|
regs = []
|
|
for r, k in sorted((r, k) for r, k in state.items() if isinstance(r, int) and k in MASK_KINDS):
|
|
if all(entry[s] is not None and r not in entry[s] for s in succ[n]) and \
|
|
any(live[s] is ALL or r in live[s] for s in succ[n]):
|
|
regs.append(r)
|
|
if not regs:
|
|
continue
|
|
last = blk[-1] if blk else None
|
|
at = len(blk) - 1 if last is not None and (base_op(last["op"]) in branches) else len(blk)
|
|
pc = last.get("pc", 0) if last is not None else 0
|
|
for r in regs:
|
|
reg = {"k": "sgpr", "r": r, "n": 1}
|
|
blk.insert(at, {"op": TO_DATA, "args": [dict(reg), dict(reg)], "mods": [], "pc": pc, "enc": "",
|
|
"synthetic": True})
|
|
at += 1
|
|
added += 1
|
|
inserted += added
|
|
if not added:
|
|
break
|
|
return inserted
|
|
|
|
|
|
def analyse(blocks, succ, *, include_either=False, wave64=True):
|
|
entry = [None] * len(blocks) # None: not reached yet
|
|
if blocks:
|
|
entry[0] = {}
|
|
work = [0] if blocks else []
|
|
while work:
|
|
n = work.pop()
|
|
state = dict(entry[n])
|
|
for ins in blocks[n]:
|
|
step(state, ins, wave64)
|
|
for s in succ[n]:
|
|
if entry[s] is None:
|
|
merged = dict(state)
|
|
else: # a mask on both paths, or a mask on one and 0 / -1 on the other
|
|
merged = {}
|
|
for r in entry[s].keys() & state.keys():
|
|
a_k, b_k = entry[s][r], state[r]
|
|
if a_k == b_k:
|
|
merged[r] = a_k
|
|
elif a_k == EITHER:
|
|
merged[r] = b_k
|
|
elif b_k == EITHER:
|
|
merged[r] = a_k
|
|
else:
|
|
merged[r] = MASK
|
|
if merged != entry[s]:
|
|
entry[s] = merged
|
|
work.append(s)
|
|
out, writes, either = {}, set(), {}
|
|
for n, blk in enumerate(blocks):
|
|
state = dict(entry[n] or {})
|
|
for ins in blk:
|
|
out[id(ins)] = {r: k for r, k in state.items() if k in MASK_KINDS}
|
|
if include_either:
|
|
either[id(ins)] = {r for r, k in state.items() if k == EITHER}
|
|
if step(state, ins, wave64):
|
|
writes.add(id(ins))
|
|
return (out, writes, either) if include_either else (out, writes)
|