mirror of
https://github.com/ProjectLeonida/mandy.git
synced 2026-12-06 21:48:37 +00:00
A loop over data the host has not mirrored yet reads zeros and can run
billions of times; VIctory lost the GPU that way and caps every loop at
128 passes in a pixel shader, 256 in a vertex, geometry or mesh shader and
4096 in a compute shader (victory lower.rs LOOP_LIMIT and count_iteration,
commit 15b0091e8; the per-stage values from 570a941e9). Leonida had no cap.
cfg_structure.loop_counters finds the loops of any graph: each strongly
connected region left after the counted edges of the loops around it are
removed, its counted edges the ones into its entries (the back edges of a
natural loop), its resets the blocks outside with an edge in. Every cycle
has a counted edge, so every loop ends. rdna2spirv keeps one Function
variable per loop; every lane of a wave runs the same blocks, so the lanes'
counters agree (one counter per wave). At the cap a branch back takes its
other way out, and a block with no other way leaves the program: %pc = the
end and %done, and a pixel is discarded at the end (%lc_kill, after the
POPS interlock like every exit). A wave that leaves early is counted done
by the barrier rounds and the wave64 emulation rounds, so it holds no
barrier; under --wave64-emulate such blocks count as an early s_endpgm for
plan_structured_emulation and stay out of lane-local folds.
--loop-limit PS,VS,CS sets the limits (or one N; 0 = no cap, and the output
is byte-identical to before: all 102 fixtures, with and without
--wave64-emulate). index.json records loop_limit and capped_loops for every
module with a loop. Contract row "Loop iteration cap" in docs/design.md.
Tests: tests/semantic/test_loop_limit.py with the hand-written fixtures
loop_limit_back.asm, loop_limit_jump.asm and loop_limit_barrier.asm (the
exported count, the discard at the cap, the dispatch-loop form, the vertex
cap, and a two-wave compute shader whose second wave never leaves its loop
while the first passes s_barrier, in native wave32 barrier rounds and under
--wave64-emulate with one and two waves); tests/test_cfg_structure.py
checks loop_counters on 6,000 random graphs. Not GPU-verified.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
113 lines
5.4 KiB
Python
113 lines
5.4 KiB
Python
"""Shared helpers for the translator tests (standard library only)."""
|
|
import gc
|
|
import os
|
|
import struct
|
|
import sys
|
|
import tempfile
|
|
import warnings
|
|
|
|
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
ROOT = os.path.dirname(os.path.dirname(HERE))
|
|
# The mutation tests point this at a sabotaged copy of tools/; normally it is the repository's own.
|
|
TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")
|
|
FIXTURE_DIR = os.path.join(HERE, "fixtures", "disasm")
|
|
|
|
sys.dont_write_bytecode = True # never drop __pycache__ into the tree under test
|
|
sys.path.insert(0, TOOLS_DIR)
|
|
import rdna2spirv # noqa: E402 (path set above)
|
|
from spirv_mini_interp import run_fragment # noqa: E402
|
|
|
|
# translate() reads <dir>/<name>.s and, for pixel shaders, an input signature from <dir>/../<name>.dxbc.
|
|
# A DXBC container with zero parts (magic, 24 zero bytes, part count 0, 4 more bytes) declares no inputs.
|
|
STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4)
|
|
|
|
|
|
def translate_fixture(name, dxbc=STUB_DXBC, fssm=None):
|
|
"""SPIR-V assembly text for tests/semantic/fixtures/disasm/<name>.s, translated by the translator under test.
|
|
|
|
`dxbc` overrides the empty input signature; pixel shaders that read attributes need a real ISG1 part.
|
|
`fssm` supplies the compute-shader header blob (RSRC2 and group size) for cs_* fixtures.
|
|
"""
|
|
src = os.path.join(FIXTURE_DIR, name + ".s")
|
|
if not os.path.isfile(src):
|
|
raise AssertionError(f"missing fixture {src}") # a missing fixture is a failure, never a skip
|
|
with open(src, "rb") as f:
|
|
return translate_listing(name, f.read(), dxbc, fssm)
|
|
|
|
|
|
def translate_lines(name, lines, dxbc=STUB_DXBC, fssm=None):
|
|
"""Like translate_fixture for a hand-written program given as instruction lines (no fixture file)."""
|
|
text = f"; {name} hand-written test program\n" + "".join("\t" + ln.strip() + "\n" for ln in lines)
|
|
return translate_listing(name, text.encode("utf-8"), dxbc, fssm)
|
|
|
|
|
|
def asm_fixture(name):
|
|
"""The instruction and label lines of the hand-written tests/semantic/fixtures/<name>.asm (comments dropped)."""
|
|
with open(os.path.join(HERE, "fixtures", name + ".asm"), encoding="utf-8") as f:
|
|
return [ln.strip() for ln in f if ln.strip() and not ln.lstrip().startswith(";")]
|
|
|
|
|
|
def resolve_labels(lines, size=4):
|
|
"""Instruction lines with `name:` labels, in the form translate_lines takes: every instruction gets a `size`-byte
|
|
placeholder encoding (the translator places instructions by their encodings) and a branch to a label gets its
|
|
signed dword offset from the next instruction (RDNA2 SOPP: target = PC + 4 + 4 * SIMM16)."""
|
|
labels, placed, pc = {}, [], 0
|
|
for line in lines:
|
|
if line.endswith(":"):
|
|
labels[line[:-1]] = pc
|
|
continue
|
|
placed.append((line, pc))
|
|
pc += size
|
|
out = []
|
|
for line, at in placed:
|
|
words = line.split()
|
|
if words[0].startswith(("s_branch", "s_cbranch_")) and len(words) == 2 and words[1] in labels:
|
|
line = f"{words[0]} {(labels[words[1]] - at - size) // 4}"
|
|
out.append(f"{line} ; encoding: [{','.join(['0x00'] * size)}]")
|
|
return out
|
|
|
|
|
|
def translate_listing(name, data, dxbc=STUB_DXBC, fssm=None):
|
|
"""SPIR-V assembly text for a listing in the translator's input format (bytes of a .s file)."""
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
os.mkdir(os.path.join(tmp, "disasm"))
|
|
with open(os.path.join(tmp, "disasm", name + ".s"), "wb") as f:
|
|
f.write(data)
|
|
with open(os.path.join(tmp, name + ".dxbc"), "wb") as f:
|
|
f.write(dxbc)
|
|
if fssm is not None:
|
|
os.mkdir(os.path.join(tmp, "fssm"))
|
|
with open(os.path.join(tmp, "fssm", name + ".fssm"), "wb") as f:
|
|
f.write(fssm)
|
|
with warnings.catch_warnings():
|
|
# translate() leaves its .dxbc handle to the garbage collector; harmless, and not ours to change here.
|
|
warnings.simplefilter("ignore", ResourceWarning)
|
|
result = rdna2spirv.translate(os.path.join(tmp, "disasm", name + ".s"))
|
|
gc.collect() # release the handle before the temporary directory is removed (Windows)
|
|
return result
|
|
|
|
|
|
def mrt0_words(spvasm, **run_options):
|
|
"""Run the translated pixel shader once; return the four 32-bit words it writes to mrt0."""
|
|
out = run_fragment(spvasm, **run_options)
|
|
if list(out) != ["%out_mrt0"]:
|
|
raise AssertionError(f"expected exactly one output, %out_mrt0; got {sorted(out)}")
|
|
return list(out["%out_mrt0"])
|
|
|
|
|
|
def varyings(spvasm, attrs, bary):
|
|
"""Input values for a translated PS, given {attribute n: three per-vertex vec4s of the producer's raw 32-bit
|
|
words} and the barycentric weights `bary` of vertices 0..2, as Vulkan hands them over: a PerVertexKHR input gets
|
|
the three vertices, a Flat one vertex 0, any other the words read as f32 and interpolated; %bary gets `bary`."""
|
|
f = lambda w: struct.unpack("<f", struct.pack("<I", w))[0] # noqa: E731
|
|
out = {"%bary": tuple(bary)}
|
|
for n, verts in attrs.items():
|
|
name, fv = f"%in_attr{n}", [tuple(f(w) for w in v) for v in verts]
|
|
if f"OpDecorate {name} PerVertexKHR" in spvasm:
|
|
out[name] = tuple(fv)
|
|
elif f"OpDecorate {name} Flat" in spvasm:
|
|
out[name] = fv[0]
|
|
else:
|
|
out[name] = tuple(sum(b * v[c] for b, v in zip(bary, fv)) for c in range(4))
|
|
return out
|