diff --git a/docs/design.md b/docs/design.md index ebee74ad03..2f244d2411 100644 --- a/docs/design.md +++ b/docs/design.md @@ -308,6 +308,7 @@ How the generated SPIR-V expects the runtime to work: | `s_*_saveexec_b32/b64`, `s_andn1/andn2_wrexec_b32/b64` | RDNA2 ISA SOP1. saveexec: `D = EXEC; EXEC = f(S0, EXEC); SCC = (EXEC != 0)`. wrexec: `EXEC = f(S0, EXEC); D = EXEC`. `f` is one of `and`, `or`, `xor`, `andn1` (`~S0 & EXEC`), `andn2` (`S0 & ~EXEC`), `orn1` (`~S0 \| EXEC`), `orn2` (`S0 \| ~EXEC`), `nand`, `nor`, `xnor`, the table in `Gen.EXEC_LOGIC`. The definitions match `tools/cf_ref.py` `_SAVEEXEC`, the FUZZ-8 model. Each invocation holds its own lane's bit (0 or ~0), so `f` is the bitwise op on that bit. A lane EXEC had off becomes active when `f` gives 1 for it (`nand`, `nor`, `orn1`, `orn2`, `xnor`, ...), as on hardware, and SCC is the wave vote. Until 2026-11-22 only `and`/`or`/`andn2_saveexec` and `andn2_wrexec` were translated. CPU-checked by `tests/semantic/test_saveexec_variants.py` (all ten saveexec kinds in wave32 and wave64, both wrexec kinds, partial EXEC and S0, an empty result, every lane against `cf_ref._SAVEEXEC`) and by `tools/cf_diff.py` (300 programs × wave32/64 still pass). Hardware-verified on native RDNA2 (`gfx1036`, Windows 11, driver `32.0.21045.29003`, wave32 & wave64, 0 mismatches): all 10 `saveexec` kinds and both `wrexec` kinds (`andn1`/`andn2`) match bit-for-bit on non-symmetric masks (`src0 = 0x0F0F0F0F`, `exec = 0x33333333` in wave32; `0x0F0F0F0F_00FF00FF` / `0x33333333_55555555` in wave64), zero-result `SCC = 0`, wave64 upper-32-bit-only `new_exec = 0x00000001_00000000` setting `SCC = 1`, and `sdst == src0` register aliasing (`s4, s4` and `s[4:5], s[4:5]`) reading original `src0` before writing old `EXEC` to `sdst`. **Not GPU-verified** for the seven new kinds. Measured on native gfx1100 (single 8-lane workgroup, 36 programs): all ten `saveexec` kinds and both `wrexec` forms follow `f` for three `S0`/`EXEC` pairs, including lanes `EXEC` had off being switched back on (`nand` with `S0=0x03`, `EXEC=0x0F` leaves `0xFFFFFFFC`, activating lanes 4-7), `D` holding the old `EXEC` for `saveexec` and the new one for `wrexec`, and `SCC` the `EXEC != 0` vote. | | Control flow | Reducible graphs use structured branches and natural loops. Irreducible graphs use the dispatch-loop form, which can also be forced with `--dispatch-loop` for comparisons. The control-flow unit test checks 18,228 generated graphs. Irreducible graphs use node splitting (`cfg_structure.split_irreducible`, up to `min(2*N, N+64)` blocks) and fall back to the dispatch-loop form when capped; it can also be forced with `--dispatch-loop` for comparisons. `cfg_structure.structure`, `cfg_structure.run`, and `rdna2spirv.assemble`'s structured emitter are iterative and hoist each guarded member's dominated tail continuation out of its enclosing guard (exact by strict dominance: no block outside the guard's subtree can target the continuation), keeping `OpSelectionMerge` nesting O(1) on sequential diamond/loop chains instead of nesting O(N) deep and hitting Python's recursion limit on multi-thousand-block shaders (e.g. 2,000 sequential diamonds nest to depth 2 instead of 2,000). The control-flow unit test (`tests/test_cfg_structure.py`) checks 20,000 generated graphs plus 2,000-diamond, 1,200-loop, and 1,500-early-exit chains. `capped_tree()` also runs `cfg_structure.unwrap_known_pc_guards` (shared with `wave64_emulate_opt`) to unwrap tautological `("guard", g, ...)` nodes whenever abstract interpretation proves `%pc == g` on all incoming paths (e.g. post-dominating merge blocks after diamonds and loops); this keeps `ms_wave_info_s3`'s `s_barrier` in uniform top-level control flow (fixing an AMD Windows LLPC `0xC0000005` pipeline-creation crash on AMD Ryzen 5 7600 RDNA2 iGPU driver `24.10.24`, `4096/4096` exact on AMD RDNA2 and RTX 4070 SUPER) and avoids false `needs_barrier_rounds` triggers (`SHADER-STRUCTURED-PC-UNWRAP`). AMD A/B checks compare the two forms for selected pixel shaders with defined test inputs. For shaders that never export colour, the comparison checks pixel coverage. **Nesting is bounded (SHADER-299):** a tree deeper than `MAX_STRUCTURED_DEPTH` (16) is emitted in the dispatch-loop form instead, since `spirv-val` time grows roughly with the cube of the measured nesting depth. **Nesting is bounded (SHADER-299, SHADER-427):** a tree deeper than `MAX_STRUCTURED_DEPTH` (64; `--max-structured-depth N`, 0 = no bound) is emitted in the dispatch-loop form instead, since `spirv-val` time grows roughly with the cube of the measured nesting depth. Before #1904, over the 1.0.2.1 corpus (26,503 modules, `spirv-val` 2026.4): the deepest block of a module is nested 118 constructs deep, 12,963 modules are structured (median 15) and 6,000 of those are deeper than 16; an estimated 85% of the corpus's `spirv-val` time is in modules nested 20 or deeper. Median `spirv-val` time for the same module in each form: depth 20 181 -> 129 ms (1.4x), 30 507 -> 371 (1.4x), 50 1,712 -> 738 (2.3x), 64 2,692 -> 1,163 (2.3x), 77 5,122 -> 1,130 (4.5x), and the deepest (118) 13,683 -> 1,352 ms (10.1x). Depth 5-12 shows no gain (at depth 6 the flat form is slightly slower), which is why the bound first sat at 16. Since #1904 (`cfg_structure` hoists tails) the deepest tree in the corpus is 29: of 12,944 structured modules, 1,031 are deeper than 16 (747 CS, 284 PS), 57 deeper than 20, 24 deeper than 24. For those 1,031 the flat form saves only 12% of `spirv-val` time (1,235 -> 1,091 s summed, slowest module 8.3 -> 5.9 s), while on an RTX 5070 Ti (NVIDIA 621.24) it compiles slower: the 284 pixel shaders 1.67x (827 -> 1,382 s summed, two rounds), four compute modules at depth 19-24 2.0x (297 -> 591 s, 1.6-2.7x each), so the bound now sits above the corpus (SHADER-427). Both forms pass `spirv-val` on a 200-shader slice (200/200 each), and `gen.nesting` records the tree depth. AMD's Windows driver adds a reason to keep the structured form (SHADER-995): on a Radeon gfx1036 iGPU (32.0.21042.62) the dispatch-loop module of `XboxBvhBuilder.dll`'s `LeafRehydration` (tree depth 18, a 581-case switch) takes 34 minutes to create (XXDESIGN), where its structured module is created in 2.9 s; ten other programs of that DLL compile in the dispatch-loop form there in 0.4-40 s, 2.5-5x their structured time ([embedded_shaders.md](embedded_shaders.md), section 7). | | Loop guard | Each loop counts header visits per invocation and exits through its structured merge at `--loop-limit N` (default 65536, zero disables). Counters reset on entry, including nested EXEC retries and atomic loops. A PC-dispatch visit counts a dispatch iteration. Natural exits within the budget preserve their outputs. Five-star-recomp (b12a952) reported a story-load timeout when the shader input made its exit condition unreachable. | +| Loop guard: a total an invocation | `--loop-total N` (default 1,048,576; 0 = none): on top of each loop's own count, one count of every guarded back edge of an invocation, in a `Private` variable, which no back edge passes once it reaches N. Each loop keeps its own limit and a loop that ends by itself is cut only once a whole invocation has made N visits, but nested loops can no longer multiply their limits (65,536 visits of an inner loop in each of 65,536 visits of the outer one). The case: a loop bound computed by a float divide whose divisor is 0 is +inf, converts to 0xFFFFFFFF, and an inclusive exit test against it never fails once the counter wraps; nested loops of that kind ran at the per-loop limit for seconds a dispatch and the device was lost with no bad address. It changes the translation of every program with a loop, so a shader library takes it when it is translated again. `tests/semantic/test_loop_iteration_guard.py` checks it: two loops that never end stop at the total in both wave sizes, loops that end are untouched, and without a total the per-loop counts multiply. | | User data | **Push constants, 144 bytes:** dwords 0–31 = initial s0–s31 (the user SGPRs the console driver loads from the root signature: descriptor-table pointers, constants and so on), dwords 32–33 = the 64-bit **heap base**, dwords 34–35 = the **code base**: the Xbox VA where the runtime uploaded this shader's whole FSSM blob. `--mesh-compute` modules add dwords 36–37, the output buffer address (152 bytes; see "Mesh shaders as compute"). `--pc-tail-ubo` keeps only dwords 0–31 here (128 bytes) and moves the rest to a uniform block (see "Push-constant tail as a uniform block"). The runtime has to reproduce the console driver's root-signature-to-user-SGPR mapping; that comes from the exe or driver behaviour. **Mesh shaders** read their root SGPRs through the graphics root window: s16..s31 come from dwords 8..23 (where a VS, PS or GS reads s8..s23), s8..s15 are 0, s0..s7 dwords 0..7; the index records `"root_window": {"sgpr": 16, "dword": 8}` (D3D-448-GRAPHICS, `docs/d3d12_vulkan.md` 3.5). Checked by `tests/semantic/test_ms_root_window.py` (MeshEXT and `--mesh-compute`, CPU interpreter) and `d3d12_mesh_test` (RX 9070 XT). | | Direct resource heap | In the matched Prop/Tree BatchCull compute signature the two explicit tables and scalar constant occupy s4–s6. Bind the resource heap's uint32 arena-relative byte address at s7 (push-constant byte 28). The program supplies a zero high word and scales the resource index by 32 bytes. Other stages and signatures consume different SGPRs. See [descriptor heaps and the bindless model](d3d12_vulkan.md#34-descriptor-heaps-and-the-bindless-model) for the evidence and graphics examples. | | Xbox GPU addresses | Shaders build Xbox GPU virtual addresses, and some force the high dword to 0 (descriptor tables in the low 4 GB). Every memory access goes to **heap base + Xbox VA**, so the runtime maps the console's GPU address window into one host buffer-device-address allocation. | diff --git a/make_game.py b/make_game.py index 03d93a2b8b..35ff7043ed 100644 --- a/make_game.py +++ b/make_game.py @@ -1857,7 +1857,10 @@ def fallback_flags(a) -> tuple[str, ...]: if descriptor_hash != "fnv1a": flags += (f"--descriptor-hash={descriptor_hash}",) limit = getattr(a, "loop_limit", None) - return flags if limit is None else (*flags, f"--loop-limit={limit}") + if limit is not None: + flags = (*flags, f"--loop-limit={limit}") + total = getattr(a, "loop_total", None) + return flags if total is None else (*flags, f"--loop-total={total}") def recorded_fallback_flags(work: str) -> tuple[str, ...]: @@ -3102,6 +3105,9 @@ def main() -> int: ap.add_argument("--descriptor-hash", choices=("fnv1a", "fnv1a_fmix32"), default="fnv1a", help="translate all stages for the selected runtime descriptor table hash") ap.add_argument("--loop-limit", type=int, help="translator loop visit limit (default 65536, 0 disables)") + ap.add_argument("--loop-total", type=int, + help="translator total of loop visits an invocation may make across all its loops, on top of each " + "loop's own limit (default 1048576, 0 = none)") ap.add_argument("--compact-spirv", action="store_true", help="run the translator's compact binary pass on all shader libraries (requires spirv-opt)") ap.add_argument("--no-float-controls", action="store_true", @@ -3135,6 +3141,8 @@ def main() -> int: a = ap.parse_args() if a.loop_limit is not None and not 0 <= a.loop_limit <= 0xffffffff: ap.error("--loop-limit must be in 0..4294967295") + if a.loop_total is not None and not 0 <= a.loop_total <= 0xffffffff: + ap.error("--loop-total must be in 0..4294967295") stages = STAGES if a.stages is not None: stages = [s.strip() for s in a.stages.split(",") if s.strip()] diff --git a/tests/semantic/test_control_flow_branches.py b/tests/semantic/test_control_flow_branches.py index 789da34de1..7952395cef 100644 --- a/tests/semantic/test_control_flow_branches.py +++ b/tests/semantic/test_control_flow_branches.py @@ -314,6 +314,7 @@ def __init__(self, spvasm: str): self.constants: dict[str, int | float | bool | tuple | list] = {} self.ptr_types: dict[str, tuple[str, str]] = {} self.var_class: dict[str, str] = {} + self.private_init: dict[str, tuple] = {} # Private globals: (initializer id or None, pointee type) self.var_box: dict[str, list] = {} self.pointers: dict[str, tuple] = {} self.outputs: list[str] = [] @@ -392,11 +393,16 @@ def _parse(self): elif cls == "PushConstant": self.var_box[res] = [None] self.pointers[res] = ("pc", None) + elif cls == "Private": # the loop guard's total: one per run, from its initializer + self.private_init[res] = (a[2] if len(a) > 2 else None, pointee) def run(self, max_steps: int = 20000) -> dict[str, tuple]: values = dict(self.constants) var_box = dict(self.var_box) pointers = dict(self.pointers) + for res, (init, pointee) in self.private_init.items(): + var_box[res] = [values[init] if init is not None else self.zero(pointee)] + pointers[res] = (var_box[res], 0) def val(x: str): if x in values: diff --git a/tests/semantic/test_loop_ballot_barrier.py b/tests/semantic/test_loop_ballot_barrier.py index 9f5c6ffb2e..53d320be71 100644 --- a/tests/semantic/test_loop_ballot_barrier.py +++ b/tests/semantic/test_loop_ballot_barrier.py @@ -136,7 +136,10 @@ def _parse_spv(asm): elif op == "OpVariable": sc = args[1] _, elem = ptr_elem[args[0]] - gvars[res] = (sc, elem) + if sc == "Private": # one per invocation, as a function variable (the loop guard's total) + fvars.append((res, elem, args[2] if len(args) > 2 else None)) + else: + gvars[res] = (sc, elem) continue if op == "OpLabel": diff --git a/tests/semantic/test_loop_iteration_guard.py b/tests/semantic/test_loop_iteration_guard.py index a990031dd8..dd5916aff3 100644 --- a/tests/semantic/test_loop_iteration_guard.py +++ b/tests/semantic/test_loop_iteration_guard.py @@ -73,3 +73,41 @@ def test_inner_budget_resets_on_each_entry(self): with patch.object(rdna2spirv, "LOOP_LIMIT", 3): text, _ = _translate_cs("cs_guard_nested", lines, threads=32) self.assertEqual(execute(text, 32, 0), [9] * 32) + + # Two nested loops that never end (as an inclusive exit against a bound of 0xFFFFFFFF makes them, once the counter + # wraps). With a count per loop the limits multiply: LIMIT visits of the inner loop in each of LIMIT outer visits. + # --loop-total bounds them all together. s9 counts the inner loop's visits. + NEVER = ["s_mov_b32 s8, 0", "s_mov_b32 s9, 0", "outer:", "s_mov_b32 s10, 0", + "inner:", "s_add_u32 s9, s9, 1", "s_add_u32 s10, s10, 1", "s_cmp_eq_u32 s10, 0", + "s_cbranch_scc0 inner", "s_add_u32 s8, s8, 1", "s_cmp_eq_u32 s8, 0", "s_cbranch_scc0 outer", + "v_mov_b32_e32 v1, s9", "v_lshlrev_b32_e32 v2, 2, v0", + "buffer_store_dword v1, v2, s[0:3], 0 offen", "s_endpgm"] + + def nested(self, lines, limit, total, lanes=32): + with patch.object(rdna2spirv, "LOOP_LIMIT", limit), patch.object(rdna2spirv, "LOOP_TOTAL", total): + text, _ = _translate_cs("cs_guard_total", lines, threads=lanes, emulate=lanes == 64) + return text, execute(text, lanes, 0) + + def test_total_bounds_nested_loops(self): + # Without a total: 50 visits of the inner loop in each of 50 outer visits. + text, words = self.nested(self.NEVER, 50, 0) + self.assertNotIn("%loop_guard_total", text) + self.assertEqual(words, [2500] * 32) + # A total of 40: the first inner run takes 41 visits (the 41st finds the total spent), and the outer loop + # leaves at once after it. + text, words = self.nested(self.NEVER, 50, 40) + self.assertIn("%loop_guard_total", text) + self.assertEqual(words, [41] * 32) + # Emulated wave64: the round scheduler's own loop is guarded too and spends from the same total, so fewer + # visits are left for the program's loops, never more. + text, words = self.nested(self.NEVER, 50, 40, lanes=64) + self.assertIn("%loop_guard_total", text) + self.assertEqual(len(set(words)), 1) + self.assertTrue(0 < words[0] <= 41, words[0]) + + def test_total_leaves_loops_that_end_alone(self): + # Loops that end by themselves within the total compute what they did: 3 x 3 visits. + lines = [s.replace("s10, 0", "s10, 3").replace("s8, 0", "s8, 3") if s.startswith("s_cmp") else s + for s in self.NEVER] + _, words = self.nested(lines, 50, 16) + self.assertEqual(words, [9] * 32) diff --git a/tests/semantic/test_wave64_emulate_opt.py b/tests/semantic/test_wave64_emulate_opt.py index 6593a668b7..e524711de9 100644 --- a/tests/semantic/test_wave64_emulate_opt.py +++ b/tests/semantic/test_wave64_emulate_opt.py @@ -311,6 +311,8 @@ def make_inv(idx, coord): else: box = [zero_of(pointee)] ptrs[res] = (box, 0) + elif cls == "Private": # one per invocation (the loop guard's total), from its initializer + ptrs[res] = ([consts[init_id] if init_id is not None else zero_of(pointee)], 0) else: raise NotImplementedError(f"global storage class {cls}") return { diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 13fbd034db..7f392c9914 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -53,6 +53,7 @@ # differs. docs/design.md "Control flow" has the numbers. MAX_STRUCTURED_DEPTH = 64 LOOP_LIMIT = spirv_loop_guard.DEFAULT_LIMIT +LOOP_TOTAL = spirv_loop_guard.DEFAULT_TOTAL # --loop-total: the visits of all the loops of an invocation (0: none) DESCRIPTOR_HASHES = ("fnv1a", "fnv1a_fmix32") DESCRIPTOR_HASH = "fnv1a" # --descriptor-table: how the table's entries are read. "plain" is what every module read until the T# dimension @@ -18893,7 +18894,7 @@ def finish_module(g): if OPT_SPIRV: import spirv_opt text = spirv_opt.optimize(text) - return spirv_loop_guard.add_guards(text, LOOP_LIMIT) + return spirv_loop_guard.add_guards(text, LOOP_LIMIT, total=LOOP_TOTAL) def _block_out_pcs(blocks, raw_edges, succ): @@ -19802,7 +19803,7 @@ def _out_inside_input(src, out): def main(): - global MAX_SHARED_BYTES, MAX_STRUCTURED_DEPTH, LOOP_LIMIT, DESCRIPTOR_HASH, DESCRIPTOR_TABLE + global MAX_SHARED_BYTES, MAX_STRUCTURED_DEPTH, LOOP_LIMIT, LOOP_TOTAL, DESCRIPTOR_HASH, DESCRIPTOR_TABLE ap = argparse.ArgumentParser() ap.add_argument("src") ap.add_argument("--out", required=True) @@ -19874,6 +19875,10 @@ def main(): help="descriptor table entry layout: 'tagged' also carries each image's array kind, recorded as " "descriptor_table in the module meta (default: tagged; 'plain' is the old layout, for a " "library that keeps the runtime's old behaviour)") + ap.add_argument("--loop-total", type=spirv_loop_guard.parse_limit, default=spirv_loop_guard.DEFAULT_TOTAL, + metavar="N", + help="the most visits all the loops of an invocation make together, on top of each loop's own " + "limit, so nested loops cannot multiply it (default %(default)s; 0 = none)") ap.add_argument("--loop-limit", type=spirv_loop_guard.parse_limit, default=spirv_loop_guard.DEFAULT_LIMIT, help="maximum visits to each loop header, including dispatch loops (default %(default)s, 0 disables)") ap.add_argument("--max-structured-depth", type=_depth_arg, default=MAX_STRUCTURED_DEPTH, metavar="N", @@ -19905,6 +19910,7 @@ def main(): DESCRIPTOR_HASH = a.descriptor_hash DESCRIPTOR_TABLE = a.descriptor_table LOOP_LIMIT = a.loop_limit + LOOP_TOTAL = a.loop_total MAX_STRUCTURED_DEPTH = a.max_structured_depth global STRUCTURED, WAVE64_EMULATE, WAVE64_GRAPHICS, BARY_FALLBACK, TEXEL_OFFSET_FALLBACK, MESH_COMPUTE, FMA_KHR, SHADER_CLOCK, F16_HALVES, OPT_SPIRV global PC_TAIL_UBO diff --git a/tools/spirv_loop_guard.py b/tools/spirv_loop_guard.py index 9036d78157..8f83d4d857 100644 --- a/tools/spirv_loop_guard.py +++ b/tools/spirv_loop_guard.py @@ -2,14 +2,24 @@ Five-star-recomp b12a952 identified nonterminating translated loops during story loading. Instrument the back edge so a normally terminating iteration takes its original exit. + +Each loop counts its own visits from every entry, so nested loops multiply their limits: an inner loop may make +65,536 visits in each of 65,536 visits of the outer one, which bounds nothing a GPU survives. `total` adds a second +count, of every guarded back edge of an invocation, in a Private variable, which no back edge passes once it reaches +the total. Each loop keeps its own limit; a loop that ends by itself is cut only after the whole invocation has made +`total` visits. The case it is for: a loop bound computed by a float divide whose divisor is 0 is +inf, converts to +0xFFFFFFFF, and an inclusive exit test against it never fails once the counter wraps; nested loops of that kind ran +for seconds a dispatch at the per-loop limit, and the device was lost. """ import argparse from collections import defaultdict import re DEFAULT_LIMIT = 65536 +DEFAULT_TOTAL = 1 << 20 # visits of all the guarded loops of an invocation together _LINE = re.compile(r"(?m)^[ \t]*(?:(%[\w.]+)\s*=\s*)?(Op(?:Label|BranchConditional|Branch|Switch|" - r"LoopMerge|SelectionMerge|Phi|Function|TypeInt|TypeBool|Constant))\b([^;\n]*)") + r"LoopMerge|SelectionMerge|Phi|Function|TypeInt|TypeBool|TypePointer|Constant|" + r"EntryPoint))\b([^;\n]*)") def parse_limit(text): @@ -19,9 +29,11 @@ def parse_limit(text): return value -def add_guards(text, limit=DEFAULT_LIMIT): +def add_guards(text, limit=DEFAULT_LIMIT, total=DEFAULT_TOTAL): if not 0 <= limit <= 0xffffffff: raise ValueError("loop limit must fit an unsigned 32-bit word") + if not 0 <= total <= 0xffffffff: + raise ValueError("loop total must fit an unsigned 32-bit word") if not limit or "OpLoopMerge" not in text: return text prefix = "%loop_guard_" @@ -29,14 +41,18 @@ def add_guards(text, limit=DEFAULT_LIMIT): prefix += "_" heads, labels, terminators, merges, phis = {}, {}, {}, {}, defaultdict(list) pred = defaultdict(list) - constants = {} - uint = boolean = first_function = block = None + constants, pointers = {}, {} + uint = boolean = first_function = block = entry_point = None for match in _LINE.finditer(text): result, op, operands = match.groups() args = operands.split() if op == "OpFunction": if first_function is None: first_function = match.start() + elif op == "OpEntryPoint": + entry_point = match.end() + elif op == "OpTypePointer": + pointers[tuple(args)] = result elif op == "OpTypeInt" and args == ["32", "0"]: uint = result elif op == "OpTypeBool": @@ -67,12 +83,22 @@ def add_guards(text, limit=DEFAULT_LIMIT): if boolean is None: boolean = prefix + "bool" decls.append(f"{boolean} = OpTypeBool") - for value in (1, limit): + # The invocation's total is a global, which the entry point lists (SPIR-V 1.4 lists every global it uses); a + # fragment without an entry point keeps the per-loop counts alone. + totalled = total > 0 and entry_point is not None + for value in (1, limit) + ((0, total) if totalled else ()): if value not in constants: constants[value] = prefix + f"c{value}" decls.append(f"{constants[value]} = OpConstant {uint} {value}") edits, undef = [], {} + if totalled: + private = pointers.get(("Private", uint)) + if private is None: + private = prefix + "private" + decls.append(f"{private} = OpTypePointer Private {uint}") + decls.append(f"{prefix}total = OpVariable {private} Private {constants[0]}") + edits.append((entry_point, entry_point, f" {prefix}total")) for i, (header, exit_label) in enumerate(heads.items()): # The translator emits dominators first. A structured loop has exactly one back edge. backward = [p for p in pred[header] if labels[p] >= labels[header]] @@ -89,8 +115,17 @@ def add_guards(text, limit=DEFAULT_LIMIT): latch = q + "latch" if split else back incoming = " ".join((q + "next " + latch) if p == back else (constants[1] + " " + p) for p in pred[header]) edits.append((labels[header], labels[header], f"\n{q}count = OpPhi {uint} {incoming}")) - operations = [f"{q}next = OpIAdd {uint} {q}count {constants[1]}", - f"{q}room = OpULessThan {boolean} {q}count {constants[limit]}"] + operations = [f"{q}next = OpIAdd {uint} {q}count {constants[1]}"] + if totalled: + # Room in this loop's own count and in the invocation's total: the back edge needs both. + operations += [f"{q}spent = OpLoad {uint} {prefix}total", + f"{q}spent_next = OpIAdd {uint} {q}spent {constants[1]}", + f"OpStore {prefix}total {q}spent_next", + f"{q}own = OpULessThan {boolean} {q}count {constants[limit]}", + f"{q}left = OpULessThan {boolean} {q}spent {constants[total]}", + f"{q}room = OpLogicalAnd {boolean} {q}own {q}left"] + else: + operations.append(f"{q}room = OpULessThan {boolean} {q}count {constants[limit]}") if op == "OpBranch" or split: branch = f"OpBranchConditional {q}room {header} {exit_label}" else: