Initial XCL source and TTPF viewer

This commit is contained in:
ivall
2026-11-20 21:03:53 +01:00
commit 8fa7fa0fa3
113 changed files with 101440 additions and 0 deletions
+52
View File
@@ -0,0 +1,52 @@
"""Generate crates/xcl/src/hle/d3d12_layout.rs from d3d12.h (microsoft/DirectX-Headers, MIT).
Usage: python -I scripts/gen_d3d12_layout.py <d3d12.h> crates/xcl/src/hle/d3d12_layout.rs
Extracts, for every ID3D12* COM interface: IID, parent interface and the full vtable
method order (including inherited IUnknown/ID3D12Object methods) from the C-style
`XxxVtbl` structs. XCL uses PC order as the first guess for D3D12.X objects and names
every slot in its logs/reports.
"""
import re
import sys
def main(src, dst):
text = open(src, encoding="utf-8", errors="replace").read()
iids = {}
parents = {}
for m in re.finditer(r'MIDL_INTERFACE\("([0-9a-fA-F-]{36})"\)\s*(\w+)\s*:\s*public\s+(\w+)', text):
iids[m.group(2)] = m.group(1).lower()
parents[m.group(2)] = m.group(3)
vtbls = {}
for m in re.finditer(r"typedef struct (\w+)Vtbl\s*\{(.*?)\}\s*\1Vtbl;", text, re.S):
name, body = m.group(1), m.group(2)
raw = re.findall(r"\(\s*STDMETHODCALLTYPE\s*\*\s*(\w+)\s*\)", body)
# struct-returning methods are declared twice (#if !defined(_WIN32) / #else)
methods = [m for i, m in enumerate(raw) if i == 0 or raw[i - 1] != m]
vtbls[name] = methods
names = sorted(n for n in vtbls if n.startswith("ID3D12") and n in iids)
out = [
"// @generated by scripts/gen_d3d12_layout.py from d3d12.h (microsoft/DirectX-Headers, MIT) – do not edit.",
"",
"pub struct Iface {",
" pub name: &'static str,",
" pub iid: &'static str,",
" pub parent: &'static str,",
" pub methods: &'static [&'static str],",
"}",
"",
"pub static IFACES: &[Iface] = &[",
]
for n in names:
ms = ", ".join(f'"{x}"' for x in vtbls[n])
out.append(f' Iface {{ name: "{n}", iid: "{iids[n]}", parent: "{parents.get(n, "")}", methods: &[{ms}] }},')
out.append("];")
open(dst, "w", encoding="utf-8", newline="\n").write("\n".join(out) + "\n")
dev = max((n for n in names if re.fullmatch(r"ID3D12Device\d*", n)), key=lambda n: len(vtbls[n]))
print(f"{len(names)} interfaces; most derived device {dev} with {len(vtbls[dev])} methods -> {dst}")
if __name__ == "__main__":
main(sys.argv[1], sys.argv[2])
+138
View File
@@ -0,0 +1,138 @@
"""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])
+7
View File
@@ -0,0 +1,7 @@
# Build everything (the e2e test needs the test title + DLL) and run all tests.
$ErrorActionPreference = 'Stop'
Set-Location (Join-Path $PSScriptRoot '..')
cargo build --workspace
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
cargo test --workspace -- --test-threads=4
exit $LASTEXITCODE