rdna2spirv: decode run-time buffer formats in one function per module

buffer_load_format with the format taken from the V# decoded all 27 FORMATS inline and selected one, about 900
instructions per load once UNORM/SNORM became exact integer quotients. indirect_diffuse_lighting's two
ScreenProbes_ActivateProbes compute shaders have 3,281 such loads: under --wave64-emulate their modules passed
SPIR-V's id bound (4,194,303) and no longer validated, and before that they were 60 MB modules a driver could
not compile in 100 GB.

The decode is now %fmt_decode_fn, emitted once and called per load (like %desc_lookup_fn). tbuffer loads, whose
format is in the instruction, decode only that format. ScreenProbes_ActivateProbes: 6.16 M instructions -> 2.20 M,
41.7 MB, passes spirv-val. spirv_mini_interp runs OpFunctionCall / OpFunctionParameter / OpReturnValue so the
semantic tests go through the function.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
ItsNotRexed
2026-11-22 00:31:05 -05:00
parent 067d3e8b97
commit dcd8ecf10b
2 changed files with 89 additions and 15 deletions

View File

@ -320,6 +320,7 @@ def _invocation(text, inputs, push_constants, memory, step=False):
id_type = {} # constant / result id -> its type id (the width of a signed comparison)
pc_type = {} # id -> pointee type id of a PushConstant pointer
in_body = False
first_fn = None
body = []
outputs = []
@ -358,6 +359,7 @@ def _invocation(text, inputs, push_constants, memory, step=False):
continue
if op == "OpFunction":
in_body = True
first_fn = res
continue
if op in _IGNORED:
continue
@ -450,7 +452,20 @@ def _invocation(text, inputs, push_constants, memory, step=False):
return signed(val(x), t[1] if t else 32)
labels = {res: idx for idx, (res, op, _, _) in enumerate(body) if op == "OpLabel" and res}
pc = 0
# Every function's first body index and parameter ids. The first OpFunction was consumed by the header parse;
# later ones are in the body. Execution starts at %main (the entry point the translator names).
fn_start, fn_params = {first_fn: 0}, {}
for idx, (res, op, _, _) in enumerate(body):
if op == "OpFunction":
fn_start[res] = idx + 1
for fid, start in list(fn_start.items()): # parameters come right after OpFunction
params, i = [], start
while i < len(body) and body[i][1] == "OpFunctionParameter":
params.append(body[i][0])
i += 1
fn_params[fid], fn_start[fid] = params, i
calls = [] # (return pc, result id, cur_label, prev_label)
pc = fn_start.get("%main", 0)
killed = False
cur_label = prev_label = None
while pc < len(body):
@ -463,6 +478,28 @@ def _invocation(text, inputs, push_constants, memory, step=False):
if op == "OpLabel":
prev_label, cur_label = cur_label, res
continue
if op == "OpFunctionCall":
fid, args = a[1], a[2:]
if fid not in fn_start or len(args) != len(fn_params[fid]) or len(calls) > 16:
raise UnsupportedConstruct(f"OpFunctionCall {fid}")
for prm, arg in zip(fn_params[fid], args):
values[prm] = val(arg)
if arg in id_type:
id_type[prm] = id_type[arg]
calls.append((pc, res, cur_label, prev_label))
pc = fn_start[fid]
continue
if op == "OpReturnValue":
if not calls:
raise UnsupportedConstruct("OpReturnValue outside a called function")
ret = val(a[0])
pc, res_id, cur_label, prev_label = calls.pop()
values[res_id] = ret
continue
if op == "OpReturn" and not calls:
break
if op in ("OpFunction", "OpFunctionParameter"):
raise UnsupportedConstruct(f"{op} reached by falling through")
if op in _IGNORED:
continue
if op == "OpKill":

View File

@ -160,6 +160,7 @@ class Gen:
self.blocks = [] # per basic block: list of SPIR-V lines (dispatch-loop form), empty = straight-line
self.succ = [] # per basic block: the blocks it can go to next (none = the program ends there)
self.desc_fn = None # lines of the descriptor-lookup function, once an instruction needs it
self.fmt_fn = None # lines of the typed-buffer format-decode function, once a dynamic-format load needs it
self.sgpr_imm = {} # SGPR -> literal an s_mov_b32 put there earlier in this basic block (see gather_addr_modes)
self.desc_cache = {} # (first SGPR, dwords) -> id of the %desc_lookup_fn result in the current basic block
self._scan = (None, 0, []) # (body list, lines already seen, open merge labels): see desc_cache_ok
@ -1099,6 +1100,46 @@ class Gen:
self.dst({"k": "vgpr", "r": vdata["r"] + out, "n": 1}, self.tou(comp))
out += 1
def decode_any_format(self, fmt, words):
"""Decode every supported format from 4 packed dwords, then pick by FORMAT (0 for one outside FORMATS)."""
comps = [self.cu(0)] * 4
for code in self.FORMATS:
dec = self.decode_format(words, code)
e = self.tmp()
self.emit(f"{e} = OpIEqual %bool {fmt} {self.cu(code)}")
nxt = []
for c in range(4):
s = self.tmp()
self.emit(f"{s} = OpSelect %uint {e} {dec[c]} {comps[c]}")
nxt.append(s)
comps = nxt
return comps
def format_decode_call(self, fmt, words):
"""4 uint ids: the element decoded per the run-time FORMAT, through one function in the module.
Decoding all FORMATS is about 900 instructions (the exact UNORM/SNORM quotients are integer code). Inlined at
every dynamic-format load, 3,281 loads made a 60 MB module whose id bound passed SPIR-V's 4,194,303 limit
(indirect_diffuse_lighting ScreenProbes_ActivateProbes under --wave64-emulate)."""
if self.fmt_fn is None:
params = ["%fd_fmt"] + [f"%fd_w{i}" for i in range(4)]
saved, self.body = self.body, []
dec = self.decode_any_format(params[0], params[1:])
res = self.tmp()
self.emit(f"{res} = OpCompositeConstruct %v4uint_fmt " + " ".join(dec))
lines, self.body = self.body, saved
self.fmt_fn = (["%fmt_decode_fn = OpFunction %v4uint_fmt None %fn_fmt_decode"] +
[f"{q} = OpFunctionParameter %uint" for q in params] + ["%fd_entry = OpLabel"] +
lines + [f" OpReturnValue {res}", "OpFunctionEnd"])
r = self.tmp()
self.emit(f"{r} = OpFunctionCall %v4uint_fmt %fmt_decode_fn {fmt} " + " ".join(words[:4]))
comps = []
for c in range(4):
x = self.tmp()
self.emit(f"{x} = OpCompositeExtract %uint {r} {c}")
comps.append(x)
return comps
def buffer_load_format(self, op, a, mods, fixed_fmt=None):
"""buffer_load_format_[x|xy|xyz|xyzw]: element at V#.base + offsets, decoded per the V# FORMAT field
(word3 bits 12-18), then swizzled by DST_SEL_X/Y/Z/W (word3 bits 0-11: 0=0, 1=1, 4..7 = X..W).
@ -1178,18 +1219,11 @@ class Gen:
self.emit(f"{bw} = OpSelect %uint {nz} {merged} {words[i]}")
packed.append(bw)
words = packed
# Decode every supported format, then pick by FORMAT.
comps = [self.cu(0)] * 4
for code in self.FORMATS:
dec = self.decode_format(words, code)
e = self.tmp()
self.emit(f"{e} = OpIEqual %bool {fmt} {self.cu(code)}")
nxt = []
for c in range(4):
s = self.tmp()
self.emit(f"{s} = OpSelect %uint {e} {dec[c]} {comps[c]}")
nxt.append(s)
comps = nxt
if fixed_fmt is not None:
# tbuffer: the format is in the instruction, so only that one is decoded.
comps = self.decode_format(words, fixed_fmt) if fixed_fmt in self.FORMATS else [self.cu(0)] * 4
else:
comps = self.format_decode_call(fmt, words)
# DST_SEL swizzle: 0 -> 0, 1 -> 1.0 (float/norm) or integer 1 (UINT/SINT; SHADER-86), 4..7 -> X..W.
is_int_fmt = "%false"
for code_v, (_, kind, _) in self.FORMATS.items():
@ -6446,6 +6480,9 @@ def assemble(gen):
types.append(f"{name} = OpConstant %uint {v}")
if gen.desc_fn:
types.append("%fn_desc_lookup = OpTypeFunction %uint " + " ".join(["%uint"] * 8))
if gen.fmt_fn:
types.append("%v4uint_fmt = OpTypeVector %uint 4") # dedupe_types merges it with any other uvec4
types.append("%fn_fmt_decode = OpTypeFunction %v4uint_fmt " + " ".join(["%uint"] * 5))
if gen.uses_ballot:
types.append("%v4uint_bal = OpTypeVector %uint 4") # dedupe_types merges it with any other uvec4
if gen.uses_bvh and not any(t.startswith("%v3float = ") for t in types):
@ -6724,7 +6761,7 @@ def assemble(gen):
f"OpStore %vinp{reg}_{c} %vinb{reg}_{c}"]
# Spill pointers last: a spilled value's type may be declared anywhere above.
types += [f"{ptr} = OpTypePointer Function {t}" for t, ptr in gen.x_ptr_types.items()]
out = hdr + dec + types + gvars + (gen.desc_fn or []) + fn
out = hdr + dec + types + gvars + (gen.desc_fn or []) + (gen.fmt_fn or []) + fn
tree = cfg_structure.structure(gen.succ) if gen.blocks and STRUCTURED and not gen.emulate else None
gen.control_flow = "structured" if tree is not None else "dispatch loop" if gen.blocks else "straight line"
if gen.emulate:
@ -6799,7 +6836,7 @@ def assemble(gen):
fn = fn[:last_var + 1] + fn_vars + fn[last_var + 1:]
if pops:
fn.append("OpBeginInvocationInterlockEXT") # end of the entry block: uniform, executed once
out = hdr + dec + types + gvars + (gen.desc_fn or []) + fn
out = hdr + dec + types + gvars + (gen.desc_fn or []) + (gen.fmt_fn or []) + fn
gen.body =[" " + l if not (l.startswith("%") and " = OpLabel" in l) else l for l in flow + body]
end_lock = " OpEndInvocationInterlockEXT\n" if pops else ""
if ms: