mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-12-03 12:22:28 +00:00
A Rust crate replacing the experiment-branch Python prototype: console container reader, a decoder for every encoding format (opcode names generated from the public LLVM disassembler; SDWA/DPP extension words), HLSL translation of every prototype rule through family tables, and coverage over local shaders. bx-cli shader translate and bx-cli shader coverage run it. The decoder prints the text llvm-mc prints for 127 instructions; three shader pairs of our own translate to exactly the prototype's output. Locally, all 4,331 target-build VS/PS shaders decode, 703 translate on their own (491 with the prototype's rules), and all 214 pipeline pairs the prototype translated give identical HLSL and layout. Signed-off-by: ates <ahmetrizaates@hotmail.com>
130 lines
7.3 KiB
Python
130 lines
7.3 KiB
Python
#!/usr/bin/env python3
|
|
"""Generates shader-transpiler/crates/gfx10-translate/src/opcodes.rs: the GFX10.3 (gfx1030)
|
|
instruction names for every opcode value of every encoding format the decoder handles.
|
|
|
|
The names come from the public LLVM AMDGPU disassembler (llvm-mc, Apache-2.0 WITH
|
|
LLVM-exception): for each format, an instruction word is built with each opcode value and
|
|
fixed, valid operand fields, and llvm-mc names it or rejects it. Only the resulting facts (opcode
|
|
number -> mnemonic) are committed; LLVM itself is not.
|
|
|
|
usage: gen_opcodes.py [--llvm-mc PATH] > shader-transpiler/crates/gfx10-translate/src/opcodes.rs
|
|
"""
|
|
import argparse
|
|
import concurrent.futures
|
|
import os
|
|
import subprocess
|
|
import sys
|
|
|
|
# (name, opcode bits, word builder, mask of word 0's format and opcode bits) per format.
|
|
# Builders place `op` in the format's opcode field; the other fields hold valid registers.
|
|
# Layouts: AMD "RDNA 2" instruction set reference.
|
|
FORMATS = [
|
|
# SOP2 opcodes from 0x60 and VOP2 opcodes from 0x3E are the prefixes of other formats.
|
|
("SOP2", 7, lambda op: [0x80000000 | (op << 23) | (2 << 8) | 1] if op < 0x60 else None, 0xFF800000),
|
|
("SOPK", 5, lambda op: [[0xB0000000 | (op << 23) | 0x10], [0xB0000000 | (op << 23) | 0x1801, 0x1]], 0xFF800000),
|
|
("SOP1", 8, lambda op: [0xBE800000 | (op << 8) | 2], 0xFF80FF00),
|
|
("SOPC", 7, lambda op: [0xBF000000 | (op << 16) | (2 << 8) | 1], 0xFFFF0000),
|
|
("SOPP", 7, lambda op: [0xBF800000 | (op << 16)], 0xFFFF0000),
|
|
("SMEM", 8, lambda op: [0xF4000000 | (op << 18) | 2, 0xFA000010], 0xFFFC0000),
|
|
# v_madmk/madak/fmamk/fmaak carry a literal constant after the instruction word.
|
|
("VOP2", 6, lambda op: [[(op << 25) | (2 << 9) | 0x101], [(op << 25) | (2 << 9) | 0x101, 0x3F800000]] if op < 0x3E else None,
|
|
0xFE000000),
|
|
("VOP1", 8, lambda op: [0x7E000000 | (op << 9) | 0x101], 0xFE01FE00),
|
|
("VOPC", 8, lambda op: [0x7C000000 | (op << 17) | (2 << 9) | 0x101], 0xFFFE0000),
|
|
("VOP3", 10, lambda op: [0xD4000000 | (op << 16), (0x103 << 18) | (0x102 << 9) | 0x101], 0xFFFF0000),
|
|
("VOP3P", 7, lambda op: [0xCC000000 | (op << 16), (0x103 << 18) | (0x102 << 9) | 0x101], 0xFC7F0000),
|
|
("VINTRP", 2, lambda op: [0xC8000000 | (op << 16) | 1], 0xFC030000),
|
|
("DS", 8, lambda op: [[0xD8000000 | (op << 18), w] for w in (0x00000201, 0x00000001, 0x00030201)], 0xFFFC0000),
|
|
("MUBUF", 7, lambda op: [0xE0000000 | ((op & 0x7F) << 18) | 0x2000, 0x80010001], 0xFDFC0000),
|
|
("MTBUF", 4, lambda op: [0xE8000000 | (op & 7) << 16 | (22 << 19) | 0x2000, 0x80010001 | ((op >> 3) << 21)], 0xFC070000),
|
|
("MIMG", 8, lambda op: [[0xF0000000 | ((op & 0x7F) << 18) | ((op >> 7) << 0) | (1 << 3) | (0xF << 8), w]
|
|
for w in (0x00820004, 0x00020004)], 0xFDFC0001),
|
|
("FLAT", 7, lambda op: [0xDC000000 | (op << 18), 0x007D0001], 0xFDFCC000),
|
|
("GLOBAL", 7, lambda op: [0xDC008000 | (op << 18), 0x007D0001], 0xFDFCC000),
|
|
]
|
|
|
|
|
|
def name_of(llvm_mc, words, mask, mcpu):
|
|
"""The mnemonic llvm-mc gives `words`, or None. A name counts only when llvm-mc reports no
|
|
invalid encoding and its first instruction is as long as `words` with the same format and
|
|
opcode bits (`mask`): for an invalid opcode, llvm-mc skips a word and decodes the next one as
|
|
an instruction of its own. Operand fields may be re-encoded, so they are not compared."""
|
|
data = b"".join(w.to_bytes(4, "little") for w in words)
|
|
text = " ".join("0x%02x" % b for b in data)
|
|
r = subprocess.run([llvm_mc, "--disassemble", "-show-encoding", "-arch=amdgcn", "-mcpu=" + mcpu], input=text,
|
|
capture_output=True, text=True)
|
|
if "invalid instruction encoding" in r.stderr:
|
|
return None
|
|
for line in r.stdout.splitlines():
|
|
if "encoding:" not in line:
|
|
continue
|
|
asm, enc = line.split("; encoding:")
|
|
encoded = bytes(int(b, 16) for b in enc.strip().strip("[]").split(","))
|
|
same = len(encoded) == len(data) and (int.from_bytes(encoded[:4], "little") & mask) == (words[0] & mask)
|
|
return asm.split()[0] if same else None
|
|
return None
|
|
|
|
|
|
def main():
|
|
ap = argparse.ArgumentParser()
|
|
ap.add_argument("--llvm-mc", default=os.environ.get("LLVM_MC", "/opt/homebrew/opt/llvm/bin/llvm-mc"))
|
|
a = ap.parse_args()
|
|
version = subprocess.run([a.llvm_mc, "--version"], capture_output=True, text=True).stdout.split("\n")
|
|
version = next((v.strip() for v in version if "version" in v.lower()), "unknown")
|
|
jobs = [(fmt, op, build(op), mask) for fmt, bits, build, mask in FORMATS for op in range(1 << bits)]
|
|
|
|
def first_name(job):
|
|
# A builder gives one word list, or several variants of the operand fields to try in turn
|
|
# (llvm-mc rejects some opcodes unless their unused fields are zero).
|
|
if job[2] is None:
|
|
return None
|
|
variants = job[2] if isinstance(job[2][0], list) else [job[2]]
|
|
# gfx1030 first; the console compiler also emits a few GFX10.1 instructions that LLVM
|
|
# knows only for gfx1010 (v_mac_f32), so gaps are filled from there.
|
|
for mcpu in ("gfx1030", "gfx1010"):
|
|
for v in variants:
|
|
n = name_of(a.llvm_mc, v, job[3], mcpu)
|
|
if n:
|
|
return n
|
|
return None
|
|
|
|
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool:
|
|
names = list(pool.map(first_name, jobs))
|
|
out = ["// @generated by scripts/console-shader/gen_opcodes.py from %s (gfx1030, gaps from gfx1010)." % version,
|
|
"// Do not edit. Facts only: opcode number -> mnemonic, per encoding format, as named by the",
|
|
"// public LLVM AMDGPU disassembler (Apache-2.0 WITH LLVM-exception).", "",
|
|
"/// (opcode, mnemonic) pairs of one encoding format, sorted by opcode.", "pub type Table = &'static [(u16, &'static str)];", ""]
|
|
for fmt, _, _, _ in FORMATS:
|
|
rows = [(op, n) for (f, op, _, _), n in zip(jobs, names) if f == fmt and n]
|
|
out.append("pub static %s: Table = &[" % fmt)
|
|
for op, n in rows:
|
|
out.append(" (%d, \"%s\")," % (op, n))
|
|
out.append("];")
|
|
out.append("")
|
|
print("%s: %d opcodes" % (fmt, len(rows)), file=sys.stderr)
|
|
# MTBUF unified buffer formats (word 0 bits 25:19), named by the disassembler as format:[NAME].
|
|
def format_name(value):
|
|
words = [0xE8000000 | (value << 19) | (3 << 16) | 0x2000, 0x80000000]
|
|
text = " ".join("0x%02x" % b for w in words for b in w.to_bytes(4, "little"))
|
|
r = subprocess.run([a.llvm_mc, "--disassemble", "-arch=amdgcn", "-mcpu=gfx1030"], input=text,
|
|
capture_output=True, text=True)
|
|
if "invalid instruction encoding" in r.stderr or "format:[" not in r.stdout:
|
|
return None
|
|
return r.stdout.split("format:[")[1].split("]")[0]
|
|
|
|
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool:
|
|
formats = list(pool.map(format_name, range(128)))
|
|
out.append("/// MTBUF unified buffer formats: (value, name), as `format:[NAME]` prints them.")
|
|
out.append("pub static BUF_FORMATS: Table = &[")
|
|
for value, name in enumerate(formats):
|
|
if name and not name.isdigit():
|
|
out.append(" (%d, \"%s\")," % (value, name))
|
|
out.append("];")
|
|
out.append("")
|
|
print("BUF_FORMATS: %d" % sum(1 for f in formats if f and not f.isdigit()), file=sys.stderr)
|
|
sys.stdout.write("\n".join(out))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|