upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/tools/wave64_emulate_opt.py
diff options
context:
space:
mode:
authorTG0000 <122870448+TG0000@users.noreply.github.com>2026-11-23 16:45:26 +0100
committerGitHub <noreply@github.com>2026-11-23 09:45:26 -0600
commit8c22bf40a00f6bfe88b047abcc5cdbfcbc59d00d (patch)
treeb4ed61a00e047dd59901dfa4f3eb537bc5d63e22 /tools/wave64_emulate_opt.py
parentbc773d30734608d913e80072ff77f05010b6cf6e (diff)
wave64_emulate_opt: cache opcode metadata, fuse liveness/body pass, and precompute superblock dirty transfer (#6895)
Squash-merged after diff review of PR #6895 - wave64_emulate_opt: cache opcode metadata, fuse liveness/body pass, and precompute superblock dirty transfer
Diffstat (limited to 'tools/wave64_emulate_opt.py')
-rw-r--r--tools/wave64_emulate_opt.py1057
1 files changed, 729 insertions, 328 deletions
diff --git a/tools/wave64_emulate_opt.py b/tools/wave64_emulate_opt.py
index 2f684308e..f917c9c4d 100644
--- a/tools/wave64_emulate_opt.py
+++ b/tools/wave64_emulate_opt.py
@@ -117,23 +117,255 @@ _NO_DEST_PREFIXES = (
117 "buffer_gl", "buffer_wbinvl", "ds_gws", "ds_nop", 117 "buffer_gl", "buffer_wbinvl", "ds_gws", "ds_nop",
118) 118)
119 119
120_SOP2_B32_LOGIC = frozenset({
121 "s_and_b32", "s_or_b32", "s_xor_b32", "s_andn2_b32", "s_orn2_b32",
122 "s_nand_b32", "s_nor_b32", "s_xnor_b32", "s_not_b32",
123})
124
125_FORBIDDEN_FOLD_OPS = frozenset({
126 "s_barrier", "s_sendmsg", "s_setpc_b64", "s_swappc_b64", "s_trap",
127 "s_sethalt", "s_setkill", "s_sleep", "s_setprio",
128 "s_round_mode", "s_denorm_mode",
129 "v_readlane_b32", "v_readfirstlane_b32", "v_writelane_b32",
130 "v_permlane16_b32", "v_permlanex16_b32",
131 "ds_bpermute_b32", "ds_permute_b32", "ds_swizzle_b32",
132 "ds_gws_init", "ds_gws_sema_v", "ds_gws_sema_br", "ds_gws_sema_p", "ds_gws_barrier",
133 "ds_consume", "ds_append", "ds_ordered_count",
134 "s_wqm_b32", "s_wqm_b64", "s_quadmask_b32", "s_quadmask_b64",
135})
136
137_ALWAYS_BARRIER_OPS = frozenset({
138 "s_barrier", "v_readlane_b32", "v_readfirstlane_b32",
139 "v_permlane16_b32", "v_permlanex16_b32",
140 "ds_bpermute_b32", "ds_permute_b32", "ds_swizzle_b32",
141 "s_wqm_b32", "s_wqm_b64",
142})
143
144_VOTED_BRANCHES = frozenset({
145 "s_cbranch_execz", "s_cbranch_execnz", "s_cbranch_vccz", "s_cbranch_vccnz",
146})
147
148_SCALAR_NO_SCC_PREFIXES = (
149 "s_mov", "s_cselect", "s_load", "s_buffer_load", "s_getpc",
150 "s_nop", "s_waitcnt", "s_clause", "s_inst_prefetch", "s_pack",
151 "s_mul_i32", "s_mul_hi", "s_mulk", "s_ff", "s_flbit", "s_bfm",
152 "s_get_waveid",
153)
154
155# Bounded caches for opcode normalization and static per-opcode classification.
156_OP_CACHE_MAX = 4096
157_BASE_OP_CACHE = {}
158_OP_META_CACHE = {}
159
160# _scalar_rw dispatch modes
161_RW_MOVREL = 0
162_RW_TERM = 1
163_RW_NO_DEST = 2
164_RW_VCMP = 3
165_RW_ATOMIC = 4
166_RW_DS_RET = 5
167_RW_DS_NORET = 6
168_RW_SOPK_RW = 7
169_RW_DEFAULT = 8
170_RW_VOP3B = 9
171
172# Bit flags in meta[8]
173_FLAG_CMOV_RD_DEST = 1
174_FLAG_NO_KILL_DEST = 2
175_FLAG_FORBIDDEN_FOLD = 4
176_FLAG_ALWAYS_BARRIER = 8
177_FLAG_WRITES_EXEC_OP = 16
178_FLAG_SCC_VOTE_ALWAYS_MASK = 32
179_FLAG_SOP2_B32_LOGIC = 64
180_FLAG_VOTED_BRANCH = 128
181
182# Mask check categories in meta[11]
183_MASK_CHK_NONE = 0
184_MASK_CHK_WORD_READER = 1
185_MASK_CHK_MBCNT = 2
186_MASK_CHK_SCMP = 3
187_MASK_CHK_SCC_VOTE = 4
188
189# 4-bit dirty-state bitmask: bit0=("mem","r"), bit1=("mem","w"), bit2=("lds","r"), bit3=("lds","w")
190_DIRTY_MEM_R = 1
191_DIRTY_MEM_W = 2
192_DIRTY_LDS_R = 4
193_DIRTY_LDS_W = 8
194_DIRTY_MASK_TO_FROZENSET = tuple(
195 frozenset(
196 tok
197 for bit, tok in (
198 (_DIRTY_MEM_R, ("mem", "r")),
199 (_DIRTY_MEM_W, ("mem", "w")),
200 (_DIRTY_LDS_R, ("lds", "r")),
201 (_DIRTY_LDS_W, ("lds", "w")),
202 )
203 if m & bit
204 )
205 for m in range(16)
206)
207
208_EMPTY_MEM_STATS = (0, False, False, 0, False, False)
209
120 210
121def base_op(op): 211def base_op(op):
212 res = _BASE_OP_CACHE.get(op)
213 if res is not None:
214 return res
215 res = op
122 for suffix in ("_e32", "_e64", "_sdwa", "_dpp"): 216 for suffix in ("_e32", "_e64", "_sdwa", "_dpp"):
123 if op.endswith(suffix): 217 if op.endswith(suffix):
124 return op[:-len(suffix)] 218 res = op[:-len(suffix)]
125 return op 219 break
220 if len(_BASE_OP_CACHE) >= _OP_CACHE_MAX:
221 _BASE_OP_CACHE.clear()
222 _BASE_OP_CACHE[op] = res
223 return res
224
225
226def _get_op_meta(raw_op):
227 """Return cached static metadata tuple for raw opcode `raw_op`."""
228 meta = _OP_META_CACHE.get(raw_op)
229 if meta is not None:
230 return meta
231
232 op = base_op(raw_op)
233 is_term = op == "s_endpgm" or op in BRANCHES
234 scc_imp_read = op in _SCC_IMPLICIT_READS or op.startswith(("s_getreg", "s_setreg", "s_save_status"))
235 scc_uncond_write = op in _SCC_UNCONDITIONAL_WRITES
236
237 if op.startswith("s_movrel"):
238 rw_mode = _RW_MOVREL
239 elif is_term:
240 rw_mode = _RW_TERM
241 elif op.startswith(("s_cmp", "s_bitcmp")) or op.startswith("v_cmpx") or op.startswith(_NO_DEST_PREFIXES):
242 rw_mode = _RW_NO_DEST
243 elif op.startswith("v_cmp"):
244 rw_mode = _RW_VCMP
245 elif op.startswith(("buffer_atomic", "global_atomic", "flat_atomic", "image_atomic")):
246 rw_mode = _RW_ATOMIC
247 elif op.startswith("ds_"):
248 returns = (op.startswith(("ds_read", "ds_bpermute", "ds_permute", "ds_swizzle", "ds_consume", "ds_append"))
249 or "_rtn" in op)
250 rw_mode = _RW_DS_RET if returns else _RW_DS_NORET
251 elif op in ("s_addk_i32", "s_mulk_i32", "s_cmovk_i32"):
252 rw_mode = _RW_SOPK_RW
253 elif op == "s_movk_i32":
254 rw_mode = _RW_DEFAULT
255 elif op.startswith("v_") and (
256 "_co_" in op or op in ("v_mad_u64_u32", "v_mad_i64_i32", "v_div_scale_f32", "v_div_scale_f64")):
257 rw_mode = _RW_VOP3B
258 else:
259 rw_mode = _RW_DEFAULT
260
261 base_rd = 0
262 if op in _IMPLICIT_VCC_READS:
263 base_rd |= 1 << _BIT_VCC
264 if scc_imp_read:
265 base_rd |= 1 << _BIT_SCC
266 if op.startswith(("ds_", "s_sendmsg", "v_interp", "v_movrel", "v_swaprel")):
267 base_rd |= 1 << _BIT_M0
268
269 base_mw = 0
270 base_mk = 0
271 if scc_uncond_write:
272 base_mw |= 1 << _BIT_SCC
273 base_mk |= 1 << _BIT_SCC
274 elif op.startswith("s_") and not op.startswith(_SCALAR_NO_SCC_PREFIXES):
275 base_mw |= 1 << _BIT_SCC
276
277 x_mem_acc = _x_memory_order_access(op)
278 x_mem_dirty = 0
279 scratch_acc = None
280 if x_mem_acc is not None:
281 kind, r, w = x_mem_acc
282 if kind == "lds":
283 if r:
284 x_mem_dirty |= _DIRTY_LDS_R
285 if w:
286 x_mem_dirty |= _DIRTY_LDS_W
287 else:
288 if r:
289 x_mem_dirty |= _DIRTY_MEM_R
290 if w:
291 x_mem_dirty |= _DIRTY_MEM_W
292 elif op.startswith("scratch_"):
293 if "store" in op or "atomic" in op:
294 scratch_acc = ("atomic" in op, True)
295 else:
296 scratch_acc = (True, False)
297
298 flags = 0
299 if op == "s_cmov_b32" or op == "s_cmov_b64":
300 flags |= _FLAG_CMOV_RD_DEST | _FLAG_NO_KILL_DEST
301 elif op == "s_cmovk_i32":
302 flags |= _FLAG_NO_KILL_DEST
303
304 is_dpp = raw_op.endswith(("_dpp", "_dpp8"))
305 if (is_dpp
306 or op in _FORBIDDEN_FOLD_OPS
307 or op.startswith(("s_movrel", "s_setreg", "s_getreg", "s_store", "s_buffer_store", "s_atomic",
308 "ds_gws", "exp"))
309 or (x_mem_acc is None and scratch_acc is None
310 and not op.startswith(("image_sample", "image_gather", "image_bvh"))
311 and ("store" in op or "atomic" in op))):
312 flags |= _FLAG_FORBIDDEN_FOLD
313
314 if is_dpp or op in _ALWAYS_BARRIER_OPS or op.startswith("s_movrel"):
315 flags |= _FLAG_ALWAYS_BARRIER
316 if op.startswith("v_cmpx") or "saveexec" in op or "wrexec" in op:
317 flags |= _FLAG_WRITES_EXEC_OP
318 if op in _MASK_SCC_VOTE_OPS and ("saveexec" in op or "wrexec" in op or op.endswith("_mask")):
319 flags |= _FLAG_SCC_VOTE_ALWAYS_MASK
320 if op in _SOP2_B32_LOGIC:
321 flags |= _FLAG_SOP2_B32_LOGIC
322 if op in _VOTED_BRANCHES:
323 flags |= _FLAG_VOTED_BRANCH
324
325 if op in _MASK_WORD_READERS:
326 mask_chk = _MASK_CHK_WORD_READER
327 elif op in ("v_mbcnt_lo_u32_b32", "v_mbcnt_hi_u32_b32"):
328 mask_chk = _MASK_CHK_MBCNT
329 elif op.startswith(("s_cmp", "s_bitcmp")):
330 mask_chk = _MASK_CHK_SCMP
331 elif op in _MASK_SCC_VOTE_OPS:
332 mask_chk = _MASK_CHK_SCC_VOTE
333 else:
334 mask_chk = _MASK_CHK_NONE
335
336 meta = (
337 op, # 0
338 is_term, # 1
339 scc_imp_read, # 2
340 scc_uncond_write, # 3
341 rw_mode, # 4
342 base_rd, # 5
343 base_mw, # 6
344 base_mk, # 7
345 flags, # 8
346 x_mem_acc, # 9
347 scratch_acc, # 10
348 mask_chk, # 11
349 x_mem_dirty, # 12
350 )
351 if len(_OP_META_CACHE) >= _OP_CACHE_MAX:
352 _OP_META_CACHE.clear()
353 _OP_META_CACHE[raw_op] = meta
354 return meta
126 355
127 356
128def _active_insns(blk): 357def _active_insns(blk):
129 """Instructions of a basic block up to and including its terminator (branch or s_endpgm).""" 358 """Instructions of a basic block up to and including its terminator (branch or s_endpgm)."""
130 out = [] 359 meta_get = _OP_META_CACHE.get
131 for ins in blk: 360 n = len(blk)
132 out.append(ins) 361 for i, ins in enumerate(blk):
133 op = base_op(ins["op"]) 362 raw_op = ins["op"]
134 if op == "s_endpgm" or op in BRANCHES: 363 m = meta_get(raw_op)
135 break 364 if m is None:
136 return out 365 m = _get_op_meta(raw_op)
366 if m[1]:
367 return blk if i == n - 1 else blk[:i + 1]
368 return blk
137 369
138 370
139def _has_vcc_or_exec(x): 371def _has_vcc_or_exec(x):
@@ -145,9 +377,8 @@ def _has_vcc_or_exec(x):
145 return False 377 return False
146 378
147 379
148def reads_scc(ins): 380def _reads_scc_with_meta(ins, meta):
149 op = base_op(ins["op"]) 381 if meta[2]:
150 if op in _SCC_IMPLICIT_READS or op.startswith(("s_getreg", "s_setreg", "s_save_status")):
151 return True 382 return True
152 for x in ins["args"]: 383 for x in ins["args"]:
153 if x.get("k") == "special" and x.get("t") in ("scc", "src_scc"): 384 if x.get("k") == "special" and x.get("t") in ("scc", "src_scc"):
@@ -155,8 +386,12 @@ def reads_scc(ins):
155 return False 386 return False
156 387
157 388
389def reads_scc(ins):
390 return _reads_scc_with_meta(ins, _get_op_meta(ins["op"]))
391
392
158def writes_scc(ins): 393def writes_scc(ins):
159 return base_op(ins["op"]) in _SCC_UNCONDITIONAL_WRITES 394 return _get_op_meta(ins["op"])[3]
160 395
161 396
162def scc_live_outs(blocks, succ): 397def scc_live_outs(blocks, succ):
@@ -171,15 +406,29 @@ def scc_live_outs(blocks, succ):
171 use = [False] * n 406 use = [False] * n
172 kill = [False] * n 407 kill = [False] * n
173 active = [_active_insns(blk) for blk in blocks] 408 active = [_active_insns(blk) for blk in blocks]
409 meta_get = _OP_META_CACHE.get
174 for b, insns in enumerate(active): 410 for b, insns in enumerate(active):
175 k = False 411 k = False
176 u = False 412 u = False
177 for ins in insns: 413 for ins in insns:
178 if not k and reads_scc(ins): 414 raw_op = ins["op"]
415 m = meta_get(raw_op)
416 if m is None:
417 m = _get_op_meta(raw_op)
418 if m[2]:
179 u = True 419 u = True
180 break 420 break
181 if writes_scc(ins): 421 rd_explicit = False
422 for x in ins["args"]:
423 if x.get("k") == "special" and x.get("t") in ("scc", "src_scc"):
424 rd_explicit = True
425 break
426 if rd_explicit:
427 u = True
428 break
429 if m[3]:
182 k = True 430 k = True
431 break
183 use[b] = u 432 use[b] = u
184 kill[b] = k 433 kill[b] = k
185 live_in = list(use) 434 live_in = list(use)
@@ -199,30 +448,36 @@ def scc_live_outs(blocks, succ):
199 for ins in reversed(insns): 448 for ins in reversed(insns):
200 if live: 449 if live:
201 out.add(id(ins)) 450 out.add(id(ins))
202 live = (live and not writes_scc(ins)) or reads_scc(ins) 451 raw_op = ins["op"]
452 m = meta_get(raw_op)
453 if m is None:
454 m = _get_op_meta(raw_op)
455 if m[2]:
456 live = True
457 else:
458 if live and m[3]:
459 live = False
460 if not live:
461 for x in ins["args"]:
462 if x.get("k") == "special" and x.get("t") in ("scc", "src_scc"):
463 live = True
464 break
203 return out 465 return out
204 466
205 467
206def _operand_scalar_mask(x): 468def _operand_scalar_mask(x):
207 """Bitmask of scalar registers (s0..s127, vcc, scc, m0) named by operand `x`.""" 469 """Bitmask of scalar registers (s0..s127, vcc, scc, m0) named by operand `x`."""
208 k = x.get("k") 470 k = x.get("k")
209 if k == "slist":
210 m = 0
211 for item in x.get("r", ()):
212 if isinstance(item, int):
213 if 0 <= item < 128:
214 m |= 1 << item
215 elif isinstance(item, str) and item.startswith("vcc"):
216 m |= 1 << _BIT_VCC
217 return m
218 if k == "sgpr": 471 if k == "sgpr":
219 r = x["r"] 472 r = x["r"]
220 cnt = x.get("n", 1) 473 cnt = x.get("n", 1)
221 m = 0 474 if cnt == 1:
222 for i in range(cnt): 475 return (1 << r) if 0 <= r < 128 else 0
223 if 0 <= r + i < 128: 476 lo = 0 if r < 0 else r
224 m |= 1 << (r + i) 477 hi = r + cnt
225 return m 478 if hi > 128:
479 hi = 128
480 return (((1 << (hi - lo)) - 1) << lo) if hi > lo else 0
226 if k == "special": 481 if k == "special":
227 t = x.get("t", "") 482 t = x.get("t", "")
228 if t.startswith("vcc"): 483 if t.startswith("vcc"):
@@ -231,121 +486,152 @@ def _operand_scalar_mask(x):
231 return 1 << _BIT_SCC 486 return 1 << _BIT_SCC
232 if t == "m0": 487 if t == "m0":
233 return 1 << _BIT_M0 488 return 1 << _BIT_M0
489 return 0
490 if k == "slist":
491 m = 0
492 for item in x.get("r", ()):
493 if isinstance(item, int):
494 if 0 <= item < 128:
495 m |= 1 << item
496 elif isinstance(item, str) and item.startswith("vcc"):
497 m |= 1 << _BIT_VCC
498 return m
234 return 0 499 return 0
235 500
236 501
237def _scalar_rw(ins): 502def _scalar_rw_with_meta(ins, meta):
238 """Return `(read_mask, may_write_mask, must_kill_mask)` over scalar bits 0..130 for `ins`.""" 503 """Return `(read_mask, may_write_mask, must_kill_mask)` over scalar bits 0..130 for `ins`."""
239 op = base_op(ins["op"]) 504 rw_mode = meta[4]
240 a = ins["args"] 505 if rw_mode == _RW_MOVREL:
241 mods = ins.get("mods") or ()
242 # Dynamic SGPR indexing reads/writes arbitrary SGPRs + m0: never kill, conservatively read/write all SGPRs.
243 if op.startswith("s_movrel"):
244 return _ALL_SGPRS | (1 << _BIT_M0), _ALL_SGPRS, 0 506 return _ALL_SGPRS | (1 << _BIT_M0), _ALL_SGPRS, 0
245 if op == "s_endpgm" or op in BRANCHES: 507 if rw_mode == _RW_TERM:
246 rd = 0 508 return meta[5], 0, 0
247 if op in ("s_cbranch_scc0", "s_cbranch_scc1"):
248 rd |= 1 << _BIT_SCC
249 elif op in ("s_cbranch_vccz", "s_cbranch_vccnz"):
250 rd |= 1 << _BIT_VCC
251 return rd, 0, 0
252 # Split destination vs source operands conservatively.
253 dests, srcs = [], list(a)
254 if op.startswith(("s_cmp", "s_bitcmp")) or op.startswith("v_cmpx") or op.startswith(_NO_DEST_PREFIXES):
255 dests, srcs = [], list(a)
256 elif op.startswith("v_cmp"):
257 if len(a) == 2:
258 dests, srcs = [], list(a)
259 elif a:
260 dests, srcs = [a[0]], list(a[1:])
261 elif op.startswith(("buffer_atomic", "global_atomic", "flat_atomic", "image_atomic")):
262 dests = [a[0]] if ("glc" in mods and a) else []
263 srcs = list(a)
264 elif op.startswith("ds_"):
265 returns = (op.startswith(("ds_read", "ds_bpermute", "ds_permute", "ds_swizzle", "ds_consume", "ds_append"))
266 or "_rtn" in op)
267 dests, srcs = ([a[0]], list(a[1:])) if (returns and a) else ([], list(a))
268 elif op in ("s_addk_i32", "s_mulk_i32", "s_cmovk_i32", "s_movk_i32") and a:
269 # SOPK reads and writes a[0] (except s_movk_i32 which only writes a[0]).
270 dests = [a[0]]
271 srcs = list(a[1:]) if op == "s_movk_i32" else list(a)
272 elif a:
273 dests, srcs = [a[0]], list(a[1:])
274 if op.startswith("v_") and len(a) > 2 and (
275 "_co_" in op or op in ("v_mad_u64_u32", "v_mad_i64_i32", "v_div_scale_f32", "v_div_scale_f64")) \
276 and a[1].get("k") in ("sgpr", "special", "slist"):
277 dests, srcs = [a[0], a[1]], list(a[2:])
278
279 rd = 0
280 for x in srcs:
281 rd |= _operand_scalar_mask(x)
282 if op in _IMPLICIT_VCC_READS:
283 rd |= 1 << _BIT_VCC
284 if reads_scc(ins):
285 rd |= 1 << _BIT_SCC
286 if op.startswith(("ds_", "s_sendmsg", "v_interp", "v_movrel", "v_swaprel")):
287 rd |= 1 << _BIT_M0
288 if op == "s_cmov_b32" or op == "s_cmov_b64":
289 # Conditional move preserves destination when SCC == 0, so it also reads destination.
290 for d in dests:
291 rd |= _operand_scalar_mask(d)
292 509
293 may_w = 0 510 a = ins["args"]
294 for d in dests: 511 len_a = len(a)
295 may_w |= _operand_scalar_mask(d) 512 vcc_imp_w = 0
296 if op.startswith("v_cmp") and not op.startswith("v_cmpx") and len(a) == 2: 513 if rw_mode == _RW_DEFAULT:
297 may_w |= 1 << _BIT_VCC 514 dest_n = 1 if len_a else 0
298 if writes_scc(ins): 515 src_start = 1
299 may_w |= 1 << _BIT_SCC 516 elif rw_mode == _RW_NO_DEST or rw_mode == _RW_DS_NORET:
300 elif op.startswith("s_") and not op.startswith(("s_mov", "s_cselect", "s_load", "s_buffer_load", "s_getpc", 517 dest_n = 0
301 "s_nop", "s_waitcnt", "s_clause", "s_inst_prefetch", "s_pack", 518 src_start = 0
302 "s_mul_i32", "s_mul_hi", "s_mulk", "s_ff", "s_flbit", "s_bfm", 519 elif rw_mode == _RW_VCMP:
303 "s_get_waveid")): 520 if len_a == 2:
304 # Any uncategorized scalar op could touch SCC: include in may_w (never in must_kill). 521 dest_n = 0
305 may_w |= 1 << _BIT_SCC 522 src_start = 0
306 523 vcc_imp_w = 1 << _BIT_VCC
307 # Only kill registers unconditionally overwritten (never conditional moves or half-VCC writes). 524 else:
308 must_kill = 0 525 dest_n = 1 if len_a else 0
309 if op not in ("s_cmov_b32", "s_cmov_b64", "s_cmovk_i32"): 526 src_start = 1
310 for d in dests: 527 elif rw_mode == _RW_VOP3B:
311 if d.get("k") == "slist": 528 if len_a > 2 and a[1].get("k") in ("sgpr", "special", "slist"):
312 regs = d.get("r", ()) 529 dest_n = 2
313 vcc_halves = {item for item in regs if item in ("vcc_lo", "vcc_hi")} 530 src_start = 2
314 for item in regs: 531 else:
315 if isinstance(item, int): 532 dest_n = 1 if len_a else 0
316 if 0 <= item < 128: 533 src_start = 1
317 must_kill |= 1 << item 534 elif rw_mode == _RW_DS_RET:
318 elif item in ("vcc_lo", "vcc_hi") and vcc_halves == {"vcc_lo", "vcc_hi"}: 535 dest_n = 1 if len_a else 0
319 must_kill |= 1 << _BIT_VCC 536 src_start = 1
537 elif rw_mode == _RW_SOPK_RW:
538 dest_n = 1 if len_a else 0
539 src_start = 0
540 else: # _RW_ATOMIC
541 mods = ins.get("mods")
542 dest_n = 1 if (len_a and mods and "glc" in mods) else 0
543 src_start = 0
544
545 rd = meta[5]
546 may_w = meta[6] | vcc_imp_w
547 flags = meta[8]
548 no_kill_dest = flags & _FLAG_NO_KILL_DEST
549 must_kill = meta[7] | (0 if no_kill_dest else vcc_imp_w)
550 cmov_rd_dest = flags & _FLAG_CMOV_RD_DEST
551
552 for idx in range(len_a):
553 x = a[idx]
554 k = x.get("k")
555 if k == "vgpr" or k == "imm":
556 continue
557 if k == "sgpr":
558 r = x["r"]
559 cnt = x.get("n", 1)
560 if cnt == 1:
561 m = (1 << r) if 0 <= r < 128 else 0
562 else:
563 lo = 0 if r < 0 else r
564 hi = r + cnt
565 if hi > 128:
566 hi = 128
567 m = (((1 << (hi - lo)) - 1) << lo) if hi > lo else 0
568 if idx >= src_start:
569 rd |= m
570 if idx < dest_n:
571 if cmov_rd_dest:
572 rd |= m
573 may_w |= m
574 if not no_kill_dest:
575 must_kill |= m
576 elif k == "special":
577 t = x.get("t", "")
578 if t.startswith("vcc"):
579 m = 1 << _BIT_VCC
580 elif t in ("scc", "src_scc"):
581 m = 1 << _BIT_SCC
582 rd |= m # reads_scc scans all args
583 elif t == "m0":
584 m = 1 << _BIT_M0
585 else:
320 continue 586 continue
321 if d.get("k") == "special" and d.get("t") in ("vcc_lo", "vcc_hi"): 587 if idx >= src_start:
322 continue # half-write preserves the other half in wave64 588 rd |= m
323 must_kill |= _operand_scalar_mask(d) 589 if idx < dest_n:
324 if op.startswith("v_cmp") and not op.startswith("v_cmpx") and len(a) == 2: 590 if cmov_rd_dest:
325 must_kill |= 1 << _BIT_VCC 591 rd |= m
326 if writes_scc(ins): 592 may_w |= m
327 must_kill |= 1 << _BIT_SCC 593 if not no_kill_dest and t not in ("vcc_lo", "vcc_hi"):
594 must_kill |= m
595 elif k == "slist":
596 regs = x.get("r", ())
597 m = 0
598 for item in regs:
599 if isinstance(item, int):
600 if 0 <= item < 128:
601 m |= 1 << item
602 elif isinstance(item, str) and item.startswith("vcc"):
603 m |= 1 << _BIT_VCC
604 if idx >= src_start:
605 rd |= m
606 if idx < dest_n:
607 if cmov_rd_dest:
608 rd |= m
609 may_w |= m
610 if not no_kill_dest:
611 has_lo = False
612 has_hi = False
613 for item in regs:
614 if isinstance(item, int):
615 if 0 <= item < 128:
616 must_kill |= 1 << item
617 elif item == "vcc_lo":
618 has_lo = True
619 elif item == "vcc_hi":
620 has_hi = True
621 if has_lo and has_hi:
622 must_kill |= 1 << _BIT_VCC
623
328 return rd, may_w, must_kill 624 return rd, may_w, must_kill
329 625
330 626
331def _scalar_liveness(active_blocks, succ): 627def _scalar_rw(ins):
332 """Exact conservative backward scalar liveness `live_in[b]` (int bitmask) for each block.""" 628 """Return `(read_mask, may_write_mask, must_kill_mask)` over scalar bits 0..130 for `ins`."""
333 n = len(active_blocks) 629 return _scalar_rw_with_meta(ins, _get_op_meta(ins["op"]))
334 preds = [[] for _ in range(n)] 630
335 for b in range(n): 631
336 for s in succ[b]: 632def _solve_scalar_liveness(use, kill, preds):
337 preds[s].append(b) 633 """Run backward scalar liveness worklist given per-block `(use, kill)` bitmasks and `preds`."""
338 use = [0] * n 634 n = len(use)
339 kill = [0] * n
340 for b, insns in enumerate(active_blocks):
341 u = 0
342 k = 0
343 for ins in insns:
344 rd, _, mk = _scalar_rw(ins)
345 u |= rd & ~k
346 k |= mk
347 use[b] = u
348 kill[b] = k
349 live_in = list(use) 635 live_in = list(use)
350 live_out = [0] * n 636 live_out = [0] * n
351 in_work = [bool(u) for u in live_in] 637 in_work = [bool(u) for u in live_in]
@@ -367,6 +653,32 @@ def _scalar_liveness(active_blocks, succ):
367 return live_in 653 return live_in
368 654
369 655
656def _scalar_liveness(active_blocks, succ):
657 """Exact conservative backward scalar liveness `live_in[b]` (int bitmask) for each block."""
658 n = len(active_blocks)
659 preds = [[] for _ in range(n)]
660 for b in range(n):
661 for s in succ[b]:
662 preds[s].append(b)
663 use = [0] * n
664 kill = [0] * n
665 meta_get = _OP_META_CACHE.get
666 for b, insns in enumerate(active_blocks):
667 u = 0
668 k = 0
669 for ins in insns:
670 raw_op = ins["op"]
671 m = meta_get(raw_op)
672 if m is None:
673 m = _get_op_meta(raw_op)
674 rd, _, mk = _scalar_rw_with_meta(ins, m)
675 u |= rd & ~k
676 k |= mk
677 use[b] = u
678 kill[b] = k
679 return _solve_scalar_liveness(use, kill, preds)
680
681
370def _postdominators(succ): 682def _postdominators(succ):
371 """Immediate post-dominator `ipdom[b]` (Cooper-Harvey-Kennedy on reversed CFG with virtual exit `n`).""" 683 """Immediate post-dominator `ipdom[b]` (Cooper-Harvey-Kennedy on reversed CFG with virtual exit `n`)."""
372 n = len(succ) 684 n = len(succ)
@@ -488,88 +800,79 @@ def _classify_block_body(insns, lane_masks, scc_live, mask_writes):
488 may_w = 0 800 may_w = 0
489 exec_writes = [] 801 exec_writes = []
490 sgpr_write_ops = [] 802 sgpr_write_ops = []
491 empty_stats = (0, False, False, 0, False, False) 803 meta_get = _OP_META_CACHE.get
804 has_mask_writes = bool(mask_writes)
805 has_scc_live = bool(scc_live)
492 806
493 for ins in insns: 807 for ins in insns:
494 raw_op = ins["op"] 808 raw_op = ins["op"]
495 op = base_op(raw_op) 809 m = meta_get(raw_op)
496 if op == "s_endpgm" or op in BRANCHES: 810 if m is None:
811 m = _get_op_meta(raw_op)
812 if m[1]:
497 break 813 break
498 if id(ins) in mask_writes: 814 if has_mask_writes and id(ins) in mask_writes:
499 # write_all_lanes VGPR store (parked lane mask): runs even when EXEC == 0, so must not be skipped. 815 # write_all_lanes VGPR store (parked lane mask): runs even when EXEC == 0, so must not be skipped.
500 return False, empty_stats, 0, (), () 816 return False, _EMPTY_MEM_STATS, 0, (), ()
501 a = ins["args"] 817 flags = m[8]
502 lm = lane_masks.get(id(ins), {})
503
504 # 1. Strictly forbidden opcodes inside a lane-local folded region (cross-lane, barrier, unmasked writes). 818 # 1. Strictly forbidden opcodes inside a lane-local folded region (cross-lane, barrier, unmasked writes).
505 if raw_op.endswith(("_dpp", "_dpp8")): 819 if flags & _FLAG_FORBIDDEN_FOLD:
506 return False, empty_stats, 0, (), () 820 return False, _EMPTY_MEM_STATS, 0, (), ()
507 if op in ("s_barrier", "s_sendmsg", "s_setpc_b64", "s_swappc_b64", "s_trap", 821
508 "s_sethalt", "s_setkill", "s_sleep", "s_setprio", 822 acc = m[9]
509 "s_round_mode", "s_denorm_mode",
510 "v_readlane_b32", "v_readfirstlane_b32", "v_writelane_b32",
511 "v_permlane16_b32", "v_permlanex16_b32",
512 "ds_bpermute_b32", "ds_permute_b32", "ds_swizzle_b32",
513 "ds_gws_init", "ds_gws_sema_v", "ds_gws_sema_br", "ds_gws_sema_p", "ds_gws_barrier",
514 "ds_consume", "ds_append", "ds_ordered_count",
515 "s_wqm_b32", "s_wqm_b64", "s_quadmask_b32", "s_quadmask_b64"):
516 return False, empty_stats, 0, (), ()
517 if op.startswith(("s_movrel", "s_setreg", "s_getreg", "s_store", "s_buffer_store", "s_atomic",
518 "ds_gws", "exp")):
519 return False, empty_stats, 0, (), ()
520
521 acc = _x_memory_order_access(op)
522 if acc is not None: 823 if acc is not None:
523 kind, r, w = acc 824 kind, r, w = acc
524 if kind == "lds": 825 if kind == "lds":
525 lds_ops += 1 826 lds_ops += 1
526 lds_r = lds_r or r 827 if r:
527 lds_w = lds_w or w 828 lds_r = True
829 if w:
830 lds_w = True
528 else: 831 else:
529 mem_ops += 1 832 mem_ops += 1
530 mem_r = mem_r or r 833 if r:
531 mem_w = mem_w or w
532 elif op.startswith("scratch_"):
533 if "store" in op or "atomic" in op:
534 mem_ops += 1
535 mem_w = True
536 if "atomic" in op:
537 mem_r = True 834 mem_r = True
538 else: 835 if w:
836 mem_w = True
837 else:
838 sacc = m[10]
839 if sacc is not None:
539 mem_ops += 1 840 mem_ops += 1
540 mem_r = True 841 if sacc[0]:
541 elif op.startswith(("image_sample", "image_gather", "image_bvh")): 842 mem_r = True
542 pass # read-only sampled-image / BVH queries: not ordered against buffer/image stores by x_memory_order 843 if sacc[1]:
543 elif "store" in op or "atomic" in op: 844 mem_w = True
544 return False, empty_stats, 0, (), ()
545 845
546 # 2. Cross-lane mask readers (`wave_mask`, `wave_equal`, live-SCC `scc_from_mask`). 846 # 2. Cross-lane mask readers (`wave_mask`, `wave_equal`, live-SCC `scc_from_mask`).
547 if op in _MASK_WORD_READERS: 847 a = ins["args"]
548 if len(a) > 1 and _holds_lane_mask(ins, a[1], lm): 848 mask_chk = m[11]
549 return False, empty_stats, 0, (), () 849 if mask_chk:
550 elif op in ("v_mbcnt_lo_u32_b32", "v_mbcnt_hi_u32_b32"): 850 if mask_chk == _MASK_CHK_SCC_VOTE:
551 if len(a) > 1 and a[1].get("k") != "imm" and _holds_lane_mask(ins, a[1], lm): 851 if has_scc_live and id(ins) in scc_live:
552 return False, empty_stats, 0, (), () 852 if (flags & _FLAG_SCC_VOTE_ALWAYS_MASK) or (bool(a) and _has_vcc_or_exec(a[0])):
553 elif op.startswith(("s_cmp", "s_bitcmp")): 853 return False, _EMPTY_MEM_STATS, 0, (), ()
554 if any(_holds_lane_mask(ins, x, lm) for x in a): 854 lm = lane_masks.get(id(ins), {})
555 return False, empty_stats, 0, (), () 855 if any(_is_mask_op(ins, x, lm) for x in a[1:]):
556 elif op in _MASK_SCC_VOTE_OPS and id(ins) in scc_live: 856 return False, _EMPTY_MEM_STATS, 0, (), ()
557 # Would emit scc_from_mask -> x_round if operating on a lane mask (matches Gen.is_mask_op). 857 elif mask_chk == _MASK_CHK_WORD_READER:
558 is_mask_dst = bool(a) and _has_vcc_or_exec(a[0]) 858 if len(a) > 1 and _holds_lane_mask(ins, a[1], lane_masks.get(id(ins), {})):
559 if "saveexec" in op or "wrexec" in op or op.endswith("_mask") or is_mask_dst \ 859 return False, _EMPTY_MEM_STATS, 0, (), ()
560 or any(_is_mask_op(ins, x, lm) for x in a[1:]): 860 elif mask_chk == _MASK_CHK_MBCNT:
561 return False, empty_stats, 0, (), () 861 if len(a) > 1 and a[1].get("k") != "imm" and _holds_lane_mask(ins, a[1], lane_masks.get(id(ins), {})):
862 return False, _EMPTY_MEM_STATS, 0, (), ()
863 else: # _MASK_CHK_SCMP
864 lm = lane_masks.get(id(ins), {})
865 if any(_holds_lane_mask(ins, x, lm) for x in a):
866 return False, _EMPTY_MEM_STATS, 0, (), ()
562 867
563 # 3. Track scalar writes and EXEC writes. 868 # 3. Track scalar writes and EXEC writes.
564 _, ins_mw, _ = _scalar_rw(ins) 869 _, ins_mw, _ = _scalar_rw_with_meta(ins, m)
565 may_w |= ins_mw 870 may_w |= ins_mw
566 s_bits = ins_mw & _ALL_SGPRS 871 s_bits = ins_mw & _ALL_SGPRS
567 if s_bits: 872 if s_bits:
568 sgpr_write_ops.append((s_bits, op, a)) 873 sgpr_write_ops.append((s_bits, m[0], a))
569 writes_exec = (op.startswith("v_cmpx") or "saveexec" in op or "wrexec" in op 874 if (flags & _FLAG_WRITES_EXEC_OP) or (bool(a) and a[0].get("k") == "special" and a[0].get("t", "").startswith("exec")):
570 or (bool(a) and a[0].get("k") == "special" and a[0].get("t", "").startswith("exec"))) 875 exec_writes.append((m[0], a))
571 if writes_exec:
572 exec_writes.append((op, a))
573 876
574 return True, (mem_ops, mem_r, mem_w, lds_ops, lds_r, lds_w), may_w, exec_writes, sgpr_write_ops 877 return True, (mem_ops, mem_r, mem_w, lds_ops, lds_r, lds_w), may_w, exec_writes, sgpr_write_ops
575 878
@@ -618,6 +921,13 @@ def _exec_writes_stay_inactive(region_blocks, blk_info, run_live_in):
618 `s[r:r+1]` and every write to `EXEC` produces 0 whenever `EXEC == 0` and all such pairs are 0, then 921 `s[r:r+1]` and every write to `EXEC` produces 0 whenever `EXEC == 0` and all such pairs are 0, then
619 an inactive lane stays inactive across arbitrary nested / reused saveexec if-else diamonds. 922 an inactive lane stays inactive across arbitrary nested / reused saveexec if-else diamonds.
620 """ 923 """
924 has_exec_write = False
925 for u in region_blocks:
926 if blk_info[u][3]:
927 has_exec_write = True
928 break
929 if not has_exec_write:
930 return True
621 sgpr_writers = collections.defaultdict(list) 931 sgpr_writers = collections.defaultdict(list)
622 for u in region_blocks: 932 for u in region_blocks:
623 for item in blk_info[u][4]: 933 for item in blk_info[u][4]:
@@ -627,11 +937,10 @@ def _exec_writes_stay_inactive(region_blocks, blk_info, run_live_in):
627 sgpr_writers[lsb.bit_length() - 1].append(item) 937 sgpr_writers[lsb.bit_length() - 1].append(item)
628 s_bits ^= lsb 938 s_bits ^= lsb
629 zero_pairs = set() 939 zero_pairs = set()
630 for r in range(127): 940 for r, w0 in sgpr_writers.items():
631 if (3 << r) & run_live_in: 941 if r >= 127 or ((3 << r) & run_live_in):
632 continue # entry value could be read before first write in R 942 continue # entry value could be read before first write in R
633 w0 = sgpr_writers.get(r) 943 if w0 != sgpr_writers.get(r + 1):
634 if not w0 or w0 != sgpr_writers.get(r + 1):
635 continue 944 continue
636 pair_mask = 3 << r 945 pair_mask = 3 << r
637 if all(s_bits == pair_mask and bool(a) and _sgpr_pair(a[0]) == r for s_bits, _, a in w0): 946 if all(s_bits == pair_mask and bool(a) and _sgpr_pair(a[0]) == r for s_bits, _, a in w0):
@@ -833,20 +1142,115 @@ def find_local_exec_folds(blocks, raw_edges, succ, lane_masks, scc_live, mask_wr
833 preds[s].add(b) 1142 preds[s].add(b)
834 1143
835 ipdom = _postdominators(succ) 1144 ipdom = _postdominators(succ)
836 scalar_live_in = _scalar_liveness(active_blocks, succ)
837 1145
838 blk_info = [] 1146 # Single fused pass over active_blocks: compute scalar liveness (use/kill),
839 terms = [] 1147 # block-body classification (blk_info), and block terminators (terms).
1148 use = [0] * n
1149 kill = [0] * n
1150 blk_info = [None] * n
1151 terms = [None] * n
1152 meta_get = _OP_META_CACHE.get
1153 has_mask_writes = bool(mask_writes)
1154 has_scc_live = bool(scc_live)
1155
840 for b, insns in enumerate(active_blocks): 1156 for b, insns in enumerate(active_blocks):
841 blk_info.append(_classify_block_body(insns, lane_masks, scc_live, mask_writes)) 1157 u_mask = 0
842 last = insns[-1] if insns else None 1158 k_mask = 0
843 op = base_op(last["op"]) if last is not None else None 1159 clean = True
844 if op == "s_endpgm": 1160 mem_ops = lds_ops = 0
845 terms.append(("end", None)) 1161 mem_r = mem_w = lds_r = lds_w = False
846 elif op in BRANCHES: 1162 may_w = 0
847 terms.append(("br", op)) 1163 exec_writes = []
1164 sgpr_write_ops = []
1165 term = ("fall", None)
1166
1167 for ins in insns:
1168 raw_op = ins["op"]
1169 m = meta_get(raw_op)
1170 if m is None:
1171 m = _get_op_meta(raw_op)
1172 rd, ins_mw, mk = _scalar_rw_with_meta(ins, m)
1173 u_mask |= rd & ~k_mask
1174 k_mask |= mk
1175 if m[1]:
1176 op = m[0]
1177 term = ("end", None) if op == "s_endpgm" else ("br", op)
1178 break
1179 if not clean:
1180 continue
1181 if has_mask_writes and id(ins) in mask_writes:
1182 clean = False
1183 continue
1184 flags = m[8]
1185 if flags & _FLAG_FORBIDDEN_FOLD:
1186 clean = False
1187 continue
1188 acc = m[9]
1189 if acc is not None:
1190 kind, r, w = acc
1191 if kind == "lds":
1192 lds_ops += 1
1193 if r:
1194 lds_r = True
1195 if w:
1196 lds_w = True
1197 else:
1198 mem_ops += 1
1199 if r:
1200 mem_r = True
1201 if w:
1202 mem_w = True
1203 else:
1204 sacc = m[10]
1205 if sacc is not None:
1206 mem_ops += 1
1207 if sacc[0]:
1208 mem_r = True
1209 if sacc[1]:
1210 mem_w = True
1211
1212 a = ins["args"]
1213 mask_chk = m[11]
1214 if mask_chk:
1215 if mask_chk == _MASK_CHK_SCC_VOTE:
1216 if has_scc_live and id(ins) in scc_live:
1217 if (flags & _FLAG_SCC_VOTE_ALWAYS_MASK) or (bool(a) and _has_vcc_or_exec(a[0])):
1218 clean = False
1219 continue
1220 lm = lane_masks.get(id(ins), {})
1221 if any(_is_mask_op(ins, x, lm) for x in a[1:]):
1222 clean = False
1223 continue
1224 elif mask_chk == _MASK_CHK_WORD_READER:
1225 if len(a) > 1 and _holds_lane_mask(ins, a[1], lane_masks.get(id(ins), {})):
1226 clean = False
1227 continue
1228 elif mask_chk == _MASK_CHK_MBCNT:
1229 if len(a) > 1 and a[1].get("k") != "imm" and _holds_lane_mask(ins, a[1], lane_masks.get(id(ins), {})):
1230 clean = False
1231 continue
1232 else: # _MASK_CHK_SCMP
1233 lm = lane_masks.get(id(ins), {})
1234 if any(_holds_lane_mask(ins, x, lm) for x in a):
1235 clean = False
1236 continue
1237
1238 may_w |= ins_mw
1239 s_bits = ins_mw & _ALL_SGPRS
1240 if s_bits:
1241 sgpr_write_ops.append((s_bits, m[0], a))
1242 if (flags & _FLAG_WRITES_EXEC_OP) or (bool(a) and a[0].get("k") == "special" and a[0].get("t", "").startswith("exec")):
1243 exec_writes.append((m[0], a))
1244
1245 use[b] = u_mask
1246 kill[b] = k_mask
1247 terms[b] = term
1248 if clean:
1249 blk_info[b] = (True, (mem_ops, mem_r, mem_w, lds_ops, lds_r, lds_w), may_w, exec_writes, sgpr_write_ops)
848 else: 1250 else:
849 terms.append(("fall", None)) 1251 blk_info[b] = (False, _EMPTY_MEM_STATS, 0, (), ())
1252
1253 scalar_live_in = _solve_scalar_liveness(use, kill, preds)
850 1254
851 # Gather candidate s_cbranch_execz / s_cbranch_execnz blocks with single-entry/single-exit post-dominated regions. 1255 # Gather candidate s_cbranch_execz / s_cbranch_execnz blocks with single-entry/single-exit post-dominated regions.
852 candidates = [] 1256 candidates = []
@@ -1014,56 +1418,59 @@ def find_local_exec_folds(blocks, raw_edges, succ, lane_masks, scc_live, mask_wr
1014 return selected, fold_chain, absorbed 1418 return selected, fold_chain, absorbed
1015 1419
1016 1420
1017_SOP2_B32_LOGIC = frozenset({
1018 "s_and_b32", "s_or_b32", "s_xor_b32", "s_andn2_b32", "s_orn2_b32",
1019 "s_nand_b32", "s_nor_b32", "s_xnor_b32", "s_not_b32",
1020})
1021
1022
1023def _is_uniform_scc_safe(active_blocks, lane_masks, scc_live): 1421def _is_uniform_scc_safe(active_blocks, lane_masks, scc_live):
1024 """True iff no instruction triggers wave64's per-lane 32-bit half-mask SCC write (rdna2spirv.py scc_logic) 1422 """True iff no instruction triggers wave64's per-lane 32-bit half-mask SCC write (rdna2spirv.py scc_logic)
1025 with live SCC. When True, %scc is guaranteed identical across all 64 lanes of each wave.""" 1423 with live SCC. When True, %scc is guaranteed identical across all 64 lanes of each wave."""
1424 if not scc_live:
1425 return True
1426 meta_get = _OP_META_CACHE.get
1026 for insns in active_blocks: 1427 for insns in active_blocks:
1027 for ins in insns: 1428 for ins in insns:
1028 op = base_op(ins["op"]) 1429 ins_id = id(ins)
1029 if op not in _SOP2_B32_LOGIC or id(ins) not in scc_live: 1430 if ins_id not in scc_live:
1431 continue
1432 raw_op = ins["op"]
1433 m = meta_get(raw_op)
1434 if m is None:
1435 m = _get_op_meta(raw_op)
1436 if not (m[8] & _FLAG_SOP2_B32_LOGIC):
1030 continue 1437 continue
1031 a = ins["args"] 1438 a = ins["args"]
1032 lm = lane_masks.get(id(ins), {}) 1439 lm = lane_masks.get(ins_id, {})
1033 writes_exec = bool(a) and a[0].get("k") == "special" and a[0].get("t", "").startswith("exec") 1440 writes_exec = bool(a) and a[0].get("k") == "special" and a[0].get("t", "").startswith("exec")
1034 if writes_exec or any(_holds_lane_mask(ins, x, lm) for x in a[1:]): 1441 if writes_exec or any(_holds_lane_mask(ins, x, lm) for x in a[1:]):
1035 return False 1442 return False
1036 return True 1443 return True
1037 1444
1038 1445
1039def _insn_may_barrier(ins, lane_masks, scc_live): 1446def _insn_may_barrier_with_meta(ins, meta, lane_masks, scc_live):
1040 """Conservative (over-approximate) check: True if `ins` may emit x_round or OpControlBarrier in --wave64-emulate.""" 1447 if meta[1]:
1041 raw_op = ins["op"]
1042 op = base_op(raw_op)
1043 if op == "s_endpgm" or op in BRANCHES:
1044 return False 1448 return False
1045 if raw_op.endswith(("_dpp", "_dpp8")): 1449 flags = meta[8]
1046 return True 1450 if flags & _FLAG_ALWAYS_BARRIER:
1047 if op in ("s_barrier", "v_readlane_b32", "v_readfirstlane_b32",
1048 "v_permlane16_b32", "v_permlanex16_b32",
1049 "ds_bpermute_b32", "ds_permute_b32", "ds_swizzle_b32",
1050 "s_wqm_b32", "s_wqm_b64"):
1051 return True
1052 if op.startswith("s_movrel"):
1053 return True 1451 return True
1452 mask_chk = meta[11]
1453 if not mask_chk:
1454 return False
1054 a = ins["args"] 1455 a = ins["args"]
1456 if mask_chk == _MASK_CHK_SCC_VOTE:
1457 if not scc_live or id(ins) not in scc_live:
1458 return False
1459 if (flags & _FLAG_SCC_VOTE_ALWAYS_MASK) or (bool(a) and _has_vcc_or_exec(a[0])):
1460 return True
1461 lm = lane_masks.get(id(ins), {})
1462 return any(_is_mask_op(ins, x, lm) for x in a[1:])
1463 if mask_chk == _MASK_CHK_WORD_READER:
1464 return len(a) > 1 and _holds_lane_mask(ins, a[1], lane_masks.get(id(ins), {}))
1465 if mask_chk == _MASK_CHK_MBCNT:
1466 return len(a) > 1 and a[1].get("k") != "imm" and _holds_lane_mask(ins, a[1], lane_masks.get(id(ins), {}))
1055 lm = lane_masks.get(id(ins), {}) 1467 lm = lane_masks.get(id(ins), {})
1056 if op in _MASK_WORD_READERS: 1468 return any(_holds_lane_mask(ins, x, lm) for x in a)
1057 return len(a) > 1 and _holds_lane_mask(ins, a[1], lm) 1469
1058 if op in ("v_mbcnt_lo_u32_b32", "v_mbcnt_hi_u32_b32"): 1470
1059 return len(a) > 1 and a[1].get("k") != "imm" and _holds_lane_mask(ins, a[1], lm) 1471def _insn_may_barrier(ins, lane_masks, scc_live):
1060 if op.startswith(("s_cmp", "s_bitcmp")): 1472 """Conservative (over-approximate) check: True if `ins` may emit x_round or OpControlBarrier in --wave64-emulate."""
1061 return any(_holds_lane_mask(ins, x, lm) for x in a) 1473 return _insn_may_barrier_with_meta(ins, _get_op_meta(ins["op"]), lane_masks, scc_live)
1062 if op in _MASK_SCC_VOTE_OPS and id(ins) in scc_live:
1063 is_mask_dst = bool(a) and _has_vcc_or_exec(a[0])
1064 return ("saveexec" in op or "wrexec" in op or op.endswith("_mask") or is_mask_dst
1065 or any(_is_mask_op(ins, x, lm) for x in a[1:]))
1066 return False
1067 1474
1068 1475
1069def _dirty_conflicts(dirty, reads, writes): 1476def _dirty_conflicts(dirty, reads, writes):
@@ -1142,6 +1549,9 @@ def plan_structured_emulation(blocks, raw_edges, succ, folds, fold_chain, absorb
1142 sb_has_endpgm = {} 1549 sb_has_endpgm = {}
1143 sb_may_barrier = {} 1550 sb_may_barrier = {}
1144 sb_mem_stats = {} 1551 sb_mem_stats = {}
1552 sb_clears_dirty = {}
1553 sb_gen_dirty = {}
1554 meta_get = _OP_META_CACHE.get
1145 1555
1146 for b in eff_blocks: 1556 for b in eff_blocks:
1147 has_sb = False 1557 has_sb = False
@@ -1149,114 +1559,104 @@ def plan_structured_emulation(blocks, raw_edges, succ, folds, fold_chain, absorb
1149 may_bar = False 1559 may_bar = False
1150 mem_ops = lds_ops = 0 1560 mem_ops = lds_ops = 0
1151 mem_r = mem_w = lds_r = lds_w = False 1561 mem_r = mem_w = lds_r = lds_w = False
1562 clears_dirty = False
1563 gen_dirty = 0
1152 chain = chain_of[b] 1564 chain = chain_of[b]
1565 last_c = len(chain) - 1
1153 for idx_c, cur in enumerate(chain): 1566 for idx_c, cur in enumerate(chain):
1154 insns = active_blocks[cur] 1567 insns = active_blocks[cur]
1155 for ins in insns: 1568 for ins in insns:
1156 op = base_op(ins["op"]) 1569 raw_op = ins["op"]
1157 if op == "s_endpgm": 1570 m = meta_get(raw_op)
1158 has_end = True 1571 if m is None:
1159 break 1572 m = _get_op_meta(raw_op)
1160 if op in BRANCHES: 1573 op = m[0]
1161 if idx_c == len(chain) - 1 and cur not in folds: 1574 if m[1]:
1162 if op in ("s_cbranch_execz", "s_cbranch_execnz", "s_cbranch_vccz", "s_cbranch_vccnz"): 1575 if op == "s_endpgm":
1163 may_bar = True 1576 has_end = True
1577 elif idx_c == last_c and cur not in folds and (m[8] & _FLAG_VOTED_BRANCH):
1578 may_bar = True
1579 clears_dirty = True
1580 gen_dirty = 0
1164 break 1581 break
1165 if op == "s_barrier": 1582 if op == "s_barrier":
1166 has_sb = True 1583 has_sb = True
1167 may_bar = True 1584 may_bar = True
1168 elif _insn_may_barrier(ins, lane_masks, scc_live): 1585 clears_dirty = True
1586 gen_dirty = 0
1587 continue
1588 if not may_bar and _insn_may_barrier_with_meta(ins, m, lane_masks, scc_live):
1169 may_bar = True 1589 may_bar = True
1170 acc = _x_memory_order_access(op) 1590 acc = m[9]
1171 if acc is not None: 1591 if acc is not None:
1172 kind, r, w = acc 1592 kind, r, w = acc
1173 if kind == "lds": 1593 if kind == "lds":
1174 lds_ops += 1 1594 lds_ops += 1
1175 lds_r = lds_r or r 1595 if r:
1176 lds_w = lds_w or w 1596 lds_r = True
1597 if w:
1598 lds_w = True
1177 else: 1599 else:
1178 mem_ops += 1 1600 mem_ops += 1
1179 mem_r = mem_r or r 1601 if r:
1180 mem_w = mem_w or w
1181 elif op.startswith("scratch_"):
1182 mem_ops += 1
1183 if "store" in op or "atomic" in op:
1184 mem_w = True
1185 if "atomic" in op:
1186 mem_r = True 1602 mem_r = True
1187 else: 1603 if w:
1188 mem_r = True 1604 mem_w = True
1605 gen_dirty |= m[12]
1606 else:
1607 sacc = m[10]
1608 if sacc is not None:
1609 mem_ops += 1
1610 if sacc[0]:
1611 mem_r = True
1612 if sacc[1]:
1613 mem_w = True
1189 if cur in folds: 1614 if cur in folds:
1190 mo, mr, mw, lo, lr, lw = folds[cur]["mem_stats"] 1615 fd = folds[cur]
1616 mo, mr, mw, lo, lr, lw = fd["mem_stats"]
1191 mem_ops += mo 1617 mem_ops += mo
1192 mem_r = mem_r or mr 1618 if mr:
1193 mem_w = mem_w or mw 1619 mem_r = True
1620 if mw:
1621 mem_w = True
1194 lds_ops += lo 1622 lds_ops += lo
1195 lds_r = lds_r or lr 1623 if lr:
1196 lds_w = lds_w or lw 1624 lds_r = True
1625 if lw:
1626 lds_w = True
1627 for k in fd["mem_reads"]:
1628 gen_dirty |= _DIRTY_LDS_R if k == "lds" else _DIRTY_MEM_R
1629 for k in fd["mem_writes"]:
1630 gen_dirty |= _DIRTY_LDS_W if k == "lds" else _DIRTY_MEM_W
1197 sb_has_sbarrier[b] = has_sb 1631 sb_has_sbarrier[b] = has_sb
1198 sb_has_endpgm[b] = has_end 1632 sb_has_endpgm[b] = has_end
1199 sb_may_barrier[b] = may_bar 1633 sb_may_barrier[b] = may_bar
1200 sb_mem_stats[b] = (mem_ops, mem_r, mem_w, lds_ops, lds_r, lds_w) 1634 sb_mem_stats[b] = (mem_ops, mem_r, mem_w, lds_ops, lds_r, lds_w)
1201 1635 sb_clears_dirty[b] = clears_dirty
1202 def transfer_superblock(b, d_in): 1636 sb_gen_dirty[b] = gen_dirty
1203 """Strictly monotone GEN/KILL dirty transfer over superblock `b`.
1204
1205 Only unconditional barriers (`s_barrier` and voted branches `s_cbranch_execz/nz/vccz/nz`) clear `d`.
1206 Never clears on `d_in`-induced or intra-block memory conflicts: if an earlier `x_round` (e.g.
1207 `v_readlane_b32`) or an earlier conflict cleared `g.x_dirty` in codegen, a phantom clear here could
1208 wipe a live dirty domain written afterward and drop a required cross-block `OpControlBarrier`.
1209 """
1210 d = set(d_in)
1211 chain = chain_of[b]
1212 for idx_c, cur in enumerate(chain):
1213 insns = active_blocks[cur]
1214 for ins in insns:
1215 op = base_op(ins["op"])
1216 if op == "s_endpgm":
1217 break
1218 if op in BRANCHES:
1219 if idx_c == len(chain) - 1 and cur not in folds:
1220 if op in ("s_cbranch_execz", "s_cbranch_execnz", "s_cbranch_vccz", "s_cbranch_vccnz"):
1221 d.clear() # branch_condition unconditionally runs g_vote -> x_round -> barrier
1222 break
1223 if op == "s_barrier":
1224 d.clear()
1225 continue
1226 acc = _x_memory_order_access(op)
1227 if acc is not None:
1228 kind, r, w = acc
1229 if r:
1230 d.add((kind, "r"))
1231 if w:
1232 d.add((kind, "w"))
1233 if cur in folds:
1234 fd = folds[cur]
1235 for k in fd["mem_reads"]:
1236 d.add((k, "r"))
1237 for k in fd["mem_writes"]:
1238 d.add((k, "w"))
1239 return frozenset(d)
1240 1637
1241 # ---- Mode 1: Single-wave (`x_lanes == 64`) -> 100% inline structured SPIR-V, 0 OpSwitch ---- 1638 # ---- Mode 1: Single-wave (`x_lanes == 64`) -> 100% inline structured SPIR-V, 0 OpSwitch ----
1242 if x_lanes == 64: 1639 if x_lanes == 64:
1243 dirty_in = {b: set() for b in eff_blocks} 1640 dirty_in = {b: 0 for b in eff_blocks}
1244 work = collections.deque(eff_blocks) 1641 work = collections.deque(eff_blocks)
1245 in_work = set(eff_blocks) 1642 in_work = set(eff_blocks)
1246 while work: 1643 while work:
1247 u = work.popleft() 1644 u = work.popleft()
1248 in_work.discard(u) 1645 in_work.discard(u)
1249 d_out = transfer_superblock(u, dirty_in[u]) 1646 d_out = sb_gen_dirty[u] if sb_clears_dirty[u] else (dirty_in[u] | sb_gen_dirty[u])
1250 for v in eff_succ[u]: 1647 if d_out:
1251 if not d_out <= dirty_in[v]: 1648 for v in eff_succ[u]:
1252 dirty_in[v].update(d_out) 1649 old_v = dirty_in[v]
1253 if v not in in_work: 1650 new_v = old_v | d_out
1254 in_work.add(v) 1651 if new_v != old_v:
1255 work.append(v) 1652 dirty_in[v] = new_v
1653 if v not in in_work:
1654 in_work.add(v)
1655 work.append(v)
1256 return { 1656 return {
1257 "mode": "inline_all", 1657 "mode": "inline_all",
1258 "tree": tree, 1658 "tree": tree,
1259 "dirty_in": {b: frozenset(d) for b, d in dirty_in.items()}, 1659 "dirty_in": {b: _DIRTY_MASK_TO_FROZENSET[d] for b, d in dirty_in.items()},
1260 "inline_blocks": set(eff_blocks), 1660 "inline_blocks": set(eff_blocks),
1261 "sync_free_blocks": set(), 1661 "sync_free_blocks": set(),
1262 "mini_of_block": {}, 1662 "mini_of_block": {},
@@ -1352,7 +1752,7 @@ def plan_structured_emulation(blocks, raw_edges, succ, folds, fold_chain, absorb
1352 mini_of_block = {} 1752 mini_of_block = {}
1353 mini_blocks = {} 1753 mini_blocks = {}
1354 tail_blocks = set() 1754 tail_blocks = set()
1355 cur_dirty = frozenset() 1755 cur_dirty = 0
1356 mini_idx = 0 1756 mini_idx = 0
1357 1757
1358 for idx_it, it in enumerate(flat_top): 1758 for idx_it, it in enumerate(flat_top):
@@ -1360,9 +1760,9 @@ def plan_structured_emulation(blocks, raw_edges, succ, folds, fold_chain, absorb
1360 has_end = any(sb_has_endpgm[u] for u in it_blocks) 1760 has_end = any(sb_has_endpgm[u] for u in it_blocks)
1361 if it[0] == "block" and (not has_end or idx_it == len(flat_top) - 1): 1761 if it[0] == "block" and (not has_end or idx_it == len(flat_top) - 1):
1362 b = it[1] 1762 b = it[1]
1363 dirty_in[b] = cur_dirty 1763 dirty_in[b] = _DIRTY_MASK_TO_FROZENSET[cur_dirty]
1364 inline_blocks.add(b) 1764 inline_blocks.add(b)
1365 cur_dirty = transfer_superblock(b, cur_dirty) 1765 cur_dirty = sb_gen_dirty[b] if sb_clears_dirty[b] else (cur_dirty | sb_gen_dirty[b])
1366 steps.append(("inline_block", b)) 1766 steps.append(("inline_block", b))
1367 continue 1767 continue
1368 if has_end: 1768 if has_end:
@@ -1372,24 +1772,25 @@ def plan_structured_emulation(blocks, raw_edges, succ, folds, fold_chain, absorb
1372 rem.update(_blocks_in_tree(rem_it)) 1772 rem.update(_blocks_in_tree(rem_it))
1373 tail_blocks = rem 1773 tail_blocks = rem
1374 steps.append(("tail_scheduler", rem, bool(cur_dirty))) 1774 steps.append(("tail_scheduler", rem, bool(cur_dirty)))
1375 cur_dirty = frozenset() 1775 cur_dirty = 0
1376 break 1776 break
1377 ok_sf, sf_reads, sf_writes = check_sync_free(it) 1777 ok_sf, sf_reads, sf_writes = check_sync_free(it)
1378 if ok_sf: 1778 if ok_sf:
1379 pre_bar = _dirty_conflicts(cur_dirty, sf_reads, sf_writes) 1779 pre_bar = _dirty_conflicts(_DIRTY_MASK_TO_FROZENSET[cur_dirty], sf_reads, sf_writes)
1380 if pre_bar: 1780 if pre_bar:
1381 cur_dirty = frozenset() 1781 cur_dirty = 0
1382 for u in it_blocks: 1782 for u in it_blocks:
1383 dirty_in[u] = frozenset() # pre_bar cleared conflicts before entering sync-free region 1783 dirty_in[u] = frozenset() # pre_bar cleared conflicts before entering sync-free region
1384 inline_blocks.add(u) 1784 inline_blocks.add(u)
1385 sync_free_blocks.add(u) 1785 sync_free_blocks.add(u)
1386 cur_dirty = frozenset(set(cur_dirty) 1786 for k in sf_reads:
1387 | {(k, "r") for k in sf_reads} 1787 cur_dirty |= _DIRTY_LDS_R if k == "lds" else _DIRTY_MEM_R
1388 | {(k, "w") for k in sf_writes}) 1788 for k in sf_writes:
1789 cur_dirty |= _DIRTY_LDS_W if k == "lds" else _DIRTY_MEM_W
1389 steps.append(("inline_sync_free", it, pre_bar)) 1790 steps.append(("inline_sync_free", it, pre_bar))
1390 else: 1791 else:
1391 pre_bar = bool(cur_dirty) 1792 pre_bar = bool(cur_dirty)
1392 cur_dirty = frozenset() # mini-scheduler ends with OpControlBarrier %c2 %c2 %c948 1793 cur_dirty = 0 # mini-scheduler ends with OpControlBarrier %c2 %c2 %c948
1393 mini_blocks[mini_idx] = it_blocks 1794 mini_blocks[mini_idx] = it_blocks
1394 for u in it_blocks: 1795 for u in it_blocks:
1395 mini_of_block[u] = mini_idx 1796 mini_of_block[u] = mini_idx