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:
authoredwin042331-hue <edwin042331@gmail.com>2026-11-22 09:54:45 -0400
committeredwin042331-hue <edwin042331@gmail.com>2026-11-22 10:57:54 -0400
commit18abefa47b0b9ccfb1afdf38e8edbd7b60f98955 (patch)
tree154dc8dd0733f6055eb44f03482d6e3a9fcd1cca /tools/wave64_emulate_opt.py
parent6a6704df1592e1dc4a3215ddf1423a78adb52045 (diff)
wave64-emulate: elide dead SCC votes and fold safe lane-local execz regions
Reduces redundant round barriers and OpSwitch cases under --wave64-emulate (Issue #884) via two exact CFG/dataflow passes in tools/wave64_emulate_opt.py: (1) backward SCC liveness skips scc_from_mask/scc_any_half votes when SCC is dead-out; (2) safe lane-local s_cbranch_execz/execnz region folding inlines single-entry/single-exit read-only regions with no cross-lane ops, no barriers, no EXEC-widening, and no live-out scalars behind if (%active) and chains single-predecessor continuations.
Diffstat (limited to 'tools/wave64_emulate_opt.py')
-rw-r--r--tools/wave64_emulate_opt.py697
1 files changed, 697 insertions, 0 deletions
diff --git a/tools/wave64_emulate_opt.py b/tools/wave64_emulate_opt.py
new file mode 100644
index 000000000..a44a03f86
--- /dev/null
+++ b/tools/wave64_emulate_opt.py
@@ -0,0 +1,697 @@
1"""Exact CFG/dataflow optimizations for --wave64-emulate (Issue #884).
2
3Two conservative, bit-exact analyses over a compute/mesh shader's basic blocks:
4
51. `scc_live_outs(blocks, succ)` -> set of `id(ins)` whose SCC write can reach
6 any SCC read before being unconditionally overwritten. Under --wave64-emulate,
7 mask ops (`s_and_saveexec_b64`, `s_andn2_b64`, `s_or_b64`, `s_not_b64`,
8 `s_wqm_b64`, ...) otherwise pay a full cross-lane `x_round` + `x_split`
9 (workgroup barrier + OpSwitch case) to compute SCC even when SCC is dead.
10
112. `find_local_exec_folds(blocks, raw_edges, succ, lane_masks, scc_live)` ->
12 `(folds, fold_chain, absorbed)`: identifies single-entry, single-exit
13 regions guarded by `s_cbranch_execz` / `s_cbranch_execnz` whose body has:
14 - no cross-lane operations, no `s_barrier`, no live-SCC mask votes,
15 - no memory or LDS writes/atomics and no unmasked side effects,
16 - no EXEC-widening writes (an inactive lane stays inactive across the region),
17 - no scalar (`SGPR`, `VCC`, `SCC`, `M0`) written in the region that is live
18 at the join block (`skip`),
19 - reducible internal control flow (`cfg_structure.structure` succeeds).
20
21 Each such region can be emitted inline as a structured `if (%active) { R }`
22 inside its guarding block with zero `x_round` / `x_split` / `OpControlBarrier`,
23 keeping all 64 lanes of the wave in the exact same scheduler round on arrival
24 at `skip`. When `skip` has no predecessors outside `{B} | R`, `skip` is also
25 chained inline after the fold, collapsing chains of thousands of unrolled
26 `s_and_saveexec_b64; s_cbranch_execz` diamonds into a single scheduler block.
27
28Standard library only.
29"""
30import collections
31import os
32import sys
33
34sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)))
35import cfg_structure # noqa: E402
36import lane_masks as _lane_masks # noqa: E402
37
38BRANCHES = frozenset({
39 "s_branch", "s_cbranch_scc0", "s_cbranch_scc1",
40 "s_cbranch_vccz", "s_cbranch_vccnz",
41 "s_cbranch_execz", "s_cbranch_execnz",
42})
43
44# Instructions that implicitly read SCC (in addition to explicit `scc` operands).
45_SCC_IMPLICIT_READS = frozenset({
46 "s_cbranch_scc0", "s_cbranch_scc1",
47 "s_cselect_b32", "s_cselect_b64",
48 "s_cmov_b32", "s_cmov_b64",
49 "s_addc_u32", "s_subb_u32",
50})
51
52# Instructions verified in tools/rdna2spirv.py to unconditionally overwrite %scc.
53# Conservatively omitting an op only keeps SCC live across it (never unsafe).
54_SAVEEXEC_KINDS = ("and", "or", "xor", "andn1", "andn2", "orn1", "orn2", "nand", "nor", "xnor")
55_ALL_SAVEEXEC_WREXEC = frozenset(
56 [f"s_{k}_saveexec_b{w}" for k in _SAVEEXEC_KINDS for w in (32, 64)]
57 + [f"s_{k}_wrexec_b{w}" for k in ("andn1", "andn2") for w in (32, 64)]
58)
59
60_SCC_UNCONDITIONAL_WRITES = _ALL_SAVEEXEC_WREXEC | frozenset({
61 "s_and_b64", "s_or_b64", "s_xor_b64", "s_andn2_b64", "s_orn2_b64",
62 "s_nand_b64", "s_nor_b64", "s_xnor_b64", "s_not_b64",
63 "s_and_b32", "s_or_b32", "s_xor_b32", "s_andn2_b32", "s_orn2_b32",
64 "s_nand_b32", "s_nor_b32", "s_xnor_b32", "s_not_b32",
65 "s_add_u32", "s_addc_u32", "s_sub_u32", "s_subb_u32",
66 "s_add_i32", "s_sub_i32", "s_addk_i32",
67 "s_lshl1_add_u32", "s_lshl2_add_u32", "s_lshl3_add_u32", "s_lshl4_add_u32",
68 "s_min_u32", "s_max_u32", "s_min_i32", "s_max_i32",
69 "s_abs_i32", "s_absdiff_i32",
70 "s_lshl_b32", "s_lshr_b32", "s_ashr_i32", "s_lshl_b64",
71 "s_bfe_u32", "s_bfe_i32", "s_bfe_u64", "s_bfe_i64",
72 "s_bcnt0_i32_b32", "s_bcnt1_i32_b32", "s_bcnt0_i32_b64", "s_bcnt1_i32_b64",
73 "s_wqm_b32", "s_wqm_b64", "s_quadmask_b32", "s_quadmask_b64",
74 "s_cmp_eq_u32", "s_cmp_lg_u32", "s_cmp_gt_u32", "s_cmp_ge_u32", "s_cmp_lt_u32", "s_cmp_le_u32",
75 "s_cmp_eq_i32", "s_cmp_lg_i32", "s_cmp_gt_i32", "s_cmp_ge_i32", "s_cmp_lt_i32", "s_cmp_le_i32",
76 "s_cmp_eq_u64", "s_cmp_lg_u64",
77 "s_bitcmp0_b32", "s_bitcmp1_b32", "s_bitcmp0_b64", "s_bitcmp1_b64",
78})
79
80# Mask ops that emit a cross-lane vote in --wave64-emulate when SCC is live.
81_MASK_SCC_VOTE_OPS = _ALL_SAVEEXEC_WREXEC | frozenset({
82 "s_and_b64", "s_or_b64", "s_xor_b64", "s_andn2_b64", "s_orn2_b64",
83 "s_nand_b64", "s_nor_b64", "s_xnor_b64", "s_not_b64",
84 "s_wqm_b32", "s_wqm_b64",
85})
86
87# Scalar register bit positions for fast integer-bitmask backward liveness.
88_BIT_VCC = 128
89_BIT_SCC = 129
90_BIT_M0 = 130
91_ALL_SGPRS = (1 << 128) - 1
92
93_IMPLICIT_VCC_READS = frozenset({
94 "v_cndmask_b32", "v_addc_co_u32", "v_subb_co_u32", "v_subbrev_co_u32",
95 "v_add_co_ci_u32", "v_sub_co_ci_u32", "v_subrev_co_ci_u32",
96 "v_addc_u32", "v_subb_u32", "v_div_fmas_f32", "v_div_fmas_f64",
97 "s_cbranch_vccz", "s_cbranch_vccnz",
98})
99
100_NO_DEST_PREFIXES = (
101 "s_cmp", "s_bitcmp", "v_cmpx", "exp",
102 "buffer_store", "global_store", "flat_store", "scratch_store", "tbuffer_store", "image_store",
103 "ds_write", "ds_store", "s_store", "s_buffer_store",
104 "s_cbranch", "s_branch", "s_waitcnt", "s_nop", "s_endpgm", "s_barrier", "s_sendmsg",
105 "s_setprio", "s_inst_prefetch", "s_clause", "s_trap", "s_icache", "s_dcache", "s_sleep",
106 "s_code_end", "s_denorm_mode", "s_round_mode", "s_ttracedata", "v_nop", "v_clrexcp",
107 "v_pipeflush", "s_set", "s_sethalt", "s_setkill", "s_wakeup", "s_version",
108 "buffer_gl", "buffer_wbinvl", "ds_gws", "ds_nop",
109)
110
111
112def base_op(op):
113 for suffix in ("_e32", "_e64", "_sdwa", "_dpp"):
114 if op.endswith(suffix):
115 return op[:-len(suffix)]
116 return op
117
118
119def _active_insns(blk):
120 """Instructions of a basic block up to and including its terminator (branch or s_endpgm)."""
121 out = []
122 for ins in blk:
123 out.append(ins)
124 op = base_op(ins["op"])
125 if op == "s_endpgm" or op in BRANCHES:
126 break
127 return out
128
129
130def reads_scc(ins):
131 op = base_op(ins["op"])
132 if op in _SCC_IMPLICIT_READS or op.startswith(("s_getreg", "s_setreg", "s_save_status")):
133 return True
134 for x in ins["args"]:
135 if x.get("k") == "special" and x.get("t") == "scc":
136 return True
137 return False
138
139
140def writes_scc(ins):
141 return base_op(ins["op"]) in _SCC_UNCONDITIONAL_WRITES
142
143
144def scc_live_outs(blocks, succ):
145 """Return the set of `id(ins)` whose SCC result may be read before being unconditionally overwritten."""
146 n = len(blocks)
147 if not n:
148 return set()
149 preds = [[] for _ in range(n)]
150 for b in range(n):
151 for s in succ[b]:
152 preds[s].append(b)
153 use = [False] * n
154 kill = [False] * n
155 active = [_active_insns(blk) for blk in blocks]
156 for b, insns in enumerate(active):
157 k = False
158 u = False
159 for ins in insns:
160 if not k and reads_scc(ins):
161 u = True
162 break
163 if writes_scc(ins):
164 k = True
165 use[b] = u
166 kill[b] = k
167 live_in = list(use)
168 live_out = [False] * n
169 work = [b for b in range(n) if live_in[b]]
170 while work:
171 b = work.pop()
172 for p in preds[b]:
173 if not live_out[p]:
174 live_out[p] = True
175 if not kill[p] and not live_in[p]:
176 live_in[p] = True
177 work.append(p)
178 out = set()
179 for b, insns in enumerate(active):
180 live = live_out[b]
181 for ins in reversed(insns):
182 if live:
183 out.add(id(ins))
184 live = (live and not writes_scc(ins)) or reads_scc(ins)
185 return out
186
187
188def _operand_scalar_mask(x):
189 """Bitmask of scalar registers (s0..s127, vcc, scc, m0) named by operand `x`."""
190 k = x.get("k")
191 if k == "sgpr":
192 r = x["r"]
193 cnt = x.get("n", 1)
194 m = 0
195 for i in range(cnt):
196 if 0 <= r + i < 128:
197 m |= 1 << (r + i)
198 return m
199 if k == "special":
200 t = x.get("t", "")
201 if t.startswith("vcc"):
202 return 1 << _BIT_VCC
203 if t == "scc":
204 return 1 << _BIT_SCC
205 if t == "m0":
206 return 1 << _BIT_M0
207 return 0
208
209
210def _scalar_rw(ins):
211 """Return `(read_mask, may_write_mask, must_kill_mask)` over scalar bits 0..130 for `ins`."""
212 op = base_op(ins["op"])
213 a = ins["args"]
214 mods = ins.get("mods") or ()
215 # Dynamic SGPR indexing reads/writes arbitrary SGPRs + m0: never kill, conservatively read/write all SGPRs.
216 if op.startswith("s_movrel"):
217 return _ALL_SGPRS | (1 << _BIT_M0), _ALL_SGPRS, 0
218 if op == "s_endpgm" or op in BRANCHES:
219 rd = 0
220 if op in ("s_cbranch_scc0", "s_cbranch_scc1"):
221 rd |= 1 << _BIT_SCC
222 elif op in ("s_cbranch_vccz", "s_cbranch_vccnz"):
223 rd |= 1 << _BIT_VCC
224 return rd, 0, 0
225 # Split destination vs source operands conservatively.
226 dests, srcs = [], list(a)
227 if op.startswith(("s_cmp", "s_bitcmp")) or op.startswith("v_cmpx") or op.startswith(_NO_DEST_PREFIXES):
228 dests, srcs = [], list(a)
229 elif op.startswith("v_cmp"):
230 if len(a) == 2:
231 dests, srcs = [], list(a)
232 elif a:
233 dests, srcs = [a[0]], list(a[1:])
234 elif op.startswith(("buffer_atomic", "global_atomic", "flat_atomic", "image_atomic")):
235 dests = [a[0]] if ("glc" in mods and a) else []
236 srcs = list(a)
237 elif op.startswith("ds_"):
238 returns = (op.startswith(("ds_read", "ds_bpermute", "ds_permute", "ds_swizzle", "ds_consume", "ds_append"))
239 or "_rtn" in op)
240 dests, srcs = ([a[0]], list(a[1:])) if (returns and a) else ([], list(a))
241 elif op in ("s_addk_i32", "s_mulk_i32", "s_cmovk_i32", "s_movk_i32") and a:
242 # SOPK reads and writes a[0] (except s_movk_i32 which only writes a[0]).
243 dests = [a[0]]
244 srcs = list(a[1:]) if op == "s_movk_i32" else list(a)
245 elif a:
246 dests, srcs = [a[0]], list(a[1:])
247 if op.startswith("v_") and len(a) > 2 and (
248 "_co_" in op or op in ("v_mad_u64_u32", "v_mad_i64_i32", "v_div_scale_f32", "v_div_scale_f64")) \
249 and a[1].get("k") in ("sgpr", "special"):
250 dests, srcs = [a[0], a[1]], list(a[2:])
251
252 rd = 0
253 for x in srcs:
254 rd |= _operand_scalar_mask(x)
255 if op in _IMPLICIT_VCC_READS:
256 rd |= 1 << _BIT_VCC
257 if reads_scc(ins):
258 rd |= 1 << _BIT_SCC
259 if op.startswith(("ds_", "s_sendmsg", "v_interp")):
260 rd |= 1 << _BIT_M0
261 if op == "s_cmov_b32" or op == "s_cmov_b64":
262 # Conditional move preserves destination when SCC == 0, so it also reads destination.
263 for d in dests:
264 rd |= _operand_scalar_mask(d)
265
266 may_w = 0
267 for d in dests:
268 may_w |= _operand_scalar_mask(d)
269 if op.startswith("v_cmp") and not op.startswith("v_cmpx") and len(a) == 2:
270 may_w |= 1 << _BIT_VCC
271 if writes_scc(ins):
272 may_w |= 1 << _BIT_SCC
273 elif op.startswith("s_") and not op.startswith(("s_mov", "s_cselect", "s_load", "s_buffer_load", "s_getpc",
274 "s_nop", "s_waitcnt", "s_clause", "s_inst_prefetch", "s_pack",
275 "s_mul_i32", "s_mul_hi", "s_mulk", "s_ff", "s_flbit", "s_bfm",
276 "s_get_waveid")):
277 # Any uncategorized scalar op could touch SCC: include in may_w (never in must_kill).
278 may_w |= 1 << _BIT_SCC
279
280 # Only kill registers unconditionally overwritten (never conditional moves or half-VCC writes).
281 must_kill = 0
282 if op not in ("s_cmov_b32", "s_cmov_b64", "s_cmovk_i32"):
283 for d in dests:
284 if d.get("k") == "special" and d.get("t") in ("vcc_lo", "vcc_hi"):
285 continue # half-write preserves the other half in wave64
286 must_kill |= _operand_scalar_mask(d)
287 if op.startswith("v_cmp") and not op.startswith("v_cmpx") and len(a) == 2:
288 must_kill |= 1 << _BIT_VCC
289 if writes_scc(ins):
290 must_kill |= 1 << _BIT_SCC
291 return rd, may_w, must_kill
292
293
294def _scalar_liveness(active_blocks, succ):
295 """Exact conservative backward scalar liveness `live_in[b]` (int bitmask) for each block."""
296 n = len(active_blocks)
297 preds = [[] for _ in range(n)]
298 for b in range(n):
299 for s in succ[b]:
300 preds[s].append(b)
301 use = [0] * n
302 kill = [0] * n
303 for b, insns in enumerate(active_blocks):
304 u = 0
305 k = 0
306 for ins in insns:
307 rd, _, mk = _scalar_rw(ins)
308 u |= rd & ~k
309 k |= mk
310 use[b] = u
311 kill[b] = k
312 live_in = list(use)
313 live_out = [0] * n
314 in_work = [bool(u) for u in live_in]
315 work = collections.deque(b for b in range(n) if in_work[b])
316 while work:
317 b = work.popleft()
318 in_work[b] = False
319 bi = live_in[b]
320 for p in preds[b]:
321 new_out = live_out[p] | bi
322 if new_out != live_out[p]:
323 live_out[p] = new_out
324 new_in = use[p] | (new_out & ~kill[p])
325 if new_in != live_in[p]:
326 live_in[p] = new_in
327 if not in_work[p]:
328 in_work[p] = True
329 work.append(p)
330 return live_in
331
332
333def _postdominators(succ):
334 """Immediate post-dominator `ipdom[b]` (Cooper-Harvey-Kennedy on reversed CFG with virtual exit `n`)."""
335 n = len(succ)
336 exit_ = n
337 rev = [[] for _ in range(n + 1)]
338 for b in range(n):
339 if succ[b]:
340 for s in succ[b]:
341 rev[s].append(b)
342 else:
343 rev[exit_].append(b)
344 # Iterative RPO from exit_ on reversed CFG.
345 state = {exit_: 1}
346 order = []
347 stack = [(exit_, iter(rev[exit_]))]
348 while stack:
349 v, it = stack[-1]
350 for w in it:
351 if w not in state:
352 state[w] = 1
353 stack.append((w, iter(rev[w])))
354 break
355 else:
356 state[v] = 2
357 order.append(v)
358 stack.pop()
359 rpo = order[::-1]
360 pos = {v: i for i, v in enumerate(rpo)}
361 ipdom = {exit_: exit_}
362 # Original successors (with [] -> [exit_]) are the predecessors in the reversed CFG.
363 orig_succ = [list(s) if s else [exit_] for s in succ] + [[]]
364 changed = True
365 while changed:
366 changed = False
367 for v in rpo[1:]:
368 new = None
369 for p in orig_succ[v]:
370 if p not in ipdom:
371 continue
372 if new is None:
373 new = p
374 continue
375 a, b = p, new
376 while a != b:
377 while pos[a] > pos[b]:
378 a = ipdom[a]
379 while pos[b] > pos[a]:
380 b = ipdom[b]
381 new = a
382 if ipdom.get(v) != new:
383 ipdom[v] = new
384 changed = True
385 return ipdom
386
387
388def _holds_lane_mask(ins, x, lm_map):
389 k = x.get("k")
390 if k == "special":
391 t = x.get("t", "")
392 return t.startswith("exec") or (t.startswith("vcc") and "vcc" in lm_map)
393 if k == "sgpr":
394 return all(x["r"] + i in lm_map for i in range(x.get("n", 1)))
395 return False
396
397
398def _is_exec_op_arg(x):
399 return x.get("k") == "special" and x.get("t", "") == "exec"
400
401
402def _sgpr_pair(x):
403 if x.get("k") == "sgpr" and x.get("n", 1) == 2:
404 return x["r"]
405 return None
406
407
408def _classify_block_body(insns, lane_masks, scc_live, mask_writes):
409 """Inspect non-terminator instructions of a block for lane-local region safety.
410
411 Returns `(clean, mem_reads, may_write_scalars, exec_writes, sgpr_writes_all, saveexec_pairs)` where:
412 - `clean`: True if no instruction does a cross-lane op, barrier, memory write, or unmasked side effect.
413 - `mem_reads`: subset of {"lds", "mem"}.
414 - `may_write_scalars`: int bitmask of scalar regs possibly written.
415 - `exec_writes`: list of `(op, args)` that write EXEC.
416 - `sgpr_writes_all`: dict mapping sgpr index -> count of writes inside this block.
417 - `saveexec_pairs`: set of base SGPR indices `r` written by `s_and_saveexec_b64 s[r:r+1], ...`.
418 """
419 mem_reads = set()
420 may_w = 0
421 exec_writes = []
422 sgpr_writes = collections.Counter()
423 saveexec_pairs = set()
424
425 for ins in insns:
426 raw_op = ins["op"]
427 op = base_op(raw_op)
428 if op == "s_endpgm" or op in BRANCHES:
429 break
430 if id(ins) in mask_writes:
431 # write_all_lanes VGPR store (parked lane mask): runs even when EXEC == 0, so must not be skipped.
432 return False, frozenset(), 0, (), sgpr_writes, saveexec_pairs
433 a = ins["args"]
434 lm = lane_masks.get(id(ins), {})
435
436 # 1. Strictly forbidden opcodes inside a lane-local folded region.
437 if raw_op.endswith(("_dpp", "_dpp8")):
438 return False, frozenset(), 0, (), sgpr_writes, saveexec_pairs
439 if op in ("s_barrier", "s_sendmsg", "s_setpc_b64", "s_swappc_b64", "s_trap",
440 "s_sethalt", "s_setkill", "s_sleep", "s_setprio",
441 "s_round_mode", "s_denorm_mode",
442 "v_readlane_b32", "v_readfirstlane_b32", "v_writelane_b32",
443 "v_permlane16_b32", "v_permlanex16_b32",
444 "ds_bpermute_b32", "ds_permute_b32", "ds_swizzle_b32",
445 "s_wqm_b32", "s_wqm_b64", "s_quadmask_b32", "s_quadmask_b64"):
446 return False, frozenset(), 0, (), sgpr_writes, saveexec_pairs
447 if op.startswith(("s_movrel", "s_setreg", "s_getreg", "s_store", "s_buffer_store", "s_atomic", "exp")):
448 return False, frozenset(), 0, (), sgpr_writes, saveexec_pairs
449 if "store" in op or "atomic" in op:
450 return False, frozenset(), 0, (), sgpr_writes, saveexec_pairs
451 if op.startswith("ds_"):
452 if not op.startswith("ds_read"):
453 return False, frozenset(), 0, (), sgpr_writes, saveexec_pairs
454 mem_reads.add("lds")
455 elif op.startswith(("buffer_load", "tbuffer_load", "global_load", "flat_load", "scratch_load",
456 "s_load_", "s_buffer_load_",
457 "image_load", "image_sample", "image_gather", "image_bvh")):
458 mem_reads.add("mem")
459
460 # 2. Cross-lane mask readers (`wave_mask`, `wave_equal`, live-SCC `scc_from_mask`).
461 if op in ("s_bcnt0_i32_b32", "s_bcnt1_i32_b32", "s_bcnt0_i32_b64", "s_bcnt1_i32_b64",
462 "s_ff0_i32_b32", "s_ff1_i32_b32", "s_ff0_i32_b64", "s_ff1_i32_b64"):
463 if len(a) > 1 and _holds_lane_mask(ins, a[1], lm):
464 return False, frozenset(), 0, (), sgpr_writes, saveexec_pairs
465 elif op in ("v_mbcnt_lo_u32_b32", "v_mbcnt_hi_u32_b32"):
466 if len(a) > 1 and a[1].get("k") != "imm" and _holds_lane_mask(ins, a[1], lm):
467 return False, frozenset(), 0, (), sgpr_writes, saveexec_pairs
468 elif op.startswith(("s_cmp", "s_bitcmp")):
469 if any(_holds_lane_mask(ins, x, lm) for x in a):
470 return False, frozenset(), 0, (), sgpr_writes, saveexec_pairs
471 elif op in _MASK_SCC_VOTE_OPS and id(ins) in scc_live:
472 # Would emit scc_from_mask -> x_round if operating on a lane mask.
473 is_mask_dst = bool(a) and a[0].get("k") == "special" and a[0].get("t", "").startswith(("exec", "vcc"))
474 if "saveexec" in op or "wrexec" in op or is_mask_dst or any(_holds_lane_mask(ins, x, lm) for x in a[1:]):
475 return False, frozenset(), 0, (), sgpr_writes, saveexec_pairs
476
477 # 3. Track scalar writes and EXEC writes.
478 _, ins_mw, _ = _scalar_rw(ins)
479 may_w |= ins_mw
480 # Track individual SGPR writes for exact saved-EXEC-mask checking.
481 s_bits = ins_mw & _ALL_SGPRS
482 while s_bits:
483 lsb = s_bits & -s_bits
484 sgpr_writes[lsb.bit_length() - 1] += 1
485 s_bits ^= lsb
486 if op == "s_and_saveexec_b64" and a:
487 pair = _sgpr_pair(a[0])
488 if pair is not None:
489 saveexec_pairs.add(pair)
490 writes_exec = (op.startswith("v_cmpx") or "saveexec" in op or "wrexec" in op
491 or (bool(a) and a[0].get("k") == "special" and a[0].get("t", "").startswith("exec")))
492 if writes_exec:
493 exec_writes.append((op, a))
494
495 return True, frozenset(mem_reads), may_w, exec_writes, sgpr_writes, saveexec_pairs
496
497
498def _exec_writes_stay_inactive(region_blocks, blk_info):
499 """Return True iff every EXEC write in `region_blocks` preserves `active == False` for inactive lanes."""
500 total_sgpr_writes = collections.Counter()
501 cand_saved = set()
502 for u in region_blocks:
503 total_sgpr_writes.update(blk_info[u][4])
504 cand_saved.update(blk_info[u][5])
505 # A pair s[r:r+1] is guaranteed to hold 0 for every lane entering R inactive if its ONLY write in R
506 # is `s_and_saveexec_b64 s[r:r+1], ...` (and neither half is written anywhere else in R).
507 zero_pairs = {r for r in cand_saved if total_sgpr_writes[r] == 1 and total_sgpr_writes[r + 1] == 1}
508 for u in region_blocks:
509 for op, a in blk_info[u][3]:
510 if op.startswith("v_cmpx") or op in ("s_and_saveexec_b64", "s_and_saveexec_b32"):
511 continue
512 if not a or not _is_exec_op_arg(a[0]):
513 return False # partial exec_lo/exec_hi or unknown EXEC write
514 if op == "s_and_b64" and len(a) == 3 and (_is_exec_op_arg(a[1]) or _is_exec_op_arg(a[2])):
515 continue
516 if op == "s_andn2_b64" and len(a) == 3:
517 if _is_exec_op_arg(a[1]):
518 continue
519 if _sgpr_pair(a[1]) in zero_pairs:
520 continue
521 return False
522 if op == "s_or_b64" and len(a) == 3:
523 if _is_exec_op_arg(a[1]) and _sgpr_pair(a[2]) in zero_pairs:
524 continue
525 if _is_exec_op_arg(a[2]) and _sgpr_pair(a[1]) in zero_pairs:
526 continue
527 return False
528 if op == "s_mov_b64" and len(a) == 2 and _sgpr_pair(a[1]) in zero_pairs:
529 continue
530 return False
531 return True
532
533
534def find_local_exec_folds(blocks, raw_edges, succ, lane_masks, scc_live, mask_writes=frozenset()):
535 """Find safe lane-local `s_cbranch_execz`/`nz` regions to fold inline under --wave64-emulate.
536
537 Returns `(folds, fold_chain, absorbed)`:
538 - `folds`: dict `head_block -> {"run": int, "skip": int, "region": frozenset[int],
539 "order": list[int], "sub_tree": list | None, "mem_reads": frozenset[str]}`
540 containing only the maximal (outermost) folded regions.
541 - `fold_chain`: dict `head_block -> skip_block` when `skip_block` has no predecessors outside
542 `{head_block} | region` and can be emitted directly after the fold in the same block.
543 - `absorbed`: set of all block indices emitted inline (inside a folded region or chained as `skip`).
544 """
545 n = len(blocks)
546 if n < 2:
547 return {}, {}, set()
548
549 active_blocks = [_active_insns(blk) for blk in blocks]
550 preds = [set() for _ in range(n)]
551 for b in range(n):
552 for s in succ[b]:
553 preds[s].add(b)
554
555 ipdom = _postdominators(succ)
556 scalar_live_in = _scalar_liveness(active_blocks, succ)
557
558 blk_info = []
559 terms = []
560 for b, insns in enumerate(active_blocks):
561 blk_info.append(_classify_block_body(insns, lane_masks, scc_live, mask_writes))
562 last = insns[-1] if insns else None
563 op = base_op(last["op"]) if last is not None else None
564 if op == "s_endpgm":
565 terms.append(("end", None))
566 elif op in BRANCHES:
567 terms.append(("br", op))
568 else:
569 terms.append(("fall", None))
570
571 # Gather candidate s_cbranch_execz / s_cbranch_execnz blocks with single-entry/single-exit post-dominated regions.
572 candidates = []
573 for b in range(n):
574 kind, op = terms[b]
575 if kind != "br" or op not in ("s_cbranch_execz", "s_cbranch_execnz"):
576 continue
577 edges = raw_edges[b]
578 if len(edges) < 2:
579 continue
580 tgt, fall = edges[0], edges[1]
581 run, skip = (fall, tgt) if op == "s_cbranch_execz" else (tgt, fall)
582 if run == skip or skip >= n or ipdom.get(b) != skip:
583 continue
584 # Collect region R reachable from `run` stopping at `skip`.
585 region = set()
586 work = [run]
587 ok = True
588 while work:
589 u = work.pop()
590 if u == skip or u in region:
591 continue
592 if u == b or u == 0 or not succ[u] or not blk_info[u][0]:
593 ok = False
594 break
595 region.add(u)
596 for s in succ[u]:
597 if s != skip and s not in region:
598 work.append(s)
599 if not ok or not region:
600 continue
601 # Single-entry check: no external edge into any block of R except B -> run.
602 for u in region:
603 allowed_ext = {b} if u == run else set()
604 if not preds[u] <= (region | allowed_ext):
605 ok = False
606 break
607 if not ok:
608 continue
609 # No scalar written in R may be live-in at `skip`.
610 region_may_w = 0
611 for u in region:
612 region_may_w |= blk_info[u][2]
613 if region_may_w & scalar_live_in[skip]:
614 continue
615 # EXEC must stay inactive for any lane that skipped R.
616 if not _exec_writes_stay_inactive(region, blk_info):
617 continue
618 candidates.append((len(region), b, run, skip, frozenset(region)))
619
620 # Validate innermost regions first so nested s_cbranch_execz/nz inside an outer region are already verified.
621 candidates.sort(key=lambda item: (item[0], item[1]))
622 valid = {}
623 for _, b, run, skip, region in candidates:
624 ok = True
625 for u in region:
626 tkind, top = terms[u]
627 if tkind == "end":
628 ok = False
629 break
630 if tkind == "br":
631 if top in ("s_cbranch_vccz", "s_cbranch_vccnz"):
632 ok = False
633 break
634 if top in ("s_cbranch_execz", "s_cbranch_execnz"):
635 if u not in valid or valid[u]["skip"] not in (region | {skip}):
636 ok = False
637 break
638 if not ok:
639 continue
640 # Build local sub-CFG and verify reducibility (multi-block regions use cfg_structure.structure).
641 if len(region) == 1:
642 order = [run]
643 sub_tree = None
644 else:
645 order = [run] + sorted(region - {run})
646 idx_of = {u: i for i, u in enumerate(order)}
647 sub_succ = [[idx_of[s] for s in succ[u] if s in idx_of] for u in order]
648 sub_tree = cfg_structure.structure(sub_succ)
649 if sub_tree is None:
650 continue
651 mem_reads = frozenset().union(*(blk_info[u][1] for u in region))
652 valid[b] = {
653 "run": run,
654 "skip": skip,
655 "region": region,
656 "order": order,
657 "sub_tree": sub_tree,
658 "mem_reads": mem_reads,
659 }
660
661 # Select maximal (non-overlapping outermost) folded regions.
662 selected = {}
663 in_region = set()
664 for _, b, _, _, _ in sorted(
665 ((len(v["region"]), k, v["run"], v["skip"], v["region"]) for k, v in valid.items()),
666 key=lambda x: (-x[0], x[1])):
667 fd = valid[b]
668 if b in in_region or (fd["region"] & in_region):
669 continue
670 selected[b] = fd
671 in_region.update(fd["region"])
672
673 # Chain single-predecessor `skip` continuations directly after their fold (cycle-free by construction).
674 fold_chain = {}
675 chained = set()
676 parent_chain = {}
677
678 def chain_root(x):
679 while x in parent_chain:
680 x = parent_chain[x]
681 return x
682
683 for b in sorted(selected):
684 fd = selected[b]
685 skip = fd["skip"]
686 if skip == 0 or skip in in_region or skip in chained:
687 continue
688 if not preds[skip] <= ({b} | fd["region"]):
689 continue
690 if chain_root(skip) == chain_root(b):
691 continue
692 fold_chain[b] = skip
693 parent_chain[skip] = b
694 chained.add(skip)
695
696 absorbed = in_region | chained
697 return selected, fold_chain, absorbed