mirror of
https://github.com/ivall/xcl.git
synced 2026-11-24 05:14:57 +01:00
139 lines
6.1 KiB
Python
139 lines
6.1 KiB
Python
"""Generate crates/xcl/src/gpu/rdna2_spec.rs from AMD's Machine-Readable ISA spec.
|
||
|
||
Input: amdgpu_isa_rdna2.xml from https://gpuopen.com/machine-readable-isa/ (MIT licence)
|
||
Usage: python -I scripts/gen_rdna2.py <path/to/amdgpu_isa_rdna2.xml> crates/xcl/src/gpu/rdna2_spec.rs
|
||
|
||
Only the "primary" encodings (condition "default") are emitted with operands; the
|
||
literal / SDWA / DPP / NSA variants are derived at decode time from operand values,
|
||
exactly as the hardware does. Instructions that *always* carry a literal (e.g.
|
||
V_FMAMK_F32) are flagged.
|
||
"""
|
||
|
||
import sys
|
||
import xml.etree.ElementTree as ET
|
||
|
||
|
||
def bits_of(text):
|
||
text = text.strip()
|
||
return int(text, 2), len(text)
|
||
|
||
|
||
def rust_str(s):
|
||
return '"' + s.replace("\\", "\\\\").replace('"', '\\"') + '"'
|
||
|
||
|
||
def main(src, dst):
|
||
root = ET.parse(src).getroot()
|
||
doc = root.find("Document")
|
||
isa = root.find("ISA")
|
||
arch = isa.find("Architecture").findtext("ArchitectureName")
|
||
|
||
encodings = [] # (name, bits, order, fixed_mask, fixed_value, fields, op_ranges)
|
||
enc_index = {}
|
||
for e in isa.find("Encodings"):
|
||
name = e.findtext("EncodingName")
|
||
nbits = int(e.findtext("BitCount"))
|
||
order = int(e.get("Order", "0"))
|
||
mask, _ = bits_of(e.find("EncodingIdentifierMask").text)
|
||
ids = [bits_of(i.text)[0] for i in e.find("EncodingIdentifiers")]
|
||
fields = []
|
||
op_bits = 0
|
||
for f in e.find("MicrocodeFormat").find("BitMap").iter("Field"):
|
||
fname = f.findtext("FieldName")
|
||
ranges = []
|
||
for r in sorted(f.find("BitLayout").findall("Range"), key=lambda r: int(r.get("Order", "0"))):
|
||
off, cnt = int(r.findtext("BitOffset")), int(r.findtext("BitCount"))
|
||
ranges.append((off, cnt))
|
||
if fname == "OP":
|
||
op_bits |= ((1 << cnt) - 1) << off
|
||
fields.append((fname, ranges))
|
||
# identification bits always live in the first 64 bits (NSA masks are longer)
|
||
fixed_mask = mask & ~op_bits & ((1 << 64) - 1)
|
||
values = {i & fixed_mask for i in ids}
|
||
if len(values) != 1:
|
||
raise SystemExit(f"{name}: identifiers disagree outside OP: {sorted(values)}")
|
||
encodings.append((name, nbits, order, fixed_mask, values.pop(), fields))
|
||
enc_index[name] = len(encodings) - 1
|
||
|
||
insts = []
|
||
primary_used = set()
|
||
for i in isa.find("Instructions"):
|
||
name = i.findtext("InstructionName")
|
||
fl = i.find("InstructionFlags")
|
||
flag = 0
|
||
for bit, tag in enumerate(["IsBranch", "IsConditionalBranch", "IsIndirectBranch", "IsProgramTerminator", "IsImmediatelyExecuted"]):
|
||
if (fl.findtext(tag) or "FALSE").upper() == "TRUE":
|
||
flag |= 1 << bit
|
||
encs = []
|
||
always_lit = False
|
||
for ie in i.find("InstructionEncodings"):
|
||
ename = ie.findtext("EncodingName")
|
||
cond = ie.findtext("EncodingCondition")
|
||
primary = ename.startswith("ENC_") or ename == "VOP3_SDST_ENC"
|
||
if "LITERAL" in ename and cond == "default":
|
||
# e.g. V_FMAMK_F32 / S_SETREG_IMM32_B32: the literal is part of the
|
||
# instruction, so the "literal" encoding is its only form – map it onto
|
||
# the base encoding and flag the extra dword.
|
||
always_lit = True
|
||
base = "ENC_" + ename.replace("_INST_LITERAL", "")
|
||
if base in enc_index:
|
||
ename, primary = base, True
|
||
if not primary or not cond.startswith(("default", "Nothas")):
|
||
continue
|
||
ops = []
|
||
for o in sorted(ie.find("Operands"), key=lambda o: int(o.get("Order", "0"))):
|
||
ops.append((
|
||
o.findtext("FieldName"),
|
||
o.findtext("OperandType"),
|
||
int(o.findtext("OperandSize") or "0"),
|
||
o.get("Input") == "true",
|
||
o.get("Output") == "true",
|
||
o.get("IsImplicit") == "true",
|
||
))
|
||
encs.append((enc_index[ename], int(ie.findtext("Opcode")), ops))
|
||
primary_used.add(ename)
|
||
if encs:
|
||
insts.append((name, flag, always_lit, encs))
|
||
|
||
out = []
|
||
w = out.append
|
||
w("// @generated by scripts/gen_rdna2.py – do not edit by hand.")
|
||
w(f"// Source: AMD Machine-Readable GPU ISA Specification, {arch}")
|
||
w(f"// {doc.findtext('Copyright')} Licence: {doc.findtext('License')}. Release {doc.findtext('ReleaseDate')}.")
|
||
w("#![allow(clippy::all)]")
|
||
w("")
|
||
w("use super::rdna2::{Encoding, Field, Inst, InstEnc, Operand};")
|
||
w("")
|
||
w(f"pub const ARCH: &str = {rust_str(arch)};")
|
||
w("")
|
||
w("pub static ENCODINGS: &[Encoding] = &[")
|
||
for (name, nbits, order, fmask, fval, fields) in encodings:
|
||
fs = ", ".join(
|
||
"Field { name: %s, ranges: &[%s] }" % (rust_str(fn), ", ".join(f"({o}, {c})" for o, c in rs))
|
||
for fn, rs in fields
|
||
)
|
||
prim = "true" if name in primary_used else "false"
|
||
w(f" Encoding {{ name: {rust_str(name)}, bits: {nbits}, order: {order}, primary: {prim}, fixed_mask: {fmask:#x}, fixed_value: {fval:#x}, fields: &[{fs}] }},")
|
||
w("];")
|
||
w("")
|
||
w("pub static INSTRUCTIONS: &[Inst] = &[")
|
||
for (name, flag, always_lit, encs) in insts:
|
||
es = []
|
||
for (ei, opc, ops) in encs:
|
||
os_ = ", ".join(
|
||
"Operand { field: %s, ty: %s, size: %d, input: %s, output: %s, implicit: %s }" % (
|
||
("Some(%s)" % rust_str(f)) if f else "None", rust_str(t), sz,
|
||
str(inp).lower(), str(outp).lower(), str(imp).lower())
|
||
for (f, t, sz, inp, outp, imp) in ops
|
||
)
|
||
es.append(f"InstEnc {{ encoding: {ei}, opcode: {opc}, operands: &[{os_}] }}")
|
||
w(f" Inst {{ name: {rust_str(name)}, flags: {flag}, always_literal: {str(always_lit).lower()}, encs: &[{', '.join(es)}] }},")
|
||
w("];")
|
||
with open(dst, "w", encoding="utf-8", newline="\n") as f:
|
||
f.write("\n".join(out) + "\n")
|
||
print(f"{arch}: {len(encodings)} encodings ({len(primary_used)} primary), {len(insts)} instructions -> {dst}")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main(sys.argv[1], sys.argv[2])
|