mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-27 05:12:50 +00:00
Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0609012903 | ||
|
|
dffa50cd9c | ||
|
|
b541dce0cc | ||
|
|
52ecece126 | ||
|
|
440856a997 | ||
|
|
1eeb614ea2 | ||
|
|
afd936b20b | ||
|
|
1680e6b19c | ||
|
|
3eef0ecfa8 | ||
|
|
e616583c3f | ||
|
|
c9e3394eb3 | ||
|
|
358ddc5eba |
No files matched your search
@@ -38,6 +38,8 @@ jobs:
|
||||
- name: Check generated status and PE fixtures
|
||||
run: |
|
||||
python3 crates/isa/generate_rdna2_meta.py --check
|
||||
python3 crates/isa/generate_semantics.py --check
|
||||
python3 scripts/audit/semantic_coverage.py --check
|
||||
python3 scripts/audit/status.py --check
|
||||
for fixture in x2 x3 x4; do
|
||||
python3 "experiments/x1/fixtures/$fixture.py" --check || exit 1
|
||||
@@ -48,6 +50,10 @@ jobs:
|
||||
sh -n scripts/agent-queue.sh scripts/agent-sync.sh
|
||||
- name: Test pull request template check
|
||||
run: PYTHONPATH=scripts python3 -m unittest discover -s tests/pr_template
|
||||
- name: Test semantic registry generator and coverage report
|
||||
run: |
|
||||
python3 -m unittest discover -s tests/semantics_generator
|
||||
PYTHONPATH=scripts python3 -m unittest discover -s tests/semantic_coverage
|
||||
- name: Check formatting and lint
|
||||
run: |
|
||||
cargo fmt --all -- --check
|
||||
|
||||
@@ -11,6 +11,7 @@ remains unsupported.
|
||||
|
||||
### Added
|
||||
|
||||
- Added a declarative semantic registry for gfx1030 instruction forms (`crates/isa/semantics/rdna2.toml`, schema 1) and its generator, `crates/isa/generate_semantics.py`, with `validate`, `generate` and `--check` modes. The generator checks every declaration against a closed vocabulary and the pinned AMD XML snapshot (opcode, family, SCC input and output, operand widths and signed formats), rejects contradictory, incomplete or duplicate definitions, and emits static Rust tables marked as generated. The nine SOP2 forms moved onto it with no change in behaviour: the decoder's SOP2 dispatch and `ScalarAluOp`'s mnemonic, SCC read and evaluation are now generated, and evaluation goes through shared primitives instead of per-opcode code. All existing SOP2 tests, including the native Metal known answers and the LLVM comparison, pass unchanged. Decoding speed is unchanged (10.2 ns before, 10.1 ns after, per SOP2 instruction, release build on an Apple M5 Pro). Also added `scripts/audit/semantic_coverage.py`, which generates `docs/shaders/semantic-coverage.md`: per-family counts of identified, declared, decoded, lowered, reference-verified and Metal-verified forms, taking evidence only from `docs/status.toml`. Part of #215, stages A and B.
|
||||
- Added a native Metal blend pass, `NativeCompute::render_blend`: up to 16 flat-coloured triangles drawn in order into an RGBA8 target, each with its own colour write mask (any subset of R, G, B, A) and either blending disabled or separate RGB and alpha blend factors (Zero, One, source and destination colour and alpha, and their one-minus forms) and operations (Add, Subtract, ReverseSubtract, and Min and Max, which take the unweighted values). Checked on the GPU with Metal validation in 39 passes over two original overlapping triangles: a clear-only pass; blending disabled; each source factor with the destination term zeroed and each destination factor with the source term zeroed; every operation; additive clamping; separate alpha factors; a separate alpha operation; eight write masks (each channel alone, RGB, none, RGBA, and RG with blending); and a pass whose first draw is itself blended and masked. Colours are compared per channel against images derived independently (in exact fractions) from the public Metal blend equations, which a new CPU reference in `xenora-ref` also reproduces. The tolerance was fixed before measuring: channels whose exact result is a whole 8-bit value must match exactly, and channels that need rounding may differ by 1. On an Apple M5 Pro every rounded channel matched round-to-nearest exactly. Synthetic fixtures only; no console blend state is involved.
|
||||
- Added indexed triangle draws. Native Metal: `NativeCompute::render_indexed` issues one real `drawIndexedPrimitives` call per draw (up to 16) on a 16- or 32-bit index buffer with a start index and a signed base vertex, into an RGBA8 target; a draw can sample an original BC1 texture uploaded natively. Before encoding anything it rejects the whole pass for a bad index count, an index range past the buffer, any `index + base vertex` outside the vertex buffer, and, as this API's policy, a raw all-ones index (the primitive-restart value, which Metal does not define for triangle lists). Loader: a synthetic, CPU-side index buffer binding (resource handle and offset, the view running to the end of the resource) with `cmd_set_index_buffer` and `cmd_draw_indexed_instanced`, which fetch one triangle, drawn once, through the index buffer, start index and base vertex and pass it to the existing one-triangle backend; each drawn triangle replaces the previous output. Recording rejects formats other than DXGI `R16_UINT` and `R32_UINT`, offsets not aligned to the index size or past the resource, and unknown resources. Execution checks each draw in turn, so earlier draws have already rendered when a later one fails: index counts other than 0 or 3, more than one instance or a nonzero start instance, a missing index buffer, indices past the buffer and an `index + base vertex` outside the vertex buffer are typed errors; a valid zero index or instance count draws nothing. All-ones indices are ordinary indices there. Checked on the GPU with Metal validation in 16 passes (both index sizes, 32-bit indices above 16 bits, odd 16-bit start, positive and negative base vertex, reversed winding, flat and textured two-triangle draws, draw order, BC1-textured draws), compared per pixel against images derived independently from the geometry, the public D3D12 and Metal index semantics and the public BC1 rules, which a new CPU reference in `xenora-ref` also reproduces; the loader's fetch is checked against literal positions with synthetic guest-backed buffers and through the native Metal renderer. Synthetic fixtures only; no console index-buffer views, guest programs or console draw state are involved.
|
||||
- Added a `cpu_decode` cargo-fuzz target for the static x86-64 decoder used by the read-only PE probe. It places up to 4,096 fuzz bytes as the code section of a fixed, original PE32+ header and runs `probe_pe_bytes` twice with a bounded `ProbeConfig` (4,096 bytes, 2,048 instructions, 1,024 worklist entries); nothing is executed. It checks that the two reports are identical and that every decoded instruction is 1 to 15 bytes long, lies inside the code and matches the input bytes. A startup self-check aborts the run if the synthetic header stops reaching the decoder. A 600-second local campaign (nightly cargo-fuzz, one fork-mode worker, seeded from instruction bytes in the loader's probe tests; about 2.38 million executions, coverage 1,350 edges) found one decoder defect, reported to the CPU owner on #74 and not fixed here: the probe accepts unlimited FS/GS segment prefixes and reports instructions longer than 15 bytes (minimized input: 16 bytes of `0x65`). Run it with `rustup run nightly cargo fuzz run cpu_decode`; `scripts/fuzz.sh` does not list it yet.
|
||||
|
||||
+28
-29
@@ -7,9 +7,8 @@ pub use xenora_isa::{
|
||||
ScalarSource, VectorCompareOp, VectorSource,
|
||||
};
|
||||
use xenora_isa::{
|
||||
BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_ADD_I32, S_ADD_U32, S_ADDC_U32,
|
||||
S_AND_B32, S_BRANCH, S_CBRANCH_EXECZ, S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_CMP_EQ_U32, S_ENDPGM,
|
||||
S_MOV_B32, S_OR_B32, S_SUB_I32, S_SUB_U32, S_SUBB_U32, S_WAITCNT, S_WAITCNT_VSCNT, S_XOR_B32,
|
||||
BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_BRANCH, S_CBRANCH_EXECZ,
|
||||
S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_CMP_EQ_U32, S_ENDPGM, S_MOV_B32, S_WAITCNT, S_WAITCNT_VSCNT,
|
||||
V_ADD_F32, V_ADD_NC_U32, V_AND_B32, V_ASHRREV_I32, V_CMP_EQ_I32, V_CMP_EQ_U32, V_CMP_GE_I32,
|
||||
V_CMP_GE_U32, V_CMP_GT_I32, V_CMP_GT_U32, V_CMP_LE_I32, V_CMP_LE_U32, V_CMP_LT_I32,
|
||||
V_CMP_LT_U32, V_CMP_NE_I32, V_CMP_NE_U32, V_INTERP_P1_F32, V_INTERP_P2_F32, V_LSHLREV_B32,
|
||||
@@ -17,19 +16,36 @@ use xenora_isa::{
|
||||
};
|
||||
|
||||
use xenora_isa::meta::EncodingFamily;
|
||||
use xenora_isa::semantics::FORM_IDS;
|
||||
|
||||
/// Metadata forms that [`decode`] turns into an [`Instruction`] for at least one
|
||||
/// operand combination. Operand restrictions are listed in docs/status.toml;
|
||||
/// every other form in [`xenora_isa::meta::FORMS`] is rejected as unsupported.
|
||||
pub const SEMANTIC_FORMS: [(&str, EncodingFamily); 46] = [
|
||||
/// operand combination: the hand-written forms below followed by every form of
|
||||
/// the semantic registry ([`xenora_isa::semantics::FORM_IDS`]). Operand
|
||||
/// restrictions are listed in docs/status.toml; every other form in
|
||||
/// [`xenora_isa::meta::FORMS`] is rejected as unsupported.
|
||||
pub const SEMANTIC_FORMS: [(&str, EncodingFamily); HANDWRITTEN_FORMS.len() + FORM_IDS.len()] =
|
||||
concat_forms();
|
||||
|
||||
const fn concat_forms<const N: usize>() -> [(&'static str, EncodingFamily); N] {
|
||||
let mut forms = [("", EncodingFamily::Sop2); N];
|
||||
let mut index = 0;
|
||||
while index < N {
|
||||
forms[index] = if index < HANDWRITTEN_FORMS.len() {
|
||||
HANDWRITTEN_FORMS[index]
|
||||
} else {
|
||||
FORM_IDS[index - HANDWRITTEN_FORMS.len()]
|
||||
};
|
||||
index += 1;
|
||||
}
|
||||
forms
|
||||
}
|
||||
|
||||
/// Decoded forms not yet described by the semantic registry.
|
||||
const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 37] = [
|
||||
("BUFFER_LOAD_DWORD", EncodingFamily::Mubuf),
|
||||
("BUFFER_STORE_DWORD", EncodingFamily::Mubuf),
|
||||
("EXP", EncodingFamily::Exp),
|
||||
("IMAGE_SAMPLE_LZ", EncodingFamily::Mimg),
|
||||
("S_ADD_I32", EncodingFamily::Sop2),
|
||||
("S_ADD_U32", EncodingFamily::Sop2),
|
||||
("S_ADDC_U32", EncodingFamily::Sop2),
|
||||
("S_AND_B32", EncodingFamily::Sop2),
|
||||
("S_BRANCH", EncodingFamily::Sopp),
|
||||
("S_CBRANCH_EXECZ", EncodingFamily::Sopp),
|
||||
("S_CBRANCH_SCC0", EncodingFamily::Sopp),
|
||||
@@ -37,13 +53,8 @@ pub const SEMANTIC_FORMS: [(&str, EncodingFamily); 46] = [
|
||||
("S_CMP_EQ_U32", EncodingFamily::Sopc),
|
||||
("S_ENDPGM", EncodingFamily::Sopp),
|
||||
("S_MOV_B32", EncodingFamily::Sop1),
|
||||
("S_OR_B32", EncodingFamily::Sop2),
|
||||
("S_SUB_I32", EncodingFamily::Sop2),
|
||||
("S_SUB_U32", EncodingFamily::Sop2),
|
||||
("S_SUBB_U32", EncodingFamily::Sop2),
|
||||
("S_WAITCNT", EncodingFamily::Sopp),
|
||||
("S_WAITCNT_VSCNT", EncodingFamily::Sopk),
|
||||
("S_XOR_B32", EncodingFamily::Sop2),
|
||||
("V_ADD_F32", EncodingFamily::Vop2),
|
||||
("V_ADD_NC_U32", EncodingFamily::Vop3),
|
||||
("V_AND_B32", EncodingFamily::Vop2),
|
||||
@@ -384,20 +395,8 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
|
||||
let target = branch_target(first, offset, "s_branch")?;
|
||||
return Ok((Instruction::Branch { target }, S_BRANCH.byte_len()));
|
||||
}
|
||||
for (opcode, op) in [
|
||||
(S_ADD_U32, ScalarAluOp::AddU32),
|
||||
(S_SUB_U32, ScalarAluOp::SubU32),
|
||||
(S_ADD_I32, ScalarAluOp::AddI32),
|
||||
(S_SUB_I32, ScalarAluOp::SubI32),
|
||||
(S_ADDC_U32, ScalarAluOp::AddcU32),
|
||||
(S_SUBB_U32, ScalarAluOp::SubbU32),
|
||||
(S_AND_B32, ScalarAluOp::AndB32),
|
||||
(S_OR_B32, ScalarAluOp::OrB32),
|
||||
(S_XOR_B32, ScalarAluOp::XorB32),
|
||||
] {
|
||||
if opcode.matches(first) {
|
||||
return scalar_alu(op, first, bytes);
|
||||
}
|
||||
if let Some(op) = ScalarAluOp::from_word(first) {
|
||||
return scalar_alu(op, first, bytes);
|
||||
}
|
||||
if S_CBRANCH_SCC0.matches(first) {
|
||||
let target = branch_target(first, offset, "s_cbranch_scc0")?;
|
||||
|
||||
@@ -18,15 +18,6 @@ VARIANTS = (
|
||||
("S_ENDPGM", "ENC_SOPP"),
|
||||
("S_MOV_B32", "ENC_SOP1"),
|
||||
("S_CMP_EQ_U32", "ENC_SOPC"),
|
||||
("S_ADD_U32", "ENC_SOP2"),
|
||||
("S_SUB_U32", "ENC_SOP2"),
|
||||
("S_ADD_I32", "ENC_SOP2"),
|
||||
("S_SUB_I32", "ENC_SOP2"),
|
||||
("S_ADDC_U32", "ENC_SOP2"),
|
||||
("S_SUBB_U32", "ENC_SOP2"),
|
||||
("S_AND_B32", "ENC_SOP2"),
|
||||
("S_OR_B32", "ENC_SOP2"),
|
||||
("S_XOR_B32", "ENC_SOP2"),
|
||||
("S_CBRANCH_SCC0", "ENC_SOPP"),
|
||||
("S_CBRANCH_EXECZ", "ENC_SOPP"),
|
||||
("S_CBRANCH_VCCZ", "ENC_SOPP"),
|
||||
|
||||
Executable
+541
@@ -0,0 +1,541 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Validate the declarative gfx1030 semantic registry and generate its Rust tables.
|
||||
|
||||
validate check crates/isa/semantics/rdna2.toml against its closed vocabulary
|
||||
and the pinned AMD XML snapshot (crates/isa/data/rdna2.jsonl)
|
||||
generate validate, then write crates/isa/src/semantics_gen.rs
|
||||
--check validate and regenerate in memory; exit 1 if the committed file
|
||||
differs. Never writes.
|
||||
|
||||
The registry is data only. Behaviour is chosen from a closed set of primitives
|
||||
(crates/isa/src/primitive.rs) by the declared operation, signedness and SCC
|
||||
effect, never from a mnemonic. Only the Python standard library is used
|
||||
(tomllib needs Python 3.11 or newer). See docs/shaders/semantic-registry.md.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
try:
|
||||
import tomllib
|
||||
except ModuleNotFoundError: # pragma: no cover - depends on the interpreter
|
||||
sys.exit("generate_semantics.py needs Python 3.11 or newer (tomllib)")
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
REGISTRY = ROOT / "crates/isa/semantics/rdna2.toml"
|
||||
SNAPSHOT = ROOT / "crates/isa/data/rdna2.jsonl"
|
||||
RUST = ROOT / "crates/isa/src/semantics_gen.rs"
|
||||
|
||||
SCHEMA = 1
|
||||
ARCHITECTURE = "gfx1030"
|
||||
|
||||
FORM_KEYS = {
|
||||
"name", "family", "opcode", "variant", "operation", "signedness", "carry_in",
|
||||
"width", "scc", "vcc", "exec", "wave", "operands", "spec", "verify",
|
||||
}
|
||||
TOP_KEYS = {"schema", "architecture", "source_sha256", "documents", "operand_rules", "form"}
|
||||
|
||||
OPERATIONS = {"add": "Add", "sub": "Sub", "and": "And", "or": "Or", "xor": "Xor"}
|
||||
LOGICAL = {"and", "or", "xor"}
|
||||
SIGNEDNESS = {"unsigned": "Unsigned", "signed": "Signed", "bitwise": "Bitwise"}
|
||||
CARRY_IN = {"none": "None", "scc": "Scc"}
|
||||
SCC = {
|
||||
"unchanged": "Unchanged",
|
||||
"carry_out": "CarryOut",
|
||||
"borrow": "Borrow",
|
||||
"signed_overflow": "SignedOverflow",
|
||||
"nonzero": "Nonzero",
|
||||
}
|
||||
MASK = {"unchanged": "Unchanged"}
|
||||
WAVE = {"any": "Any", "wave32": "Wave32"}
|
||||
# The decoder has no wave-size input at the registry dispatch yet, so a Wave32
|
||||
# restriction could be declared but not enforced. Reject it until it can be.
|
||||
ENFORCED_WAVES = {"any"}
|
||||
EVIDENCE = {
|
||||
"reference": "Reference",
|
||||
"independent": "Independent",
|
||||
"metal": "Metal",
|
||||
"llvm_encoding": "LlvmEncoding",
|
||||
}
|
||||
DOCUMENTS = {"guide": "Guide", "xml": "Xml"}
|
||||
# The public documents spec references may cite, pinned so a citation cannot
|
||||
# silently point at another file.
|
||||
PINNED_DOCUMENTS = {
|
||||
"guide": {
|
||||
"title": "AMD RDNA 2 Instruction Set Architecture Reference Guide",
|
||||
"file": "rdna2-shader-instruction-set-architecture.pdf",
|
||||
"pages": 291,
|
||||
},
|
||||
"xml": {
|
||||
"title": "AMD RDNA 2 machine-readable ISA (pinned XML)",
|
||||
"file": "amdgpu_isa_rdna2.xml",
|
||||
},
|
||||
}
|
||||
WIDTHS = {32}
|
||||
|
||||
# (operation, signedness) -> (required SCC effect, primitive, takes carry-in).
|
||||
# A form whose declaration is not a row here has no primitive and is rejected.
|
||||
PRIMITIVES = {
|
||||
("add", "unsigned"): ("carry_out", "add_carry_u32", True),
|
||||
("sub", "unsigned"): ("borrow", "sub_borrow_u32", True),
|
||||
("add", "signed"): ("signed_overflow", "add_overflow_i32", False),
|
||||
("sub", "signed"): ("signed_overflow", "sub_overflow_i32", False),
|
||||
("and", "bitwise"): ("nonzero", "and_nonzero_b32", False),
|
||||
("or", "bitwise"): ("nonzero", "or_nonzero_b32", False),
|
||||
("xor", "bitwise"): ("nonzero", "xor_nonzero_b32", False),
|
||||
}
|
||||
|
||||
# Operand rules the decoder implements, each exactly once. A registry rule must
|
||||
# match one of these shapes; anything else is an unimplemented rule.
|
||||
UNSUPPORTED_COMBOS = {
|
||||
"dst_vcc", "dst_exec", "dst_ttmp", "dst_m0", "dst_null", "src_vcc", "src_exec",
|
||||
"src_m0", "src_ttmp", "src_float_inline", "src_special", "two_literals",
|
||||
}
|
||||
OPERAND_RULES = {
|
||||
"sop2_sgpr": {
|
||||
"rust": "Sop2Sgpr",
|
||||
"enum": "ScalarAluOp",
|
||||
"shape": {
|
||||
"family": "SOP2",
|
||||
"dst": {"field": "SDST", "class": "sgpr", "min": 0, "max": 105},
|
||||
"src": [
|
||||
{"field": "SSRC0", "class": "scalar_source"},
|
||||
{"field": "SSRC1", "class": "scalar_source"},
|
||||
],
|
||||
"max_literals": 1,
|
||||
},
|
||||
# Every one of these is rejected by the decoder's SOP2 operand checks.
|
||||
"unsupported": UNSUPPORTED_COMBOS,
|
||||
},
|
||||
}
|
||||
|
||||
VARIANT = re.compile(r"^[A-Z][A-Za-z0-9]*$")
|
||||
RESERVED_VARIANTS = {"Self", "ALL"}
|
||||
U16_MAX = 0xFFFF
|
||||
NAME = re.compile(r"^[A-Z][A-Z0-9_]*$")
|
||||
SECTION = re.compile(r"^[0-9]+(\.[0-9]+)*$")
|
||||
|
||||
|
||||
def load_registry(path=REGISTRY):
|
||||
"""Parse the TOML registry into a dict."""
|
||||
with open(path, "rb") as handle:
|
||||
return tomllib.load(handle)
|
||||
|
||||
|
||||
def load_snapshot(path=SNAPSHOT):
|
||||
"""Index the normalised XML snapshot: source line, encodings, default variants."""
|
||||
source = None
|
||||
encodings = {}
|
||||
variants = {}
|
||||
with open(path, encoding="utf-8") as handle:
|
||||
for line in handle:
|
||||
record = json.loads(line)
|
||||
kind = record.get("kind")
|
||||
if kind == "source":
|
||||
source = record
|
||||
elif kind == "encoding":
|
||||
encodings[record["name"]] = record
|
||||
elif kind == "variant" and record.get("condition") == "default":
|
||||
variants[(record["instruction"], record["encoding"])] = record
|
||||
return {"source": source or {}, "encodings": encodings, "variants": variants}
|
||||
|
||||
|
||||
def _family_encoding(family):
|
||||
return "ENC_" + family
|
||||
|
||||
|
||||
def _rust_family(family):
|
||||
return family[0] + family[1:].lower()
|
||||
|
||||
|
||||
def _check_rule(name, rule, errors):
|
||||
implemented = OPERAND_RULES.get(name)
|
||||
if implemented is None:
|
||||
errors.append(f"operand rule {name}: not implemented by the decoder")
|
||||
return
|
||||
unsupported = rule.get("unsupported", [])
|
||||
unknown = sorted(set(unsupported) - UNSUPPORTED_COMBOS)
|
||||
if unknown:
|
||||
errors.append(f"operand rule {name}: unknown unsupported combos {unknown}")
|
||||
if len(set(unsupported)) != len(unsupported):
|
||||
errors.append(f"operand rule {name}: duplicate unsupported combos")
|
||||
if set(unsupported) != implemented["unsupported"]:
|
||||
errors.append(
|
||||
f"operand rule {name}: unsupported combos differ from those the decoder rejects"
|
||||
)
|
||||
declared = {key: value for key, value in rule.items() if key != "unsupported"}
|
||||
if declared != implemented["shape"]:
|
||||
errors.append(
|
||||
f"operand rule {name}: declaration differs from the decoder's implemented rule"
|
||||
)
|
||||
|
||||
|
||||
def _check_xml(form, rule, snapshot, errors):
|
||||
label = form["name"]
|
||||
encoding_name = _family_encoding(form["family"])
|
||||
encoding = snapshot["encodings"].get(encoding_name)
|
||||
if encoding is None:
|
||||
errors.append(f"{label}: family {form['family']} has no XML encoding {encoding_name}")
|
||||
return
|
||||
variant = snapshot["variants"].get((form["name"], encoding_name))
|
||||
if variant is None:
|
||||
errors.append(f"{label}: no default {encoding_name} variant in the XML snapshot")
|
||||
return
|
||||
if variant["opcode"] != form["opcode"]:
|
||||
errors.append(
|
||||
f"{label}: opcode {form['opcode']} disagrees with the XML opcode {variant['opcode']}"
|
||||
)
|
||||
if _identifier(encoding, form["opcode"]) not in encoding["identifiers"]:
|
||||
errors.append(f"{label}: opcode {form['opcode']} is not an identifier of {encoding_name}")
|
||||
operands = {}
|
||||
scc_in = scc_out = False
|
||||
for field, data_format, kind, size, is_input, is_output, _implicit, _encoded in variant["operands"]:
|
||||
if kind == "OPR_SSRC_SPECIAL_SCC":
|
||||
scc_in |= is_input
|
||||
scc_out |= is_output
|
||||
elif field:
|
||||
operands[field] = (data_format, size, is_input, is_output)
|
||||
if scc_in != (form["carry_in"] == "scc"):
|
||||
errors.append(f"{label}: carry_in {form['carry_in']} contradicts the XML SCC input")
|
||||
if scc_out != (form["scc"] != "unchanged"):
|
||||
errors.append(f"{label}: scc {form['scc']} contradicts the XML SCC output")
|
||||
if rule is None:
|
||||
return
|
||||
fields = [(rule["dst"]["field"], False)] + [(src["field"], True) for src in rule["src"]]
|
||||
for field, is_source in fields:
|
||||
if field not in operands:
|
||||
errors.append(f"{label}: XML has no operand {field}")
|
||||
continue
|
||||
data_format, size, is_input, is_output = operands[field]
|
||||
if size != form["width"]:
|
||||
errors.append(f"{label}: {field} is {size} bits in the XML, declared {form['width']}")
|
||||
if (is_input, is_output) != (is_source, not is_source):
|
||||
errors.append(f"{label}: {field} direction disagrees with the XML")
|
||||
signed_format = data_format.startswith("FMT_NUM_I")
|
||||
if is_source and signed_format != (form["signedness"] == "signed"):
|
||||
errors.append(
|
||||
f"{label}: signedness {form['signedness']} contradicts XML format {data_format}"
|
||||
)
|
||||
extra = sorted(set(operands) - {field for field, _ in fields})
|
||||
if extra:
|
||||
errors.append(f"{label}: XML operands {extra} are not covered by rule {form['operands']}")
|
||||
|
||||
|
||||
def _identifier(encoding, opcode):
|
||||
fields = dict((name, ranges) for name, ranges in encoding["fields"])
|
||||
(offset, size), = fields["OP"]
|
||||
base = encoding["identifiers"][0] & ~(((1 << size) - 1) << offset)
|
||||
return base | (opcode << offset)
|
||||
|
||||
|
||||
def validate(registry, snapshot):
|
||||
"""Return every error in the registry; an empty list means it is valid."""
|
||||
errors = []
|
||||
unknown = sorted(set(registry) - TOP_KEYS)
|
||||
if unknown:
|
||||
errors.append(f"unknown top-level keys {unknown}")
|
||||
if type(registry.get("schema")) is not int or registry["schema"] != SCHEMA:
|
||||
errors.append(f"schema {registry.get('schema')!r} is not {SCHEMA}")
|
||||
if registry.get("architecture") != ARCHITECTURE:
|
||||
errors.append(f"architecture {registry.get('architecture')!r} is not {ARCHITECTURE}")
|
||||
if registry.get("source_sha256") != snapshot["source"].get("sha256"):
|
||||
errors.append("source_sha256 does not match the XML snapshot")
|
||||
documents = registry.get("documents", {})
|
||||
for name, document in documents.items():
|
||||
if name not in DOCUMENTS:
|
||||
errors.append(f"unknown document {name}")
|
||||
elif document != PINNED_DOCUMENTS[name]:
|
||||
errors.append(f"document {name}: differs from the pinned public document")
|
||||
if "guide" not in documents:
|
||||
errors.append("the guide document is not declared")
|
||||
rules = registry.get("operand_rules", {})
|
||||
for name, rule in rules.items():
|
||||
_check_rule(name, rule, errors)
|
||||
forms = registry.get("form", [])
|
||||
if not forms:
|
||||
errors.append("the registry declares no forms")
|
||||
seen = {"name": set(), "opcode": set(), "variant": set()}
|
||||
for index, form in enumerate(forms):
|
||||
label = form.get("name", f"form #{index}")
|
||||
missing = sorted(FORM_KEYS - set(form))
|
||||
extra = sorted(set(form) - FORM_KEYS)
|
||||
if missing:
|
||||
errors.append(f"{label}: incomplete, missing {missing}")
|
||||
if extra:
|
||||
errors.append(f"{label}: unknown keys {extra}")
|
||||
if missing:
|
||||
continue
|
||||
for key, vocabulary in (
|
||||
("operation", OPERATIONS), ("signedness", SIGNEDNESS), ("carry_in", CARRY_IN),
|
||||
("scc", SCC), ("vcc", MASK), ("exec", MASK), ("wave", WAVE),
|
||||
):
|
||||
if form[key] not in vocabulary:
|
||||
errors.append(f"{label}: unknown {key} {form[key]!r}")
|
||||
if not isinstance(form["name"], str) or not NAME.match(form["name"]):
|
||||
errors.append(f"{label}: invalid name")
|
||||
if not isinstance(form["variant"], str) or not VARIANT.match(form["variant"]):
|
||||
errors.append(f"{label}: invalid variant {form['variant']!r}")
|
||||
if form["variant"] in RESERVED_VARIANTS:
|
||||
errors.append(f"{label}: variant {form['variant']!r} is reserved")
|
||||
if type(form["opcode"]) is not int or not 0 <= form["opcode"] <= U16_MAX:
|
||||
errors.append(f"{label}: invalid opcode")
|
||||
if form["wave"] in WAVE and form["wave"] not in ENFORCED_WAVES:
|
||||
errors.append(f"{label}: wave {form['wave']} has no decoder enforcement yet")
|
||||
if type(form["width"]) is not int or form["width"] not in WIDTHS:
|
||||
errors.append(f"{label}: width {form['width']} is not supported")
|
||||
for key, value in (
|
||||
("name", form["name"]),
|
||||
("opcode", (form["family"], form["opcode"])),
|
||||
("variant", form["variant"]),
|
||||
):
|
||||
if value in seen[key]:
|
||||
errors.append(f"{label}: duplicate {key} {value}")
|
||||
seen[key].add(value)
|
||||
if (form["signedness"] == "bitwise") != (form["operation"] in LOGICAL):
|
||||
errors.append(
|
||||
f"{label}: signedness {form['signedness']} contradicts operation {form['operation']}"
|
||||
)
|
||||
primitive = PRIMITIVES.get((form["operation"], form["signedness"]))
|
||||
if primitive is None:
|
||||
errors.append(f"{label}: no primitive implements {form['operation']}/{form['signedness']}")
|
||||
else:
|
||||
scc, _, takes_carry = primitive
|
||||
if form["scc"] != scc:
|
||||
errors.append(
|
||||
f"{label}: scc {form['scc']} contradicts {form['operation']}/"
|
||||
f"{form['signedness']} (requires {scc})"
|
||||
)
|
||||
if form["carry_in"] == "scc" and not takes_carry:
|
||||
errors.append(f"{label}: carry_in scc contradicts {form['operation']}/{form['signedness']}")
|
||||
rule = rules.get(form["operands"])
|
||||
if rule is None:
|
||||
errors.append(f"{label}: unknown operand rule {form['operands']!r}")
|
||||
elif rule.get("family") != form["family"]:
|
||||
errors.append(f"{label}: operand rule {form['operands']} is for {rule.get('family')}")
|
||||
_check_spec(label, form["spec"], documents, errors)
|
||||
verify = form["verify"]
|
||||
if not verify:
|
||||
errors.append(f"{label}: no verification requirement")
|
||||
if any(item not in EVIDENCE for item in verify):
|
||||
errors.append(f"{label}: unknown verification requirement in {verify}")
|
||||
if len(set(verify)) != len(verify):
|
||||
errors.append(f"{label}: duplicate verification requirement")
|
||||
_check_xml(form, rule, snapshot, errors)
|
||||
return errors
|
||||
|
||||
|
||||
def _check_spec(label, spec, documents, errors):
|
||||
has_guide = False
|
||||
for ref in spec:
|
||||
if set(ref) != {"document", "section", "page"}:
|
||||
errors.append(f"{label}: spec reference needs exactly document, section, page")
|
||||
continue
|
||||
if ref["document"] not in documents:
|
||||
errors.append(f"{label}: spec cites undeclared document {ref['document']!r}")
|
||||
if not SECTION.match(str(ref["section"])):
|
||||
errors.append(f"{label}: invalid spec section {ref['section']!r}")
|
||||
if type(ref["page"]) is not int or not 0 <= ref["page"] <= U16_MAX:
|
||||
errors.append(f"{label}: invalid spec page")
|
||||
if ref["document"] == "guide" and type(ref["page"]) is int and ref["page"] > 0:
|
||||
has_guide = True
|
||||
if not has_guide:
|
||||
errors.append(f"{label}: missing a guide section and page reference")
|
||||
|
||||
|
||||
def render(registry, snapshot):
|
||||
"""Return the complete generated Rust source. Requires a valid registry."""
|
||||
forms = registry["form"]
|
||||
rule_names = sorted({form["operands"] for form in forms})
|
||||
positions = {form["name"]: position for position, form in enumerate(forms)}
|
||||
out = [
|
||||
"// @generated by crates/isa/generate_semantics.py from crates/isa/semantics/rdna2.toml.",
|
||||
"// Do not edit. Regenerate: python3 crates/isa/generate_semantics.py generate",
|
||||
"",
|
||||
"use crate::meta::EncodingFamily;",
|
||||
"use crate::primitive;",
|
||||
"use crate::semantics::{",
|
||||
" CarryIn, Document, Evidence, FormSemantics, MaskEffect, Operation, OperandRule, SccEffect,",
|
||||
" Signedness, SpecRef, Wave,",
|
||||
"};",
|
||||
"",
|
||||
"/// Registry schema of the generated tables.",
|
||||
f"pub const GENERATED_SCHEMA: u32 = {registry['schema']};",
|
||||
]
|
||||
for rule_name in rule_names:
|
||||
selected = [form for form in forms if form["operands"] == rule_name]
|
||||
out += _render_enum(rule_name, selected, snapshot, positions)
|
||||
out += [
|
||||
"",
|
||||
"/// Identity of every registry form, in registry order.",
|
||||
f"pub const FORM_IDS: [(&str, EncodingFamily); {len(forms)}] = [",
|
||||
]
|
||||
for form in forms:
|
||||
out.append(f" (\"{form['name']}\", EncodingFamily::{_rust_family(form['family'])}),")
|
||||
out += [
|
||||
"];",
|
||||
"",
|
||||
"/// One validated row per registry form, in registry order.",
|
||||
f"pub static FORMS: [FormSemantics; {len(forms)}] = [",
|
||||
]
|
||||
for form in forms:
|
||||
spec = ", ".join(
|
||||
f"SpecRef {{ document: Document::{DOCUMENTS[ref['document']]}, "
|
||||
f"section: \"{ref['section']}\", page: {ref['page']} }}"
|
||||
for ref in form["spec"]
|
||||
)
|
||||
verify = ", ".join(f"Evidence::{EVIDENCE[item]}" for item in form["verify"])
|
||||
out += [
|
||||
" FormSemantics {",
|
||||
f" name: \"{form['name']}\",",
|
||||
f" family: EncodingFamily::{_rust_family(form['family'])},",
|
||||
f" opcode: {form['opcode']},",
|
||||
f" operation: Operation::{OPERATIONS[form['operation']]},",
|
||||
f" signedness: Signedness::{SIGNEDNESS[form['signedness']]},",
|
||||
f" carry_in: CarryIn::{CARRY_IN[form['carry_in']]},",
|
||||
f" width: {form['width']},",
|
||||
f" scc: SccEffect::{SCC[form['scc']]},",
|
||||
f" vcc: MaskEffect::{MASK[form['vcc']]},",
|
||||
f" exec: MaskEffect::{MASK[form['exec']]},",
|
||||
f" wave: Wave::{WAVE[form['wave']]},",
|
||||
f" operands: OperandRule::{OPERAND_RULES[form['operands']]['rust']},",
|
||||
f" spec: &[{spec}],",
|
||||
f" verify: &[{verify}],",
|
||||
" },",
|
||||
]
|
||||
out += ["];", ""]
|
||||
return "\n".join(out)
|
||||
|
||||
|
||||
def _render_enum(rule_name, forms, snapshot, positions):
|
||||
enum = OPERAND_RULES[rule_name]["enum"]
|
||||
family = forms[0]["family"]
|
||||
encoding = snapshot["encodings"][_family_encoding(family)]
|
||||
mask = encoding["identifier_mask"]
|
||||
out = [
|
||||
"",
|
||||
f"/// {family} operations declared in the semantic registry (operand rule `{rule_name}`).",
|
||||
"#[derive(Clone, Copy, Debug, Eq, PartialEq)]",
|
||||
f"pub enum {enum} {{",
|
||||
]
|
||||
for form in forms:
|
||||
carry = " plus SCC" if form["carry_in"] == "scc" else ""
|
||||
out += [
|
||||
f" /// `{form['name'].lower()}` ({family} opcode {form['opcode']}): "
|
||||
f"{form['signedness']} {form['operation']}{carry}, SCC = {form['scc']}.",
|
||||
f" {form['variant']},",
|
||||
]
|
||||
out += [
|
||||
"}",
|
||||
"",
|
||||
f"impl {enum} {{",
|
||||
" /// Every operation, in registry order.",
|
||||
f" pub const ALL: [Self; {len(forms)}] = [",
|
||||
]
|
||||
out += [f" Self::{form['variant']}," for form in forms]
|
||||
out += [
|
||||
" ];",
|
||||
"",
|
||||
f" /// Selects the operation from a first instruction word (mask 0x{mask:09_x}).",
|
||||
" pub const fn from_word(word: u32) -> Option<Self> {",
|
||||
f" match word & 0x{mask:09_x} {{",
|
||||
]
|
||||
for form in sorted(forms, key=lambda item: item["opcode"]):
|
||||
out.append(f" 0x{_identifier(encoding, form['opcode']):09_x} => Some(Self::{form['variant']}),")
|
||||
out += [
|
||||
" _ => None,",
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
" /// Lower-case mnemonic.",
|
||||
" pub const fn mnemonic(self) -> &'static str {",
|
||||
" match self {",
|
||||
]
|
||||
out += [f" Self::{form['variant']} => \"{form['name'].lower()}\"," for form in forms]
|
||||
out += [
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
" /// Whether the operation reads SCC as a carry-in or borrow-in.",
|
||||
" pub const fn reads_scc(self) -> bool {",
|
||||
" match self {",
|
||||
]
|
||||
out += [
|
||||
f" Self::{form['variant']} => {'true' if form['carry_in'] == 'scc' else 'false'},"
|
||||
for form in forms
|
||||
]
|
||||
out += [
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
" /// The validated registry row.",
|
||||
" pub fn semantics(self) -> &'static FormSemantics {",
|
||||
" &FORMS[match self {",
|
||||
]
|
||||
out += [f" Self::{form['variant']} => {positions[form['name']]}," for form in forms]
|
||||
out += [
|
||||
" }]",
|
||||
" }",
|
||||
"",
|
||||
" /// The result and the new SCC, with `carry_in` the SCC read by forms that",
|
||||
" /// consume it (ignored by the others).",
|
||||
" pub const fn evaluate(self, src0: u32, src1: u32, carry_in: bool) -> (u32, bool) {",
|
||||
" match self {",
|
||||
]
|
||||
for form in forms:
|
||||
_, function, takes_carry = PRIMITIVES[(form["operation"], form["signedness"])]
|
||||
if takes_carry:
|
||||
argument = "carry_in" if form["carry_in"] == "scc" else "false"
|
||||
call = f"primitive::{function}(src0, src1, {argument})"
|
||||
else:
|
||||
call = f"primitive::{function}(src0, src1)"
|
||||
out.append(f" Self::{form['variant']} => {call},")
|
||||
out += [" }", " }", "}"]
|
||||
return out
|
||||
|
||||
|
||||
def _display(path):
|
||||
try:
|
||||
return path.resolve().relative_to(ROOT)
|
||||
except ValueError:
|
||||
return path
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
parser.add_argument("mode", nargs="?", choices=("generate", "validate"))
|
||||
parser.add_argument("--check", action="store_true", help="fail if the committed file is stale")
|
||||
parser.add_argument("--registry", type=Path, default=REGISTRY)
|
||||
parser.add_argument("--snapshot", type=Path, default=SNAPSHOT)
|
||||
parser.add_argument("--output", type=Path, default=RUST)
|
||||
arguments = parser.parse_args()
|
||||
if bool(arguments.mode) == arguments.check:
|
||||
parser.error("choose exactly one of generate, validate or --check")
|
||||
registry = load_registry(arguments.registry)
|
||||
snapshot = load_snapshot(arguments.snapshot)
|
||||
errors = validate(registry, snapshot)
|
||||
if errors:
|
||||
for error in errors:
|
||||
print(f"error: {error}", file=sys.stderr)
|
||||
return 1
|
||||
count = len(registry["form"])
|
||||
if arguments.mode == "validate":
|
||||
print(f"registry valid: {count} forms")
|
||||
return 0
|
||||
text = render(registry, snapshot)
|
||||
if arguments.check:
|
||||
current = arguments.output.read_text(encoding="utf-8") if arguments.output.exists() else ""
|
||||
if current != text:
|
||||
print(f"{_display(arguments.output)} is stale; run generate", file=sys.stderr)
|
||||
return 1
|
||||
print(f"registry valid and generated code current: {count} forms")
|
||||
return 0
|
||||
arguments.output.write_text(text, encoding="utf-8")
|
||||
print(f"wrote {_display(arguments.output)}: {count} forms")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,232 @@
|
||||
# Declarative semantic registry for gfx1030 (AMD RDNA 2) instruction forms.
|
||||
#
|
||||
# Data only: no code strings, no expressions. Every value is a member of a closed
|
||||
# vocabulary that crates/isa/generate_semantics.py validates and turns into static
|
||||
# Rust tables (crates/isa/src/semantics_gen.rs). Identity, family, opcode and
|
||||
# operand facts are cross-checked against the pinned AMD XML snapshot
|
||||
# (crates/isa/data/rdna2.jsonl); behaviour comes from the public AMD guide cited
|
||||
# per form, never from the mnemonic. See docs/shaders/semantic-registry.md.
|
||||
#
|
||||
# Independence: the reference interpreter (crates/ref) and the second
|
||||
# interpreter (tests/validation/independent_ref.rs) never read this file.
|
||||
|
||||
schema = 1
|
||||
architecture = "gfx1030"
|
||||
# Must equal the "sha256" of the source line in crates/isa/data/rdna2.jsonl.
|
||||
source_sha256 = "d671ecbc36543674ab59e9b2feffd56718fd2137e7ad913c314f2e2508b9f4f7"
|
||||
|
||||
# Named public documents that spec references point at.
|
||||
[documents.guide]
|
||||
title = "AMD RDNA 2 Instruction Set Architecture Reference Guide"
|
||||
file = "rdna2-shader-instruction-set-architecture.pdf"
|
||||
pages = 291
|
||||
|
||||
[documents.xml]
|
||||
title = "AMD RDNA 2 machine-readable ISA (pinned XML)"
|
||||
file = "amdgpu_isa_rdna2.xml"
|
||||
|
||||
# Operand rules shared by a family. A rule names its destination and source
|
||||
# classes; the decoder implements each rule once (rules are not per opcode).
|
||||
[operand_rules.sop2_sgpr]
|
||||
family = "SOP2"
|
||||
dst = { field = "SDST", class = "sgpr", min = 0, max = 105 }
|
||||
src = [
|
||||
{ field = "SSRC0", class = "scalar_source" },
|
||||
{ field = "SSRC1", class = "scalar_source" },
|
||||
]
|
||||
# scalar_source = normal SGPR s0-s105, inline integer -16..64, or a literal word.
|
||||
max_literals = 1
|
||||
# Encodings this rule rejects, so they stay unsupported rather than guessed.
|
||||
unsupported = [
|
||||
"dst_vcc", "dst_exec", "dst_ttmp", "dst_m0", "dst_null",
|
||||
"src_vcc", "src_exec", "src_m0", "src_ttmp", "src_float_inline",
|
||||
"src_special", "two_literals",
|
||||
]
|
||||
|
||||
# ---- SOP2 32-bit integer and logical forms (migrated from #229/#230) ----
|
||||
# Field meanings:
|
||||
# name XML instruction name (stable identity)
|
||||
# family encoding family; must match the XML base encoding
|
||||
# opcode XML opcode; must match
|
||||
# variant Rust enum variant of the typed op
|
||||
# operation primitive: add | sub | and | or | xor
|
||||
# signedness unsigned | signed | bitwise (bitwise iff a logical operation)
|
||||
# carry_in none | scc (scc only for unsigned add/sub)
|
||||
# width operand and result width in bits
|
||||
# scc carry_out | borrow | signed_overflow | nonzero
|
||||
# vcc, exec unchanged (stated, not implied)
|
||||
# wave any | wave32
|
||||
# operands a key of [operand_rules]
|
||||
# spec references; at least one guide section with a page
|
||||
# verify evidence required before the form counts as verified
|
||||
|
||||
[[form]]
|
||||
name = "S_ADD_U32"
|
||||
family = "SOP2"
|
||||
opcode = 0
|
||||
variant = "AddU32"
|
||||
operation = "add"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "carry_out"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 101 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_SUB_U32"
|
||||
family = "SOP2"
|
||||
opcode = 1
|
||||
variant = "SubU32"
|
||||
operation = "sub"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "borrow"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 101 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_ADD_I32"
|
||||
family = "SOP2"
|
||||
opcode = 2
|
||||
variant = "AddI32"
|
||||
operation = "add"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "signed_overflow"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 101 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_SUB_I32"
|
||||
family = "SOP2"
|
||||
opcode = 3
|
||||
variant = "SubI32"
|
||||
operation = "sub"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "signed_overflow"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 101 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_ADDC_U32"
|
||||
family = "SOP2"
|
||||
opcode = 4
|
||||
variant = "AddcU32"
|
||||
operation = "add"
|
||||
signedness = "unsigned"
|
||||
carry_in = "scc"
|
||||
width = 32
|
||||
scc = "carry_out"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 102 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_SUBB_U32"
|
||||
family = "SOP2"
|
||||
opcode = 5
|
||||
variant = "SubbU32"
|
||||
operation = "sub"
|
||||
signedness = "unsigned"
|
||||
carry_in = "scc"
|
||||
width = 32
|
||||
scc = "borrow"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 102 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_AND_B32"
|
||||
family = "SOP2"
|
||||
opcode = 14
|
||||
variant = "AndB32"
|
||||
operation = "and"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [{ document = "guide", section = "12.1", page = 102 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_OR_B32"
|
||||
family = "SOP2"
|
||||
opcode = 16
|
||||
variant = "OrB32"
|
||||
operation = "or"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [{ document = "guide", section = "12.1", page = 102 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_XOR_B32"
|
||||
family = "SOP2"
|
||||
opcode = 18
|
||||
variant = "XorB32"
|
||||
operation = "xor"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [{ document = "guide", section = "12.1", page = 102 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
+7
-83
@@ -3,18 +3,22 @@
|
||||
use std::fmt;
|
||||
|
||||
pub mod meta;
|
||||
pub mod primitive;
|
||||
mod rdna2;
|
||||
pub mod semantics;
|
||||
#[rustfmt::skip]
|
||||
mod rdna2_meta;
|
||||
#[rustfmt::skip]
|
||||
mod semantics_gen;
|
||||
pub use rdna2::{
|
||||
BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_ADD_I32, S_ADD_U32, S_ADDC_U32,
|
||||
S_AND_B32, S_BRANCH, S_CBRANCH_EXECZ, S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_CMP_EQ_U32, S_ENDPGM,
|
||||
S_MOV_B32, S_OR_B32, S_SUB_I32, S_SUB_U32, S_SUBB_U32, S_WAITCNT, S_WAITCNT_VSCNT, S_XOR_B32,
|
||||
BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_BRANCH, S_CBRANCH_EXECZ,
|
||||
S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_CMP_EQ_U32, S_ENDPGM, S_MOV_B32, S_WAITCNT, S_WAITCNT_VSCNT,
|
||||
V_ADD_F32, V_ADD_NC_U32, V_AND_B32, V_ASHRREV_I32, V_CMP_EQ_I32, V_CMP_EQ_U32, V_CMP_GE_I32,
|
||||
V_CMP_GE_U32, V_CMP_GT_I32, V_CMP_GT_U32, V_CMP_LE_I32, V_CMP_LE_U32, V_CMP_LT_I32,
|
||||
V_CMP_LT_U32, V_CMP_NE_I32, V_CMP_NE_U32, V_INTERP_P1_F32, V_INTERP_P2_F32, V_LSHLREV_B32,
|
||||
V_LSHRREV_B32, V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32,
|
||||
};
|
||||
pub use semantics_gen::ScalarAluOp;
|
||||
|
||||
/// SGPR index of `vcc_lo`, the Wave32 vector condition code.
|
||||
pub const VCC_LO: u8 = 106;
|
||||
@@ -164,86 +168,6 @@ impl VectorCompareOp {
|
||||
}
|
||||
}
|
||||
|
||||
/// SOP2 32-bit integer operations in the supported scalar subset.
|
||||
///
|
||||
/// SCC behaviour follows the pinned AMD RDNA 2 XML descriptions: additions
|
||||
/// store the carry-out, subtractions the borrow, ADDC and SUBB also consume
|
||||
/// SCC as carry-in or borrow-in, signed forms store signed overflow (RDNA 2 ISA
|
||||
/// guide 12.1), and bitwise operations set SCC iff the result is nonzero. See
|
||||
/// docs/shaders/scalar-alu.md for the sources.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum ScalarAluOp {
|
||||
/// `s_add_u32`: D = S0 + S1, SCC = carry-out.
|
||||
AddU32,
|
||||
/// `s_sub_u32`: D = S0 - S1, SCC = borrow (S1 > S0).
|
||||
SubU32,
|
||||
/// `s_add_i32`: D = S0 + S1, SCC = signed overflow.
|
||||
AddI32,
|
||||
/// `s_sub_i32`: D = S0 - S1, SCC = signed overflow.
|
||||
SubI32,
|
||||
/// `s_addc_u32`: D = S0 + S1 + SCC, SCC = carry-out.
|
||||
AddcU32,
|
||||
/// `s_subb_u32`: D = S0 - S1 - SCC, SCC = borrow.
|
||||
SubbU32,
|
||||
/// `s_and_b32`: D = S0 & S1, SCC = D != 0.
|
||||
AndB32,
|
||||
/// `s_or_b32`: D = S0 | S1, SCC = D != 0.
|
||||
OrB32,
|
||||
/// `s_xor_b32`: D = S0 ^ S1, SCC = D != 0.
|
||||
XorB32,
|
||||
}
|
||||
|
||||
impl ScalarAluOp {
|
||||
/// Lower-case mnemonic.
|
||||
pub fn mnemonic(self) -> &'static str {
|
||||
match self {
|
||||
Self::AddU32 => "s_add_u32",
|
||||
Self::SubU32 => "s_sub_u32",
|
||||
Self::AddI32 => "s_add_i32",
|
||||
Self::SubI32 => "s_sub_i32",
|
||||
Self::AddcU32 => "s_addc_u32",
|
||||
Self::SubbU32 => "s_subb_u32",
|
||||
Self::AndB32 => "s_and_b32",
|
||||
Self::OrB32 => "s_or_b32",
|
||||
Self::XorB32 => "s_xor_b32",
|
||||
}
|
||||
}
|
||||
|
||||
/// The 32-bit result and the new SCC, with `carry_in` the SCC read by
|
||||
/// ADDC and SUBB (ignored by the other operations).
|
||||
pub fn evaluate(self, src0: u32, src1: u32, carry_in: bool) -> (u32, bool) {
|
||||
let carry = u32::from(carry_in && self.reads_scc());
|
||||
match self {
|
||||
Self::AddU32 | Self::AddcU32 => {
|
||||
let (partial, first) = src0.overflowing_add(src1);
|
||||
let (value, second) = partial.overflowing_add(carry);
|
||||
(value, first || second)
|
||||
}
|
||||
Self::SubU32 | Self::SubbU32 => {
|
||||
let (partial, first) = src0.overflowing_sub(src1);
|
||||
let (value, second) = partial.overflowing_sub(carry);
|
||||
(value, first || second)
|
||||
}
|
||||
Self::AddI32 => {
|
||||
let (value, overflow) = (src0 as i32).overflowing_add(src1 as i32);
|
||||
(value as u32, overflow)
|
||||
}
|
||||
Self::SubI32 => {
|
||||
let (value, overflow) = (src0 as i32).overflowing_sub(src1 as i32);
|
||||
(value as u32, overflow)
|
||||
}
|
||||
Self::AndB32 => (src0 & src1, src0 & src1 != 0),
|
||||
Self::OrB32 => (src0 | src1, src0 | src1 != 0),
|
||||
Self::XorB32 => (src0 ^ src1, src0 ^ src1 != 0),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the operation reads SCC as a carry-in or borrow-in.
|
||||
pub fn reads_scc(self) -> bool {
|
||||
matches!(self, Self::AddcU32 | Self::SubbU32)
|
||||
}
|
||||
}
|
||||
|
||||
/// Output targeted by a supported uncompressed four-component export.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum ExportTarget {
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
//! Reusable integer semantic primitives selected by the generated registry dispatch.
|
||||
//!
|
||||
//! Each function implements one closed [`crate::semantics::Operation`] at one
|
||||
//! signedness, with the condition-code rule the RDNA 2 guide gives for it
|
||||
//! (section 5.3, "Scalar Condition Code", and the SOP2 pseudocode in 12.1).
|
||||
//! Forms share a primitive only when their declared operation, signedness and
|
||||
//! SCC effect are identical; the generator never selects one by mnemonic.
|
||||
|
||||
/// Unsigned `a + b + carry_in` and the carry-out of bit 31.
|
||||
pub const fn add_carry_u32(a: u32, b: u32, carry_in: bool) -> (u32, bool) {
|
||||
let (partial, first) = a.overflowing_add(b);
|
||||
let (value, second) = partial.overflowing_add(carry_in as u32);
|
||||
(value, first || second)
|
||||
}
|
||||
|
||||
/// Unsigned `a - b - borrow_in` and the borrow (`b + borrow_in > a`).
|
||||
pub const fn sub_borrow_u32(a: u32, b: u32, borrow_in: bool) -> (u32, bool) {
|
||||
let (partial, first) = a.overflowing_sub(b);
|
||||
let (value, second) = partial.overflowing_sub(borrow_in as u32);
|
||||
(value, first || second)
|
||||
}
|
||||
|
||||
/// Two's-complement `a + b` and whether the exact sum leaves the i32 range.
|
||||
pub const fn add_overflow_i32(a: u32, b: u32) -> (u32, bool) {
|
||||
let (value, overflow) = (a as i32).overflowing_add(b as i32);
|
||||
(value as u32, overflow)
|
||||
}
|
||||
|
||||
/// Two's-complement `a - b` and whether the exact difference leaves the i32 range.
|
||||
pub const fn sub_overflow_i32(a: u32, b: u32) -> (u32, bool) {
|
||||
let (value, overflow) = (a as i32).overflowing_sub(b as i32);
|
||||
(value as u32, overflow)
|
||||
}
|
||||
|
||||
/// Bitwise AND and whether the result is nonzero.
|
||||
pub const fn and_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
|
||||
let value = a & b;
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Bitwise OR and whether the result is nonzero.
|
||||
pub const fn or_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
|
||||
let value = a | b;
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Bitwise XOR and whether the result is nonzero.
|
||||
pub const fn xor_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
|
||||
let value = a ^ b;
|
||||
(value, value != 0)
|
||||
}
|
||||
@@ -50,51 +50,6 @@ pub const S_CMP_EQ_U32: Opcode = Opcode {
|
||||
bits: 0xbf060000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const S_ADD_U32: Opcode = Opcode {
|
||||
mask: 0xff800000,
|
||||
bits: 0x80000000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const S_SUB_U32: Opcode = Opcode {
|
||||
mask: 0xff800000,
|
||||
bits: 0x80800000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const S_ADD_I32: Opcode = Opcode {
|
||||
mask: 0xff800000,
|
||||
bits: 0x81000000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const S_SUB_I32: Opcode = Opcode {
|
||||
mask: 0xff800000,
|
||||
bits: 0x81800000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const S_ADDC_U32: Opcode = Opcode {
|
||||
mask: 0xff800000,
|
||||
bits: 0x82000000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const S_SUBB_U32: Opcode = Opcode {
|
||||
mask: 0xff800000,
|
||||
bits: 0x82800000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const S_AND_B32: Opcode = Opcode {
|
||||
mask: 0xff800000,
|
||||
bits: 0x87000000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const S_OR_B32: Opcode = Opcode {
|
||||
mask: 0xff800000,
|
||||
bits: 0x88000000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const S_XOR_B32: Opcode = Opcode {
|
||||
mask: 0xff800000,
|
||||
bits: 0x89000000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const S_CBRANCH_SCC0: Opcode = Opcode {
|
||||
mask: 0xffff0000,
|
||||
bits: 0xbf840000,
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
//! Typed vocabulary of the declarative semantic registry (`crates/isa/semantics/rdna2.toml`).
|
||||
//!
|
||||
//! The registry is data. `crates/isa/generate_semantics.py` validates it against
|
||||
//! this closed vocabulary and the pinned AMD XML snapshot, then emits
|
||||
//! `semantics_gen.rs`: the typed operation enums, their opcode dispatch and one
|
||||
//! static [`FormSemantics`] row per form. Nothing here interprets metadata at run
|
||||
//! time; the decoder and translator call the generated `const fn`s and `match`es.
|
||||
//!
|
||||
//! The reference interpreter (`crates/ref`) and the independent interpreter
|
||||
//! (`tests/validation/independent_ref.rs`) must not use this module.
|
||||
|
||||
use crate::meta::EncodingFamily;
|
||||
|
||||
pub use crate::semantics_gen::{FORM_IDS, FORMS, GENERATED_SCHEMA};
|
||||
|
||||
/// Version of the registry schema this crate was generated against.
|
||||
pub const SCHEMA: u32 = 1;
|
||||
|
||||
/// Reusable semantic primitive selected by a form. Closed: the generator rejects
|
||||
/// any other name, and each primitive has one implementation in `primitive.rs`.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum Operation {
|
||||
/// Integer addition.
|
||||
Add,
|
||||
/// Integer subtraction.
|
||||
Sub,
|
||||
/// Bitwise AND.
|
||||
And,
|
||||
/// Bitwise OR.
|
||||
Or,
|
||||
/// Bitwise exclusive OR.
|
||||
Xor,
|
||||
}
|
||||
|
||||
/// How the operands are interpreted. `Bitwise` exactly when the operation is logical.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum Signedness {
|
||||
/// Unsigned integers.
|
||||
Unsigned,
|
||||
/// Two's-complement integers.
|
||||
Signed,
|
||||
/// Untyped bits.
|
||||
Bitwise,
|
||||
}
|
||||
|
||||
/// Extra input consumed by the operation.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum CarryIn {
|
||||
/// No carry or borrow input.
|
||||
None,
|
||||
/// SCC as carry-in (add) or borrow-in (sub).
|
||||
Scc,
|
||||
}
|
||||
|
||||
/// What a form writes to SCC.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum SccEffect {
|
||||
/// SCC is not written.
|
||||
Unchanged,
|
||||
/// Unsigned carry-out of the top bit.
|
||||
CarryOut,
|
||||
/// Unsigned borrow (subtrahend plus borrow-in exceeds the minuend).
|
||||
Borrow,
|
||||
/// Two's-complement overflow of the exact result.
|
||||
SignedOverflow,
|
||||
/// The result is not zero.
|
||||
Nonzero,
|
||||
}
|
||||
|
||||
/// What a form writes to VCC or EXEC. Stage A forms leave both unchanged.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum MaskEffect {
|
||||
/// Not written.
|
||||
Unchanged,
|
||||
}
|
||||
|
||||
/// Wave-size restriction.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum Wave {
|
||||
/// Behaviour does not depend on the wave size.
|
||||
Any,
|
||||
/// Only Wave32 behaviour is declared; Wave64 stays unsupported.
|
||||
Wave32,
|
||||
}
|
||||
|
||||
/// Shared operand rule. The decoder implements each rule once.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum OperandRule {
|
||||
/// SOP2: SDST is s0-s105; SSRC0/SSRC1 are s0-s105, inline integers -16..64
|
||||
/// or one literal word. Everything else is rejected as unsupported.
|
||||
Sop2Sgpr,
|
||||
}
|
||||
|
||||
/// Evidence a form needs before it counts as verified.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum Evidence {
|
||||
/// `crates/ref` lockstep reference.
|
||||
Reference,
|
||||
/// `tests/validation/independent_ref.rs`.
|
||||
Independent,
|
||||
/// Native Metal known-answer runs.
|
||||
Metal,
|
||||
/// LLVM assembler/disassembler encoding agreement.
|
||||
LlvmEncoding,
|
||||
}
|
||||
|
||||
/// Public document a [`SpecRef`] points at.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum Document {
|
||||
/// AMD RDNA 2 ISA reference guide (PDF).
|
||||
Guide,
|
||||
/// Pinned AMD machine-readable XML.
|
||||
Xml,
|
||||
}
|
||||
|
||||
/// One public specification reference.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct SpecRef {
|
||||
/// Source document.
|
||||
pub document: Document,
|
||||
/// Section number, for example `"12.1"`.
|
||||
pub section: &'static str,
|
||||
/// Page in the document, 0 when not paginated.
|
||||
pub page: u16,
|
||||
}
|
||||
|
||||
/// One validated registry row, emitted as a static table by the generator.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct FormSemantics {
|
||||
/// XML instruction name, the stable form identity.
|
||||
pub name: &'static str,
|
||||
/// Encoding family (matches [`crate::meta::FORMS`]).
|
||||
pub family: EncodingFamily,
|
||||
/// Opcode within the family.
|
||||
pub opcode: u16,
|
||||
/// Primitive.
|
||||
pub operation: Operation,
|
||||
/// Operand interpretation.
|
||||
pub signedness: Signedness,
|
||||
/// Carry or borrow input.
|
||||
pub carry_in: CarryIn,
|
||||
/// Operand and result width in bits.
|
||||
pub width: u8,
|
||||
/// SCC write.
|
||||
pub scc: SccEffect,
|
||||
/// VCC write.
|
||||
pub vcc: MaskEffect,
|
||||
/// EXEC write.
|
||||
pub exec: MaskEffect,
|
||||
/// Wave-size restriction.
|
||||
pub wave: Wave,
|
||||
/// Operand rule.
|
||||
pub operands: OperandRule,
|
||||
/// Public references.
|
||||
pub spec: &'static [SpecRef],
|
||||
/// Required evidence.
|
||||
pub verify: &'static [Evidence],
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
// @generated by crates/isa/generate_semantics.py from crates/isa/semantics/rdna2.toml.
|
||||
// Do not edit. Regenerate: python3 crates/isa/generate_semantics.py generate
|
||||
|
||||
use crate::meta::EncodingFamily;
|
||||
use crate::primitive;
|
||||
use crate::semantics::{
|
||||
CarryIn, Document, Evidence, FormSemantics, MaskEffect, Operation, OperandRule, SccEffect,
|
||||
Signedness, SpecRef, Wave,
|
||||
};
|
||||
|
||||
/// Registry schema of the generated tables.
|
||||
pub const GENERATED_SCHEMA: u32 = 1;
|
||||
|
||||
/// SOP2 operations declared in the semantic registry (operand rule `sop2_sgpr`).
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum ScalarAluOp {
|
||||
/// `s_add_u32` (SOP2 opcode 0): unsigned add, SCC = carry_out.
|
||||
AddU32,
|
||||
/// `s_sub_u32` (SOP2 opcode 1): unsigned sub, SCC = borrow.
|
||||
SubU32,
|
||||
/// `s_add_i32` (SOP2 opcode 2): signed add, SCC = signed_overflow.
|
||||
AddI32,
|
||||
/// `s_sub_i32` (SOP2 opcode 3): signed sub, SCC = signed_overflow.
|
||||
SubI32,
|
||||
/// `s_addc_u32` (SOP2 opcode 4): unsigned add plus SCC, SCC = carry_out.
|
||||
AddcU32,
|
||||
/// `s_subb_u32` (SOP2 opcode 5): unsigned sub plus SCC, SCC = borrow.
|
||||
SubbU32,
|
||||
/// `s_and_b32` (SOP2 opcode 14): bitwise and, SCC = nonzero.
|
||||
AndB32,
|
||||
/// `s_or_b32` (SOP2 opcode 16): bitwise or, SCC = nonzero.
|
||||
OrB32,
|
||||
/// `s_xor_b32` (SOP2 opcode 18): bitwise xor, SCC = nonzero.
|
||||
XorB32,
|
||||
}
|
||||
|
||||
impl ScalarAluOp {
|
||||
/// Every operation, in registry order.
|
||||
pub const ALL: [Self; 9] = [
|
||||
Self::AddU32,
|
||||
Self::SubU32,
|
||||
Self::AddI32,
|
||||
Self::SubI32,
|
||||
Self::AddcU32,
|
||||
Self::SubbU32,
|
||||
Self::AndB32,
|
||||
Self::OrB32,
|
||||
Self::XorB32,
|
||||
];
|
||||
|
||||
/// Selects the operation from a first instruction word (mask 0xff80_0000).
|
||||
pub const fn from_word(word: u32) -> Option<Self> {
|
||||
match word & 0xff80_0000 {
|
||||
0x8000_0000 => Some(Self::AddU32),
|
||||
0x8080_0000 => Some(Self::SubU32),
|
||||
0x8100_0000 => Some(Self::AddI32),
|
||||
0x8180_0000 => Some(Self::SubI32),
|
||||
0x8200_0000 => Some(Self::AddcU32),
|
||||
0x8280_0000 => Some(Self::SubbU32),
|
||||
0x8700_0000 => Some(Self::AndB32),
|
||||
0x8800_0000 => Some(Self::OrB32),
|
||||
0x8900_0000 => Some(Self::XorB32),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Lower-case mnemonic.
|
||||
pub const fn mnemonic(self) -> &'static str {
|
||||
match self {
|
||||
Self::AddU32 => "s_add_u32",
|
||||
Self::SubU32 => "s_sub_u32",
|
||||
Self::AddI32 => "s_add_i32",
|
||||
Self::SubI32 => "s_sub_i32",
|
||||
Self::AddcU32 => "s_addc_u32",
|
||||
Self::SubbU32 => "s_subb_u32",
|
||||
Self::AndB32 => "s_and_b32",
|
||||
Self::OrB32 => "s_or_b32",
|
||||
Self::XorB32 => "s_xor_b32",
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the operation reads SCC as a carry-in or borrow-in.
|
||||
pub const fn reads_scc(self) -> bool {
|
||||
match self {
|
||||
Self::AddU32 => false,
|
||||
Self::SubU32 => false,
|
||||
Self::AddI32 => false,
|
||||
Self::SubI32 => false,
|
||||
Self::AddcU32 => true,
|
||||
Self::SubbU32 => true,
|
||||
Self::AndB32 => false,
|
||||
Self::OrB32 => false,
|
||||
Self::XorB32 => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The validated registry row.
|
||||
pub fn semantics(self) -> &'static FormSemantics {
|
||||
&FORMS[match self {
|
||||
Self::AddU32 => 0,
|
||||
Self::SubU32 => 1,
|
||||
Self::AddI32 => 2,
|
||||
Self::SubI32 => 3,
|
||||
Self::AddcU32 => 4,
|
||||
Self::SubbU32 => 5,
|
||||
Self::AndB32 => 6,
|
||||
Self::OrB32 => 7,
|
||||
Self::XorB32 => 8,
|
||||
}]
|
||||
}
|
||||
|
||||
/// The result and the new SCC, with `carry_in` the SCC read by forms that
|
||||
/// consume it (ignored by the others).
|
||||
pub const fn evaluate(self, src0: u32, src1: u32, carry_in: bool) -> (u32, bool) {
|
||||
match self {
|
||||
Self::AddU32 => primitive::add_carry_u32(src0, src1, false),
|
||||
Self::SubU32 => primitive::sub_borrow_u32(src0, src1, false),
|
||||
Self::AddI32 => primitive::add_overflow_i32(src0, src1),
|
||||
Self::SubI32 => primitive::sub_overflow_i32(src0, src1),
|
||||
Self::AddcU32 => primitive::add_carry_u32(src0, src1, carry_in),
|
||||
Self::SubbU32 => primitive::sub_borrow_u32(src0, src1, carry_in),
|
||||
Self::AndB32 => primitive::and_nonzero_b32(src0, src1),
|
||||
Self::OrB32 => primitive::or_nonzero_b32(src0, src1),
|
||||
Self::XorB32 => primitive::xor_nonzero_b32(src0, src1),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Identity of every registry form, in registry order.
|
||||
pub const FORM_IDS: [(&str, EncodingFamily); 9] = [
|
||||
("S_ADD_U32", EncodingFamily::Sop2),
|
||||
("S_SUB_U32", EncodingFamily::Sop2),
|
||||
("S_ADD_I32", EncodingFamily::Sop2),
|
||||
("S_SUB_I32", EncodingFamily::Sop2),
|
||||
("S_ADDC_U32", EncodingFamily::Sop2),
|
||||
("S_SUBB_U32", EncodingFamily::Sop2),
|
||||
("S_AND_B32", EncodingFamily::Sop2),
|
||||
("S_OR_B32", EncodingFamily::Sop2),
|
||||
("S_XOR_B32", EncodingFamily::Sop2),
|
||||
];
|
||||
|
||||
/// One validated row per registry form, in registry order.
|
||||
pub static FORMS: [FormSemantics; 9] = [
|
||||
FormSemantics {
|
||||
name: "S_ADD_U32",
|
||||
family: EncodingFamily::Sop2,
|
||||
opcode: 0,
|
||||
operation: Operation::Add,
|
||||
signedness: Signedness::Unsigned,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
scc: SccEffect::CarryOut,
|
||||
vcc: MaskEffect::Unchanged,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Any,
|
||||
operands: OperandRule::Sop2Sgpr,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 101 }, SpecRef { document: Document::Guide, section: "5.3", page: 33 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "S_SUB_U32",
|
||||
family: EncodingFamily::Sop2,
|
||||
opcode: 1,
|
||||
operation: Operation::Sub,
|
||||
signedness: Signedness::Unsigned,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
scc: SccEffect::Borrow,
|
||||
vcc: MaskEffect::Unchanged,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Any,
|
||||
operands: OperandRule::Sop2Sgpr,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 101 }, SpecRef { document: Document::Guide, section: "5.3", page: 33 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "S_ADD_I32",
|
||||
family: EncodingFamily::Sop2,
|
||||
opcode: 2,
|
||||
operation: Operation::Add,
|
||||
signedness: Signedness::Signed,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
scc: SccEffect::SignedOverflow,
|
||||
vcc: MaskEffect::Unchanged,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Any,
|
||||
operands: OperandRule::Sop2Sgpr,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 101 }, SpecRef { document: Document::Guide, section: "5.3", page: 33 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "S_SUB_I32",
|
||||
family: EncodingFamily::Sop2,
|
||||
opcode: 3,
|
||||
operation: Operation::Sub,
|
||||
signedness: Signedness::Signed,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
scc: SccEffect::SignedOverflow,
|
||||
vcc: MaskEffect::Unchanged,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Any,
|
||||
operands: OperandRule::Sop2Sgpr,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 101 }, SpecRef { document: Document::Guide, section: "5.3", page: 33 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "S_ADDC_U32",
|
||||
family: EncodingFamily::Sop2,
|
||||
opcode: 4,
|
||||
operation: Operation::Add,
|
||||
signedness: Signedness::Unsigned,
|
||||
carry_in: CarryIn::Scc,
|
||||
width: 32,
|
||||
scc: SccEffect::CarryOut,
|
||||
vcc: MaskEffect::Unchanged,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Any,
|
||||
operands: OperandRule::Sop2Sgpr,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 102 }, SpecRef { document: Document::Guide, section: "5.3", page: 33 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "S_SUBB_U32",
|
||||
family: EncodingFamily::Sop2,
|
||||
opcode: 5,
|
||||
operation: Operation::Sub,
|
||||
signedness: Signedness::Unsigned,
|
||||
carry_in: CarryIn::Scc,
|
||||
width: 32,
|
||||
scc: SccEffect::Borrow,
|
||||
vcc: MaskEffect::Unchanged,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Any,
|
||||
operands: OperandRule::Sop2Sgpr,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 102 }, SpecRef { document: Document::Guide, section: "5.3", page: 33 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "S_AND_B32",
|
||||
family: EncodingFamily::Sop2,
|
||||
opcode: 14,
|
||||
operation: Operation::And,
|
||||
signedness: Signedness::Bitwise,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
scc: SccEffect::Nonzero,
|
||||
vcc: MaskEffect::Unchanged,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Any,
|
||||
operands: OperandRule::Sop2Sgpr,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 102 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "S_OR_B32",
|
||||
family: EncodingFamily::Sop2,
|
||||
opcode: 16,
|
||||
operation: Operation::Or,
|
||||
signedness: Signedness::Bitwise,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
scc: SccEffect::Nonzero,
|
||||
vcc: MaskEffect::Unchanged,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Any,
|
||||
operands: OperandRule::Sop2Sgpr,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 102 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "S_XOR_B32",
|
||||
family: EncodingFamily::Sop2,
|
||||
opcode: 18,
|
||||
operation: Operation::Xor,
|
||||
signedness: Signedness::Bitwise,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
scc: SccEffect::Nonzero,
|
||||
vcc: MaskEffect::Unchanged,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Any,
|
||||
operands: OperandRule::Sop2Sgpr,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 102 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,60 @@
|
||||
//! Ties the generated semantic registry tables to the independent XML metadata table.
|
||||
|
||||
use xenora_isa::ScalarAluOp;
|
||||
use xenora_isa::meta::{EncodingFamily, FORMS as META_FORMS};
|
||||
use xenora_isa::semantics::{CarryIn, FORM_IDS, FORMS, GENERATED_SCHEMA, SCHEMA};
|
||||
|
||||
#[test]
|
||||
fn generated_tables_match_the_schema_and_the_metadata_forms() {
|
||||
assert_eq!(GENERATED_SCHEMA, SCHEMA);
|
||||
assert_eq!(FORM_IDS.len(), FORMS.len());
|
||||
for (row, (name, family)) in FORMS.iter().zip(FORM_IDS) {
|
||||
assert_eq!((row.name, row.family), (name, family));
|
||||
let meta = META_FORMS
|
||||
.iter()
|
||||
.find(|form| form.name == row.name && form.family == row.family)
|
||||
.unwrap_or_else(|| panic!("{} is not an identified form", row.name));
|
||||
assert_eq!(meta.opcode, row.opcode, "{}", row.name);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_alu_dispatch_selects_exactly_the_registry_sop2_forms() {
|
||||
assert_eq!(ScalarAluOp::ALL.len(), FORMS.len());
|
||||
for op in ScalarAluOp::ALL {
|
||||
let row = op.semantics();
|
||||
assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic());
|
||||
assert_eq!(op.reads_scc(), row.carry_in == CarryIn::Scc);
|
||||
}
|
||||
let mut selected = 0;
|
||||
for meta in META_FORMS
|
||||
.iter()
|
||||
.filter(|form| form.family == EncodingFamily::Sop2)
|
||||
{
|
||||
let word = meta.bits as u32;
|
||||
match ScalarAluOp::from_word(word) {
|
||||
Some(op) => {
|
||||
assert_eq!(op.semantics().name, meta.name);
|
||||
selected += 1;
|
||||
}
|
||||
None => assert!(
|
||||
FORMS.iter().all(|row| row.name != meta.name),
|
||||
"{} is declared but not dispatched",
|
||||
meta.name
|
||||
),
|
||||
}
|
||||
}
|
||||
assert_eq!(selected, FORMS.len());
|
||||
// Other encodings never reach the SOP2 dispatch.
|
||||
for meta in META_FORMS
|
||||
.iter()
|
||||
.filter(|form| form.family != EncodingFamily::Sop2 && form.bytes == 4)
|
||||
{
|
||||
assert_eq!(
|
||||
ScalarAluOp::from_word(meta.bits as u32),
|
||||
None,
|
||||
"{}",
|
||||
meta.name
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -22,7 +22,9 @@ either path. The [changelog](../CHANGELOG.md) records notable changes.
|
||||
## RDNA 2 decoding and shader translation
|
||||
|
||||
- [Instruction coverage](shaders/instruction-coverage.md) — Desktop gfx1030 instruction forms, operand limits, and CPU and GPU results.
|
||||
- [Semantic coverage](shaders/semantic-coverage.md) — Generated per-family counts of identified, declared, decoded, lowered and verified gfx1030 forms.
|
||||
- [SOP2 scalar ALU](shaders/scalar-alu.md) — Supported scalar add, subtract and bitwise forms, their SCC rules and sources.
|
||||
- [Semantic registry](shaders/semantic-registry.md) — How to add an instruction form: registry fields, validation, generation and the independence rule.
|
||||
- [VOPC integer compares](shaders/vector-compare.md) — Wave32 compare forms, the VCC/EXEC contract, runtime `s_cbranch_vccz` and the Metal mapping.
|
||||
- [Metal Shading Language generation](shaders/msl.md) and [independent CPU reference](shaders/reference-interpreter.md) — Translation rules and separate CPU execution models.
|
||||
|
||||
|
||||
@@ -16,6 +16,18 @@ operands, writes a normal SGPR (s0-s105) and sets SCC.
|
||||
| `s_xor_b32` | S0 ^ S1 | D != 0 |
|
||||
|
||||
Sources are normal SGPRs, inline integers (-16 to 64) or one literal word.
|
||||
|
||||
These nine forms are declared as data in the semantic registry,
|
||||
`crates/isa/semantics/rdna2.toml`: opcode, operation, signedness, carry-in,
|
||||
SCC effect, operand rule and guide references. `crates/isa/generate_semantics.py`
|
||||
checks each declaration against the pinned AMD XML snapshot and rejects
|
||||
contradictions (for example a carry-in on a bitwise form, or a signed form whose
|
||||
SCC is a carry). It then generates `crates/isa/src/semantics_gen.rs`, which holds
|
||||
the decoder's opcode dispatch and `ScalarAluOp`'s mnemonic, SCC read and
|
||||
evaluation through the shared primitives in `crates/isa/src/primitive.rs`. Run
|
||||
`python3 crates/isa/generate_semantics.py validate`, `generate` or `--check`
|
||||
(Python 3.11 or newer). The reference and independent interpreters do not use
|
||||
the registry.
|
||||
`v_mov_b32_e32` may read a normal SGPR, so the results can reach vector code.
|
||||
|
||||
## Sources
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
# gfx1030 semantic coverage
|
||||
|
||||
<!-- Generated by scripts/audit/semantic_coverage.py. -->
|
||||
|
||||
Identified forms come from the AMD RDNA 2 instruction snapshot. Declared forms
|
||||
come from the semantic registry. Decoder support is the decoder's hand-written
|
||||
list plus the registry forms compiled into crates/isa/src/semantics_gen.rs.
|
||||
|
||||
The status inventory records LLVM three-way encoding checks, intermediate
|
||||
representation (IR) and Metal Shading Language (MSL) lowering, and fixture
|
||||
verification. IR and MSL share the inventory's lowering field. Reference
|
||||
verification requires an implemented reference and verified CPU fixture.
|
||||
Metal verification requires a verified GPU fixture. Both also require a decoding row. Local readbacks pending
|
||||
acceptance remain outside the verified count. All results concern synthetic fixtures.
|
||||
|
||||
| Family | Identified | Encoding-validated | Declared | Decoder-supported | IR | MSL | Reference-verified | Metal-verified | Unsupported operand variants |
|
||||
| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
|
||||
| DS | 123 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||
| EXP | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 |
|
||||
| FLAT | 54 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||
| GLOBAL | 57 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||
| MIMG | 130 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 |
|
||||
| MTBUF | 16 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||
| MUBUF | 75 | 2 | 0 | 2 | 2 | 2 | 2 | 2 | 0 |
|
||||
| SCRATCH | 22 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||
| SMEM | 14 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||
| SOP1 | 65 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 |
|
||||
| SOP2 | 51 | 9 | 9 | 9 | 9 | 9 | 0 | 0 | 12 |
|
||||
| SOPC | 18 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 |
|
||||
| SOPK | 27 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 |
|
||||
| SOPP | 36 | 6 | 0 | 6 | 6 | 6 | 4 | 4 | 0 |
|
||||
| VINTRP | 3 | 0 | 0 | 2 | 0 | 0 | 0 | 0 | 0 |
|
||||
| VOP1 | 81 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 |
|
||||
| VOP2 | 47 | 8 | 0 | 8 | 8 | 8 | 7 | 7 | 0 |
|
||||
| VOP3 | 416 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 |
|
||||
| VOP3P | 29 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||
| VOP3SDST | 10 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||
| VOPC | 190 | 12 | 0 | 12 | 12 | 12 | 0 | 0 | 0 |
|
||||
| **Total** | 1465 | 42 | 9 | 46 | 42 | 42 | 18 | 18 | 12 |
|
||||
|
||||
## Unsupported operand variants
|
||||
|
||||
The table counts distinct variant names per family across registry operand rules.
|
||||
|
||||
| Family | Operand rule | Unsupported variants |
|
||||
| --- | --- | --- |
|
||||
| SOP2 | `sop2_sgpr` | `dst_exec`, `dst_m0`, `dst_null`, `dst_ttmp`, `dst_vcc`, `src_exec`, `src_float_inline`, `src_m0`, `src_special`, `src_ttmp`, `src_vcc`, `two_literals` |
|
||||
@@ -0,0 +1,214 @@
|
||||
# Adding an instruction through the semantic registry
|
||||
|
||||
The semantic registry is a data file that declares what each supported gfx1030
|
||||
instruction form does. A generator checks it and turns it into Rust tables that
|
||||
the decoder uses. This page explains where entries live, what each field means,
|
||||
how to check and regenerate the tables, and what the generator does not do for
|
||||
you.
|
||||
|
||||
The registry covers the nine SOP2 forms listed in [SOP2 scalar ALU](scalar-alu.md).
|
||||
|
||||
## Files
|
||||
|
||||
| File | Role |
|
||||
| --- | --- |
|
||||
| `crates/isa/semantics/rdna2.toml` | The registry. Data only: every value comes from a closed vocabulary. |
|
||||
| `crates/isa/generate_semantics.py` | Validates the registry and writes the Rust tables. Python 3.11 or newer, standard library only. |
|
||||
| `crates/isa/data/rdna2.jsonl` | Pinned snapshot of the AMD machine-readable ISA XML, used to cross-check identity and operands. |
|
||||
| `crates/isa/src/semantics_gen.rs` | Generated output. Never edit it by hand. |
|
||||
| `crates/isa/src/semantics.rs` | The Rust types the generated tables use (`FormSemantics`, `Operation`, `SccEffect` and so on). |
|
||||
| `crates/isa/src/primitive.rs` | The shared integer primitives that the generated `evaluate` calls. |
|
||||
| `tests/semantics_generator/` | Unit tests for the generator. |
|
||||
|
||||
## Fields
|
||||
|
||||
The top of the file holds:
|
||||
|
||||
- `schema`: must be `1`.
|
||||
- `architecture`: must be `"gfx1030"`.
|
||||
- `source_sha256`: must equal the `sha256` on the `source` line of
|
||||
`crates/isa/data/rdna2.jsonl`, so the registry is always checked against the
|
||||
snapshot it was written for.
|
||||
- `[documents.<name>]`: the public documents that spec references cite. Only
|
||||
`guide` (the AMD RDNA 2 ISA reference guide) and `xml` (the AMD
|
||||
machine-readable ISA) are allowed, and each must match the title and file
|
||||
pinned in the generator, so a citation cannot point at another file.
|
||||
- `[operand_rules.<name>]`: an operand rule shared by a whole family. The
|
||||
decoder implements each rule once, and the generator only accepts a rule
|
||||
whose declaration matches the decoder's implementation exactly. Today there
|
||||
is one rule, `sop2_sgpr`: an SGPR destination `s0`-`s105`, two scalar sources
|
||||
(an SGPR, an inline integer -16 to 64, or a literal word) and at most one
|
||||
literal. Its `unsupported` list names the encodings the rule rejects, which
|
||||
stay unsupported instead of being guessed. The list must name exactly the
|
||||
encodings the decoder rejects.
|
||||
|
||||
Each `[[form]]` entry has exactly these fields. A missing or unknown field is an
|
||||
error.
|
||||
|
||||
| Field | Meaning | Allowed values |
|
||||
| --- | --- | --- |
|
||||
| `name` | XML instruction name, the form's stable identity | upper-case, e.g. `S_ADD_U32` |
|
||||
| `family` | Encoding family; must match the XML base encoding | e.g. `SOP2` |
|
||||
| `opcode` | Opcode; must match the XML | non-negative integer |
|
||||
| `variant` | Rust enum variant of the typed operation | CamelCase, e.g. `AddU32` |
|
||||
| `operation` | The primitive the form uses | `add`, `sub`, `and`, `or`, `xor` |
|
||||
| `signedness` | How operands are read | `unsigned`, `signed`, `bitwise` (`bitwise` exactly for `and`, `or`, `xor`) |
|
||||
| `carry_in` | Whether the form reads SCC as carry-in or borrow-in | `none`, `scc` (`scc` only for unsigned `add` and `sub`) |
|
||||
| `width` | Operand and result width in bits | `32` |
|
||||
| `scc` | What the form writes to SCC | `carry_out`, `borrow`, `signed_overflow`, `nonzero`, `unchanged` |
|
||||
| `vcc`, `exec` | Effect on VCC and EXEC, stated rather than implied | `unchanged` |
|
||||
| `wave` | Wave sizes the form is valid in | `any` (`wave32` is in the vocabulary but rejected until the decoder can enforce it) |
|
||||
| `operands` | Name of an `[operand_rules]` entry for the same family | e.g. `sop2_sgpr` |
|
||||
| `spec` | References `{ document, section, page }` | at least one `guide` reference with a page above 0 |
|
||||
| `verify` | Evidence the form needs before it counts as verified | `reference`, `independent`, `metal`, `llvm_encoding` |
|
||||
|
||||
The `operation` and `signedness` pair picks one primitive, and that primitive
|
||||
fixes the `scc` value:
|
||||
|
||||
| `operation` / `signedness` | Required `scc` | Primitive | Reads carry-in |
|
||||
| --- | --- | --- | --- |
|
||||
| `add` / `unsigned` | `carry_out` | `add_carry_u32` | allowed |
|
||||
| `sub` / `unsigned` | `borrow` | `sub_borrow_u32` | allowed |
|
||||
| `add` / `signed` | `signed_overflow` | `add_overflow_i32` | no |
|
||||
| `sub` / `signed` | `signed_overflow` | `sub_overflow_i32` | no |
|
||||
| `and`, `or`, `xor` / `bitwise` | `nonzero` | `and_nonzero_b32`, `or_nonzero_b32`, `xor_nonzero_b32` | no |
|
||||
|
||||
Behaviour is chosen only from these declared fields, never from the mnemonic.
|
||||
|
||||
## What the validator checks
|
||||
|
||||
`validate` reports every error it finds, not only the first (a form with a missing field is not checked further). Besides the
|
||||
vocabularies above, it rejects:
|
||||
|
||||
- contradictions: a declared `scc` or `carry_in` that the primitive does not
|
||||
have, `bitwise` on an arithmetic operation or the reverse;
|
||||
- duplicates: the same `name`, the same `(family, opcode)` or the same
|
||||
`variant` declared twice;
|
||||
- XML disagreements: a family with no XML encoding, a form with no default XML
|
||||
variant, a different opcode, an SCC input or output the XML does not show (or
|
||||
that the declaration omits), an operand width other than `width`, a signed
|
||||
declaration on unsigned XML formats or the reverse, an operand direction that
|
||||
differs, and XML operands the operand rule does not cover;
|
||||
- references: a spec citing an undeclared document, a bad section or page, or
|
||||
no guide page at all;
|
||||
- operand rules the decoder does not implement, or whose declaration differs
|
||||
from the implemented one;
|
||||
- wrong types: a float width, a boolean schema, an opcode or page outside
|
||||
0-65535, or a reserved variant name such as `Self`.
|
||||
|
||||
CI runs `generate_semantics.py --check`, `scripts/audit/semantic_coverage.py
|
||||
--check` and both Python test suites next to the existing
|
||||
`generate_rdna2_meta.py --check`. Both scripts stop with a clear message on
|
||||
Python older than 3.11.
|
||||
|
||||
## What the generator does not do
|
||||
|
||||
- **The XML gives identity and encodings only.** The snapshot confirms the
|
||||
name, family, opcode, operand fields, widths, number formats and whether SCC
|
||||
is read or written. It says nothing about the arithmetic. Behaviour comes from
|
||||
the AMD guide, cited in `spec`, through the closed primitive table.
|
||||
- **It does not invent behaviour.** A form whose operation, signedness or
|
||||
operand rule is not already implemented is rejected. Adding a new operation
|
||||
means hand-writing a primitive in `primitive.rs`, a variant in
|
||||
`semantics.rs` and a row in the generator's vocabulary tables, reviewed like
|
||||
any other code.
|
||||
- **Undeclared forms stay unsupported.** The generated `from_word` returns
|
||||
`None` for every opcode not in the registry, and the decoder reports
|
||||
`UnsupportedOpcode`. Nothing falls back to a guess or a no-op.
|
||||
- **It does not write tests or reference semantics.** The reference
|
||||
interpreter (`crates/ref`) and the independent interpreter
|
||||
(`tests/validation/independent_ref.rs`) never read the registry or the
|
||||
generated code, and their known-answer tests are written by hand from the
|
||||
guide. That independence is what lets them catch a wrong registry entry; keep
|
||||
it when you add a form. Agreement with these references is agreement with a
|
||||
reading of the public AMD guide, not with Xbox hardware.
|
||||
|
||||
## Commands
|
||||
|
||||
Run these from the repository root. `python3` must be 3.11 or newer.
|
||||
|
||||
```sh
|
||||
# Check the registry only.
|
||||
python3 crates/isa/generate_semantics.py validate
|
||||
|
||||
# Validate, then rewrite crates/isa/src/semantics_gen.rs.
|
||||
python3 crates/isa/generate_semantics.py generate
|
||||
|
||||
# Validate and regenerate in memory; exit 1 if the committed file is stale. Never writes.
|
||||
python3 crates/isa/generate_semantics.py --check
|
||||
|
||||
# Generator unit tests.
|
||||
python3 -m unittest discover -s tests/semantics_generator
|
||||
|
||||
# The XML metadata tables the registry is cross-checked against are still current.
|
||||
python3 crates/isa/generate_rdna2_meta.py --check
|
||||
|
||||
# Rust tests of the generated tables and the decoder that uses them.
|
||||
cargo test --locked -p xenora-isa -p xenora-decoder
|
||||
|
||||
# Independent CPU validation.
|
||||
cargo test --locked -p xenora-semantic-review
|
||||
|
||||
# Native GPU correctness on Apple silicon.
|
||||
scripts/test-gpu.sh
|
||||
```
|
||||
|
||||
The LLVM encoding corpus check needs an LLVM build with the AMDGPU target:
|
||||
|
||||
```sh
|
||||
python3 crates/isa/tests/llvm/corpus.py --llvm-bin /path/to/llvm/bin --check
|
||||
```
|
||||
|
||||
## Worked example: `s_addc_u32`
|
||||
|
||||
`s_addc_u32` adds two 32-bit sources plus SCC and writes the carry-out of
|
||||
bit 31 to SCC (guide section 12.1, page 102; SCC rules in section 5.3, page 33).
|
||||
Its registry entry is:
|
||||
|
||||
```toml
|
||||
[[form]]
|
||||
name = "S_ADDC_U32"
|
||||
family = "SOP2"
|
||||
opcode = 4
|
||||
variant = "AddcU32"
|
||||
operation = "add"
|
||||
signedness = "unsigned"
|
||||
carry_in = "scc"
|
||||
width = 32
|
||||
scc = "carry_out"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 102 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
```
|
||||
|
||||
How each field is checked:
|
||||
|
||||
1. The XML snapshot has a default `ENC_SOP2` variant named `S_ADDC_U32` with
|
||||
opcode 4, so `name`, `family` and `opcode` agree.
|
||||
2. That XML variant reads and writes SCC, which matches `carry_in = "scc"` and
|
||||
an `scc` other than `unchanged`.
|
||||
3. `add` / `unsigned` selects `add_carry_u32`, which requires
|
||||
`scc = "carry_out"` and accepts a carry-in.
|
||||
4. The XML `SDST`, `SSRC0` and `SSRC1` operands are 32-bit `FMT_NUM_U32`
|
||||
fields, which matches `width = 32`, `unsigned` and the `sop2_sgpr` rule.
|
||||
|
||||
From this entry the generator emits, in `semantics_gen.rs`, the `AddcU32`
|
||||
variant of `ScalarAluOp`, its `from_word` arm (`0x8200_0000`), the mnemonic
|
||||
`s_addc_u32`, `reads_scc() == true`, an `evaluate` arm that calls
|
||||
`primitive::add_carry_u32(src0, src1, carry_in)`, and a `FormSemantics` row.
|
||||
|
||||
To add a form the same way:
|
||||
|
||||
1. Confirm its behaviour in the AMD guide and note the section and page.
|
||||
2. Check that an existing primitive and operand rule cover it. If not, the
|
||||
form needs hand-written code first (see above).
|
||||
3. Add a `[[form]]` entry and run `validate` until it reports no errors.
|
||||
4. Run `generate` and commit the registry and `semantics_gen.rs` together.
|
||||
5. Add known-answer tests to the reference and independent interpreters by
|
||||
hand, then run every command in [Commands](#commands).
|
||||
@@ -0,0 +1,326 @@
|
||||
"""Generate the gfx1030 semantic coverage report from the checked-in inventories."""
|
||||
|
||||
import argparse
|
||||
from collections import Counter, defaultdict
|
||||
import difflib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import runpy
|
||||
import sys
|
||||
try:
|
||||
import tomllib
|
||||
except ModuleNotFoundError: # pragma: no cover - depends on the interpreter
|
||||
sys.exit("semantic_coverage.py needs Python 3.11 or newer (tomllib)")
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
SNAPSHOT = Path("crates/isa/data/rdna2.jsonl")
|
||||
REGISTRY = Path("crates/isa/semantics/rdna2.toml")
|
||||
DECODER = Path("crates/decoder/src/lib.rs")
|
||||
GENERATED = Path("crates/isa/src/semantics_gen.rs")
|
||||
STATUS = Path("docs/status.toml")
|
||||
REPORT = Path("docs/shaders/semantic-coverage.md")
|
||||
|
||||
DECODER_HEADER = re.compile(
|
||||
r'const HANDWRITTEN_FORMS: \[\(&str, EncodingFamily\); (\d+)\] = \['
|
||||
)
|
||||
# The decoder's full list is its hand-written forms plus every registry form.
|
||||
DECODER_TOTAL = re.compile(
|
||||
r'pub const SEMANTIC_FORMS: \[\(&str, EncodingFamily\); '
|
||||
r'HANDWRITTEN_FORMS\.len\(\) \+ FORM_IDS\.len\(\)\] ='
|
||||
)
|
||||
DECODER_ENTRY = re.compile(r'\("([A-Z0-9_]+)", EncodingFamily::([A-Za-z0-9]+)\),')
|
||||
STATUS_ALIASES = {
|
||||
"s_waitcnt vmcnt(0)": ("SOPP", "S_WAITCNT"),
|
||||
"s_waitcnt_vscnt null, 0": ("SOPK", "S_WAITCNT_VSCNT"),
|
||||
}
|
||||
COLUMNS = (
|
||||
"Identified", "Encoding-validated", "Declared", "Decoder-supported",
|
||||
"IR", "MSL", "Reference-verified", "Metal-verified", "Unsupported operand variants",
|
||||
)
|
||||
|
||||
|
||||
def load_snapshot(root):
|
||||
# Reuse the metadata generator's base-form rules, including literal-only
|
||||
# forms and the relative moves whose base condition is not "default".
|
||||
metadata = runpy.run_path(str(root / "crates/isa/generate_rdna2_meta.py"))
|
||||
encodings = metadata["BASE_ENCODINGS"] | metadata["EXTENSIONS"]
|
||||
snapshot = (root / SNAPSHOT).read_text(encoding="utf-8")
|
||||
variants = []
|
||||
for number, line in enumerate(snapshot.splitlines(), 1):
|
||||
location = f"{SNAPSHOT}:{number}"
|
||||
try:
|
||||
row = json.loads(line)
|
||||
except ValueError as error:
|
||||
raise ValueError(f"{location}: {error}") from error
|
||||
if not isinstance(row, dict):
|
||||
raise ValueError(f"{location}: expected an object")
|
||||
kind = row.get("kind")
|
||||
if kind == "variant":
|
||||
if (
|
||||
not isinstance(row.get("encoding"), str) or row["encoding"] not in encodings
|
||||
or any(not isinstance(row.get(key), str) or not row[key]
|
||||
for key in ("instruction", "condition"))
|
||||
or type(row.get("opcode")) is not int
|
||||
):
|
||||
raise ValueError(f"{location}: invalid variant {row!r}")
|
||||
variants.append((location, row))
|
||||
elif kind not in ("source", "encoding", "operand_type", "data_format"):
|
||||
raise ValueError(f"{location}: unknown row kind {kind!r}")
|
||||
try:
|
||||
_, _, forms = metadata["forms_from_snapshot"](snapshot)
|
||||
except (SystemExit, ValueError, KeyError, IndexError, TypeError) as error:
|
||||
raise ValueError(f"{SNAPSHOT}: {error}") from error
|
||||
identified = {(form["encoding"].upper(), form["name"]): form["opcode"] for form in forms}
|
||||
if not identified or len(identified) != len(forms):
|
||||
raise ValueError(f"{SNAPSHOT}: expected unique, nonempty base forms")
|
||||
for location, row in variants:
|
||||
encoding = row["encoding"]
|
||||
base, _ = metadata["EXTENSIONS"].get(encoding, (encoding, None))
|
||||
key = (metadata["BASE_ENCODINGS"][base].upper(), row["instruction"])
|
||||
if key not in identified:
|
||||
raise ValueError(f"{location}: cannot map {encoding} variant to base form {key}")
|
||||
return identified
|
||||
|
||||
|
||||
def parse_decoder(source):
|
||||
lines = source.splitlines()
|
||||
if sum(bool(DECODER_TOTAL.fullmatch(line.strip())) for line in lines) != 1:
|
||||
raise ValueError(f"{DECODER}: expected SEMANTIC_FORMS = hand-written + registry forms")
|
||||
starts = [i for i, line in enumerate(lines)
|
||||
if re.match(r"\s*const HANDWRITTEN_FORMS\b", line)]
|
||||
if len(starts) != 1:
|
||||
raise ValueError(f"{DECODER}: expected one HANDWRITTEN_FORMS declaration")
|
||||
start = starts[0]
|
||||
header = DECODER_HEADER.fullmatch(lines[start].strip())
|
||||
if not header:
|
||||
raise ValueError(f"{DECODER}:{start + 1}: unrecognized SEMANTIC_FORMS declaration")
|
||||
|
||||
forms = set()
|
||||
for number, line in enumerate(lines[start + 1:], start + 2):
|
||||
line = line.partition("//")[0].strip()
|
||||
if line == "];":
|
||||
if len(forms) != int(header[1]):
|
||||
raise ValueError(f"{DECODER}:{number}: SEMANTIC_FORMS length mismatch")
|
||||
return forms
|
||||
if not line:
|
||||
continue
|
||||
entry = DECODER_ENTRY.fullmatch(line)
|
||||
if not entry:
|
||||
raise ValueError(f"{DECODER}:{number}: unrecognized SEMANTIC_FORMS entry {line!r}")
|
||||
key = (entry[2].upper(), entry[1])
|
||||
if key in forms:
|
||||
raise ValueError(f"{DECODER}:{number}: duplicate form {key}")
|
||||
forms.add(key)
|
||||
raise ValueError(f"{DECODER}: unterminated SEMANTIC_FORMS")
|
||||
|
||||
|
||||
GENERATED_HEADER = re.compile(r"pub const FORM_IDS: \[\(&str, EncodingFamily\); (\d+)\] = \[")
|
||||
|
||||
|
||||
def parse_generated(source):
|
||||
"""Registry forms compiled into the decoder, read from the generated FORM_IDS table."""
|
||||
lines = source.splitlines()
|
||||
starts = [i for i, line in enumerate(lines) if GENERATED_HEADER.fullmatch(line.strip())]
|
||||
if len(starts) != 1:
|
||||
raise ValueError(f"{GENERATED}: expected one FORM_IDS declaration")
|
||||
forms = set()
|
||||
rows = 0
|
||||
for number, line in enumerate(lines[starts[0] + 1:], starts[0] + 2):
|
||||
line = line.strip()
|
||||
if line == "];":
|
||||
if rows != len(forms):
|
||||
raise ValueError(f"{GENERATED}:{number}: duplicate FORM_IDS entry")
|
||||
if len(forms) != int(GENERATED_HEADER.fullmatch(lines[starts[0]].strip())[1]):
|
||||
raise ValueError(f"{GENERATED}:{number}: FORM_IDS length mismatch")
|
||||
return forms
|
||||
entry = DECODER_ENTRY.fullmatch(line)
|
||||
if not entry:
|
||||
raise ValueError(f"{GENERATED}:{number}: unrecognized FORM_IDS entry {line!r}")
|
||||
forms.add((entry[2].upper(), entry[1]))
|
||||
rows += 1
|
||||
raise ValueError(f"{GENERATED}: unterminated FORM_IDS")
|
||||
|
||||
|
||||
def read_declarations(registry, identified):
|
||||
if type(registry.get("schema")) is not int or registry["schema"] != 1:
|
||||
raise ValueError(f"{REGISTRY}: expected schema 1")
|
||||
families = {family for family, _ in identified}
|
||||
rules = {}
|
||||
for name, rule in registry["operand_rules"].items():
|
||||
location = f"{REGISTRY}: operand_rules.{name}"
|
||||
family = rule["family"]
|
||||
unsupported = rule["unsupported"]
|
||||
if family not in families:
|
||||
raise ValueError(f"{location}: unknown family {family!r}")
|
||||
if not isinstance(unsupported, list) or any(
|
||||
not isinstance(variant, str) or not re.fullmatch(r"[a-zA-Z0-9_]+", variant)
|
||||
for variant in unsupported
|
||||
):
|
||||
raise ValueError(f"{location}: invalid unsupported list")
|
||||
rules[name] = (family, set(unsupported))
|
||||
|
||||
declared = set()
|
||||
for form in registry["form"]:
|
||||
key = (form["family"], form["name"])
|
||||
if key not in identified:
|
||||
raise ValueError(f"{REGISTRY}: unknown form {key}")
|
||||
if type(form["opcode"]) is not int or form["opcode"] != identified[key]:
|
||||
raise ValueError(f"{REGISTRY}: opcode mismatch for {key}")
|
||||
if key in declared:
|
||||
raise ValueError(f"{REGISTRY}: duplicate form {key}")
|
||||
rule = form["operands"]
|
||||
if rule not in rules or rules[rule][0] != key[0]:
|
||||
raise ValueError(f"{REGISTRY}: invalid operand rule {rule!r} for {key}")
|
||||
declared.add(key)
|
||||
return declared, rules
|
||||
|
||||
|
||||
def status_form(row, identified):
|
||||
name = row["form"]
|
||||
if not isinstance(name, str) or not isinstance(row["encoding"], str):
|
||||
raise ValueError(f"{STATUS}: invalid form or encoding in {row!r}")
|
||||
families = {family for family, _ in identified}
|
||||
family_hint = row["encoding"].split(",", 1)[0].strip().upper()
|
||||
if name in STATUS_ALIASES:
|
||||
candidates = [STATUS_ALIASES[name]]
|
||||
else:
|
||||
mnemonic = name.upper()
|
||||
eligible = families
|
||||
if mnemonic.endswith("_E32"):
|
||||
mnemonic = mnemonic.removesuffix("_E32")
|
||||
eligible = families & {"VOP1", "VOP2", "VOPC"}
|
||||
elif mnemonic.endswith("_E64"):
|
||||
mnemonic = mnemonic.removesuffix("_E64")
|
||||
eligible = families & {"VOP3", "VOP3SDST"}
|
||||
candidates = sorted((family, mnemonic) for family in eligible
|
||||
if (family, mnemonic) in identified)
|
||||
if family_hint in families:
|
||||
candidates = [key for key in candidates if key[0] == family_hint]
|
||||
if len(candidates) != 1 or candidates[0] not in identified:
|
||||
raise ValueError(f"{STATUS}: cannot uniquely map {name!r} ({candidates})")
|
||||
return candidates[0]
|
||||
|
||||
|
||||
def collect_coverage(identified, registry, decoder, status):
|
||||
declared, rules = read_declarations(registry, identified)
|
||||
unknown = decoder.difference(identified)
|
||||
if unknown:
|
||||
raise ValueError(f"{DECODER}: unknown forms {sorted(unknown)}")
|
||||
|
||||
encoded, lowered, reference, metal = set(), set(), set(), set()
|
||||
seen = set()
|
||||
for row in status["instruction"]:
|
||||
key = status_form(row, identified)
|
||||
if key in seen:
|
||||
raise ValueError(f"{STATUS}: duplicate evidence for {key}")
|
||||
seen.add(key)
|
||||
for field in ("llvm", "lowering", "reference", "cpu", "gpu"):
|
||||
if field in row and not isinstance(row[field], str):
|
||||
raise ValueError(f"{STATUS}: {key} has invalid {field} evidence")
|
||||
if row.get("llvm") == "three-way passed":
|
||||
encoded.add(key)
|
||||
lowering = row.get("lowering", "").strip().lower()
|
||||
# This status schema uses one field for the IR-to-MSL path. A
|
||||
# compile-time resolution also implements that path for the form.
|
||||
if (
|
||||
lowering.startswith(("msl ", "resolved ", "verified ", "constant or ", "per-thread "))
|
||||
and not re.search(r"\b(?:stub|placeholder|planned|unsupported|pending|todo|unimplemented|not implemented|not yet)\b", lowering)
|
||||
):
|
||||
lowered.add(key)
|
||||
elif lowering:
|
||||
raise ValueError(f"{STATUS}: {key} has unrecognized lowering {row['lowering']!r}")
|
||||
# Verified evidence also requires the status row to say the form decodes.
|
||||
decodes = row.get("decoded") is True
|
||||
if decodes and row.get("reference") == "implemented" and row.get("cpu") == "fixture verified":
|
||||
reference.add(key)
|
||||
if decodes and row.get("gpu") in {"fixture verified", "fixture verified on Apple M5"}:
|
||||
metal.add(key)
|
||||
|
||||
counts = [Counter(family for family, _ in forms) for forms in (
|
||||
identified, encoded, declared, decoder, lowered, lowered, reference, metal,
|
||||
)]
|
||||
unsupported = defaultdict(set)
|
||||
for family, variants in rules.values():
|
||||
unsupported[family].update(variants)
|
||||
return {
|
||||
family: (*[count[family] for count in counts], len(unsupported[family]))
|
||||
for family in sorted(counts[0])
|
||||
}, rules
|
||||
|
||||
|
||||
def render_report(counts, rules):
|
||||
lines = [
|
||||
"# gfx1030 semantic coverage",
|
||||
"",
|
||||
"<!-- Generated by scripts/audit/semantic_coverage.py. -->",
|
||||
"",
|
||||
"Identified forms come from the AMD RDNA 2 instruction snapshot. Declared forms",
|
||||
"come from the semantic registry. Decoder support is the decoder's hand-written",
|
||||
"list plus the registry forms compiled into crates/isa/src/semantics_gen.rs.",
|
||||
"",
|
||||
"The status inventory records LLVM three-way encoding checks, intermediate",
|
||||
"representation (IR) and Metal Shading Language (MSL) lowering, and fixture",
|
||||
"verification. IR and MSL share the inventory's lowering field. Reference",
|
||||
"verification requires an implemented reference and verified CPU fixture.",
|
||||
"Metal verification requires a verified GPU fixture. Both also require a decoding row. Local readbacks pending",
|
||||
"acceptance remain outside the verified count. All results concern synthetic fixtures.",
|
||||
"",
|
||||
"| Family | " + " | ".join(COLUMNS) + " |",
|
||||
"| --- |" + " ---: |" * len(COLUMNS),
|
||||
]
|
||||
for family, values in counts.items():
|
||||
lines.append(f"| {family} | " + " | ".join(map(str, values)) + " |")
|
||||
lines.append("| **Total** | " + " | ".join(map(str, map(sum, zip(*counts.values())))) + " |")
|
||||
lines.extend([
|
||||
"",
|
||||
"## Unsupported operand variants",
|
||||
"",
|
||||
"The table counts distinct variant names per family across registry operand rules.",
|
||||
"",
|
||||
"| Family | Operand rule | Unsupported variants |",
|
||||
"| --- | --- | --- |",
|
||||
])
|
||||
for family, name, variants in sorted((family, name, variants)
|
||||
for name, (family, variants) in rules.items()):
|
||||
names = ", ".join(f"`{variant}`" for variant in sorted(variants))
|
||||
lines.append(f"| {family} | `{name}` | {names or 'None listed'} |")
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--check", action="store_true", help="compare without writing")
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
identified = load_snapshot(ROOT)
|
||||
registry = tomllib.loads((ROOT / REGISTRY).read_text(encoding="utf-8"))
|
||||
decoder = parse_decoder((ROOT / DECODER).read_text(encoding="utf-8")) | parse_generated(
|
||||
(ROOT / GENERATED).read_text(encoding="utf-8"))
|
||||
status = tomllib.loads((ROOT / STATUS).read_text(encoding="utf-8"))
|
||||
report = render_report(*collect_coverage(identified, registry, decoder, status)).encode()
|
||||
path = ROOT / REPORT
|
||||
if not args.check:
|
||||
path.write_bytes(report)
|
||||
print(f"Wrote {REPORT}")
|
||||
return 0
|
||||
committed = path.read_bytes() if path.exists() else b""
|
||||
if committed == report:
|
||||
print(f"{REPORT} is up to date")
|
||||
return 0
|
||||
before = committed.decode("utf-8", errors="replace").splitlines(keepends=True)
|
||||
after = report.decode().splitlines(keepends=True)
|
||||
diff = list(difflib.unified_diff(before, after, fromfile=str(REPORT),
|
||||
tofile="regenerated", n=0))
|
||||
print(f"{REPORT} differs from the regenerated report", file=sys.stderr)
|
||||
for line in diff[:12]:
|
||||
print(line.rstrip("\n"), file=sys.stderr)
|
||||
if len(diff) > 12:
|
||||
print("…", file=sys.stderr)
|
||||
except (OSError, ValueError, KeyError, TypeError, AttributeError) as error:
|
||||
print(f"semantic_coverage: {error}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,117 @@
|
||||
import unittest
|
||||
|
||||
from audit import semantic_coverage as coverage
|
||||
|
||||
|
||||
class SemanticCoverageTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.identified = {("SOP2", "S_ADD_U32"): 0, ("SOP2", "S_SUB_U32"): 1}
|
||||
self.registry = {
|
||||
"schema": 1,
|
||||
"form": [{
|
||||
"family": "SOP2", "name": "S_ADD_U32", "opcode": 0,
|
||||
"operands": "scalar", "verify": ["metal", "reference", "llvm_encoding"],
|
||||
}],
|
||||
"operand_rules": {
|
||||
"scalar": {"family": "SOP2", "unsupported": ["two_literals"]},
|
||||
},
|
||||
}
|
||||
|
||||
def counts(self, *rows):
|
||||
counts, _ = coverage.collect_coverage(
|
||||
self.identified, self.registry, {("SOP2", "S_SUB_U32")},
|
||||
{"instruction": list(rows)},
|
||||
)
|
||||
return dict(zip(coverage.COLUMNS, counts["SOP2"]))
|
||||
|
||||
def test_declared_without_metal_evidence_is_not_metal_verified(self):
|
||||
counts = self.counts()
|
||||
self.assertEqual(counts["Declared"], 1)
|
||||
self.assertEqual(counts["Metal-verified"], 0)
|
||||
self.assertEqual(counts["Reference-verified"], 0)
|
||||
self.assertEqual(counts["Encoding-validated"], 0)
|
||||
|
||||
def test_status_evidence_counts_for_handwritten_form(self):
|
||||
counts = self.counts({
|
||||
"form": "s_sub_u32", "encoding": "SOP2, scalar operands",
|
||||
"llvm": "three-way passed", "lowering": "resolved scalar state and SCC",
|
||||
"reference": "implemented", "cpu": "fixture verified",
|
||||
"gpu": "fixture verified on Apple M5", "decoded": True,
|
||||
})
|
||||
self.assertEqual(counts, {
|
||||
"Identified": 2, "Encoding-validated": 1, "Declared": 1,
|
||||
"Decoder-supported": 1, "IR": 1, "MSL": 1, "Reference-verified": 1,
|
||||
"Metal-verified": 1, "Unsupported operand variants": 1,
|
||||
})
|
||||
|
||||
def test_pending_readback_does_not_count(self):
|
||||
counts = self.counts({
|
||||
"form": "s_add_u32", "encoding": "SOP2", "lowering": "resolved scalar state and SCC",
|
||||
"reference": "implemented", "cpu": "local known-answer test passed",
|
||||
"gpu": "local Apple M5 readback passed; acceptance pending",
|
||||
})
|
||||
self.assertEqual(counts["Metal-verified"], 0)
|
||||
self.assertEqual(counts["Reference-verified"], 0)
|
||||
self.assertEqual(counts["IR"], 1)
|
||||
|
||||
def test_verified_evidence_needs_a_decoding_row(self):
|
||||
counts = self.counts({
|
||||
"form": "s_sub_u32", "encoding": "SOP2", "reference": "implemented",
|
||||
"cpu": "fixture verified", "gpu": "fixture verified", "decoded": False,
|
||||
})
|
||||
self.assertEqual(counts["Reference-verified"], 0)
|
||||
self.assertEqual(counts["Metal-verified"], 0)
|
||||
|
||||
def test_declared_but_not_compiled_is_not_decoder_supported(self):
|
||||
# S_ADD_U32 is declared in the registry but absent from the compiled tables.
|
||||
self.assertEqual(self.counts()["Decoder-supported"], 1)
|
||||
|
||||
def test_generated_table_parser(self):
|
||||
source = (
|
||||
"pub const FORM_IDS: [(&str, EncodingFamily); 1] = [\n"
|
||||
' ("S_ADD_U32", EncodingFamily::Sop2),\n];'
|
||||
)
|
||||
self.assertEqual(coverage.parse_generated(source), {("SOP2", "S_ADD_U32")})
|
||||
with self.assertRaisesRegex(ValueError, "length mismatch"):
|
||||
coverage.parse_generated(source.replace("; 1]", "; 2]"))
|
||||
duplicated = source.replace("; 1]", "; 2]").replace(
|
||||
' ("S_ADD_U32", EncodingFamily::Sop2),\n',
|
||||
' ("S_ADD_U32", EncodingFamily::Sop2),\n' * 2,
|
||||
)
|
||||
with self.assertRaisesRegex(ValueError, "duplicate FORM_IDS entry"):
|
||||
coverage.parse_generated(duplicated)
|
||||
|
||||
def test_stub_or_unrecognized_lowering_fails(self):
|
||||
for lowering in ("stub", "MSL placeholder add", "MSL unimplemented", "something new"):
|
||||
with self.assertRaisesRegex(ValueError, "unrecognized lowering"):
|
||||
self.counts({"form": "s_add_u32", "encoding": "SOP2", "lowering": lowering})
|
||||
|
||||
def test_status_suffix_disambiguates_encoding(self):
|
||||
forms = {("VOP2", "V_AND_B32"): 1, ("VOP3", "V_AND_B32"): 2}
|
||||
self.assertEqual(coverage.status_form(
|
||||
{"form": "v_and_b32_e32", "encoding": "Two VGPR sources"}, forms,
|
||||
), ("VOP2", "V_AND_B32"))
|
||||
with self.assertRaisesRegex(ValueError, "cannot uniquely map"):
|
||||
coverage.status_form(
|
||||
{"form": "v_and_b32", "encoding": "Two VGPR sources"}, forms,
|
||||
)
|
||||
|
||||
def test_unknown_status_form_fails(self):
|
||||
with self.assertRaisesRegex(ValueError, "cannot uniquely map.*s_typo"):
|
||||
self.counts({"form": "s_typo", "encoding": "SOP2"})
|
||||
|
||||
def test_decoder_parser_rejects_unrecognized_entry(self):
|
||||
header = (
|
||||
"pub const SEMANTIC_FORMS: [(&str, EncodingFamily); "
|
||||
"HANDWRITTEN_FORMS.len() + FORM_IDS.len()] =\n"
|
||||
"const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 1] = ["
|
||||
)
|
||||
self.assertEqual(coverage.parse_decoder(
|
||||
f'{header}\n ("S_ADD_U32", EncodingFamily::Sop2),\n];',
|
||||
), {("SOP2", "S_ADD_U32")})
|
||||
with self.assertRaisesRegex(ValueError, "unrecognized SEMANTIC_FORMS entry"):
|
||||
coverage.parse_decoder(f"{header}\n unknown!(),\n];")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,492 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Unit tests for crates/isa/generate_semantics.py.
|
||||
|
||||
Each rejection rule is fed a small in-memory registry that breaks exactly that
|
||||
rule, checked against a tiny hand-written XML snapshot. The real registry and
|
||||
snapshot are only read, never edited. Run from the repository root:
|
||||
|
||||
python3 -m unittest discover -s tests/semantics_generator
|
||||
"""
|
||||
|
||||
import copy
|
||||
import importlib.util
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
SCRIPT = ROOT / "crates/isa/generate_semantics.py"
|
||||
|
||||
_spec = importlib.util.spec_from_file_location("generate_semantics", SCRIPT)
|
||||
gen = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(gen)
|
||||
|
||||
SHA = "0" * 64
|
||||
|
||||
# Minimal stand-in for crates/isa/data/rdna2.jsonl: the SOP2 encoding and the
|
||||
# default variants of the four forms the fixture declares (values copied from
|
||||
# the AMD XML snapshot).
|
||||
U32 = "FMT_NUM_U32"
|
||||
I32 = "FMT_NUM_I32"
|
||||
|
||||
|
||||
def _operands(data_format, scc_in=False):
|
||||
rows = [
|
||||
["SDST", data_format, "OPR_SDST", 32, False, True, False, True],
|
||||
["SSRC0", data_format, "OPR_SSRC_NOLDS", 32, True, False, False, True],
|
||||
["SSRC1", data_format, "OPR_SSRC_NOLDS", 32, True, False, False, True],
|
||||
["", "FMT_NUM_B1", "OPR_SSRC_SPECIAL_SCC", 1, False, True, True, True],
|
||||
]
|
||||
if scc_in:
|
||||
rows.append(["", "FMT_NUM_B1", "OPR_SSRC_SPECIAL_SCC", 1, True, False, True, True])
|
||||
return rows
|
||||
|
||||
|
||||
def snapshot():
|
||||
sop2_base = 0x80000000
|
||||
encoding = {
|
||||
"name": "ENC_SOP2",
|
||||
"bits": 32,
|
||||
"fields": [
|
||||
["SSRC0", [[0, 8]]], ["SSRC1", [[8, 8]]], ["SDST", [[16, 7]]],
|
||||
["OP", [[23, 7]]], ["ENCODING", [[30, 2]]],
|
||||
],
|
||||
"identifier_mask": 0xFF800000,
|
||||
"identifiers": [sop2_base | (op << 23) for op in (0, 2, 4, 14)],
|
||||
}
|
||||
variants = {}
|
||||
for name, opcode, operands in (
|
||||
("S_ADD_U32", 0, _operands(U32)),
|
||||
("S_ADD_I32", 2, _operands(I32)),
|
||||
("S_ADDC_U32", 4, _operands(U32, scc_in=True)),
|
||||
("S_AND_B32", 14, _operands(U32)),
|
||||
):
|
||||
variants[(name, "ENC_SOP2")] = {
|
||||
"instruction": name, "encoding": "ENC_SOP2", "opcode": opcode, "operands": operands,
|
||||
}
|
||||
return {"source": {"sha256": SHA}, "encodings": {"ENC_SOP2": encoding}, "variants": variants}
|
||||
|
||||
|
||||
def _form(name, opcode, variant, operation, signedness, scc, carry_in="none"):
|
||||
return {
|
||||
"name": name, "family": "SOP2", "opcode": opcode, "variant": variant,
|
||||
"operation": operation, "signedness": signedness, "carry_in": carry_in,
|
||||
"width": 32, "scc": scc, "vcc": "unchanged", "exec": "unchanged", "wave": "any",
|
||||
"operands": "sop2_sgpr",
|
||||
"spec": [{"document": "guide", "section": "12.1", "page": 101}],
|
||||
"verify": ["reference", "independent"],
|
||||
}
|
||||
|
||||
|
||||
def registry():
|
||||
rule = copy.deepcopy(gen.OPERAND_RULES["sop2_sgpr"]["shape"])
|
||||
rule["unsupported"] = sorted(gen.UNSUPPORTED_COMBOS)
|
||||
return {
|
||||
"schema": 1,
|
||||
"architecture": "gfx1030",
|
||||
"source_sha256": SHA,
|
||||
"documents": copy.deepcopy(gen.PINNED_DOCUMENTS),
|
||||
"operand_rules": {"sop2_sgpr": rule},
|
||||
"form": [
|
||||
_form("S_ADD_U32", 0, "AddU32", "add", "unsigned", "carry_out"),
|
||||
_form("S_ADD_I32", 2, "AddI32", "add", "signed", "signed_overflow"),
|
||||
_form("S_ADDC_U32", 4, "AddcU32", "add", "unsigned", "carry_out", carry_in="scc"),
|
||||
_form("S_AND_B32", 14, "AndB32", "and", "bitwise", "nonzero"),
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def form(reg, name):
|
||||
return next(item for item in reg["form"] if item["name"] == name)
|
||||
|
||||
|
||||
class Validate(unittest.TestCase):
|
||||
def errors(self, reg, snap=None):
|
||||
return gen.validate(reg, snap if snap is not None else snapshot())
|
||||
|
||||
def rejects(self, reg, fragment, snap=None):
|
||||
errors = self.errors(reg, snap)
|
||||
self.assertTrue(
|
||||
any(fragment in error for error in errors),
|
||||
f"expected an error containing {fragment!r}, got {errors}",
|
||||
)
|
||||
|
||||
# ---- acceptance ----
|
||||
|
||||
def test_accepts_the_fixture(self):
|
||||
self.assertEqual(self.errors(registry()), [])
|
||||
|
||||
def test_accepts_the_real_registry(self):
|
||||
self.assertEqual(gen.validate(gen.load_registry(), gen.load_snapshot()), [])
|
||||
|
||||
# ---- top level ----
|
||||
|
||||
def test_rejects_wrong_schema(self):
|
||||
reg = registry()
|
||||
reg["schema"] = 2
|
||||
self.rejects(reg, "schema 2 is not 1")
|
||||
|
||||
def test_rejects_source_sha256_mismatch(self):
|
||||
reg = registry()
|
||||
reg["source_sha256"] = "f" * 64
|
||||
self.rejects(reg, "source_sha256 does not match")
|
||||
|
||||
def test_rejects_unknown_top_level_key(self):
|
||||
reg = registry()
|
||||
reg["notes"] = "x"
|
||||
self.rejects(reg, "unknown top-level keys ['notes']")
|
||||
|
||||
def test_rejects_empty_registry(self):
|
||||
reg = registry()
|
||||
reg["form"] = []
|
||||
self.rejects(reg, "declares no forms")
|
||||
|
||||
# ---- incomplete or unknown fields ----
|
||||
|
||||
def test_rejects_missing_required_field(self):
|
||||
reg = registry()
|
||||
del form(reg, "S_ADD_U32")["scc"]
|
||||
self.rejects(reg, "S_ADD_U32: incomplete, missing ['scc']")
|
||||
|
||||
def test_rejects_unknown_form_key(self):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")["expression"] = "a + b"
|
||||
self.rejects(reg, "S_ADD_U32: unknown keys ['expression']")
|
||||
|
||||
# ---- closed vocabularies ----
|
||||
|
||||
def test_rejects_unknown_operation(self):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")["operation"] = "mul"
|
||||
self.rejects(reg, "S_ADD_U32: unknown operation 'mul'")
|
||||
|
||||
def test_rejects_unknown_scc_effect(self):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")["scc"] = "overflow"
|
||||
self.rejects(reg, "S_ADD_U32: unknown scc 'overflow'")
|
||||
|
||||
def test_rejects_unknown_mask_effect(self):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")["vcc"] = "written"
|
||||
self.rejects(reg, "S_ADD_U32: unknown vcc 'written'")
|
||||
|
||||
def test_rejects_unsupported_width(self):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")["width"] = 64
|
||||
self.rejects(reg, "S_ADD_U32: width 64 is not supported")
|
||||
|
||||
def test_rejects_unknown_evidence(self):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")["verify"] = ["reference", "hardware"]
|
||||
self.rejects(reg, "S_ADD_U32: unknown verification requirement")
|
||||
|
||||
def test_rejects_empty_evidence(self):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")["verify"] = []
|
||||
self.rejects(reg, "S_ADD_U32: no verification requirement")
|
||||
|
||||
# ---- contradictions ----
|
||||
|
||||
def test_rejects_bitwise_operation_declared_signed(self):
|
||||
reg = registry()
|
||||
form(reg, "S_AND_B32")["signedness"] = "signed"
|
||||
self.rejects(reg, "S_AND_B32: signedness signed contradicts operation and")
|
||||
|
||||
def test_rejects_carry_in_on_logical_operation(self):
|
||||
reg = registry()
|
||||
form(reg, "S_AND_B32")["carry_in"] = "scc"
|
||||
self.rejects(reg, "S_AND_B32: carry_in scc contradicts and/bitwise")
|
||||
|
||||
def test_rejects_carry_out_on_signed_form(self):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_I32")["scc"] = "carry_out"
|
||||
self.rejects(reg, "S_ADD_I32: scc carry_out contradicts add/signed")
|
||||
|
||||
def test_rejects_scc_unchanged_on_a_form_that_writes_it(self):
|
||||
# Declared as preserving SCC while the primitive and the XML both write it.
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")["scc"] = "unchanged"
|
||||
self.rejects(reg, "S_ADD_U32: scc unchanged contradicts add/unsigned")
|
||||
self.rejects(reg, "S_ADD_U32: scc unchanged contradicts the XML SCC output")
|
||||
|
||||
def test_rejects_carry_in_the_xml_does_not_read(self):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")["carry_in"] = "scc"
|
||||
self.rejects(reg, "S_ADD_U32: carry_in scc contradicts the XML SCC input")
|
||||
|
||||
def test_rejects_signedness_contradicting_xml_format(self):
|
||||
reg = registry()
|
||||
f = form(reg, "S_ADD_I32")
|
||||
f["signedness"], f["scc"] = "unsigned", "carry_out"
|
||||
self.rejects(reg, "S_ADD_I32: signedness unsigned contradicts XML format FMT_NUM_I32")
|
||||
|
||||
# ---- identity against the XML snapshot ----
|
||||
|
||||
def test_rejects_opcode_mismatch(self):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")["opcode"] = 1
|
||||
self.rejects(reg, "S_ADD_U32: opcode 1 disagrees with the XML opcode 0")
|
||||
|
||||
def test_rejects_family_mismatch(self):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")["family"] = "SOPC"
|
||||
self.rejects(reg, "S_ADD_U32: operand rule sop2_sgpr is for SOP2")
|
||||
self.rejects(reg, "S_ADD_U32: family SOPC has no XML encoding ENC_SOPC")
|
||||
|
||||
def test_rejects_form_absent_from_the_xml(self):
|
||||
reg = registry()
|
||||
reg["form"].append(_form("S_MUL_I32", 38, "MulI32", "add", "signed", "signed_overflow"))
|
||||
self.rejects(reg, "S_MUL_I32: no default ENC_SOP2 variant in the XML snapshot")
|
||||
|
||||
# ---- duplicates ----
|
||||
|
||||
def test_rejects_duplicate_name(self):
|
||||
reg = registry()
|
||||
reg["form"].append(copy.deepcopy(form(reg, "S_ADD_U32")))
|
||||
self.rejects(reg, "S_ADD_U32: duplicate name S_ADD_U32")
|
||||
|
||||
def test_rejects_same_encoding_claimed_twice(self):
|
||||
reg = registry()
|
||||
twin = copy.deepcopy(form(reg, "S_ADD_U32"))
|
||||
twin["name"], twin["variant"] = "S_ADD_U32_COPY", "AddU32Copy"
|
||||
reg["form"].append(twin)
|
||||
self.rejects(reg, "S_ADD_U32_COPY: duplicate opcode ('SOP2', 0)")
|
||||
|
||||
def test_rejects_duplicate_variant(self):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_I32")["variant"] = "AddU32"
|
||||
self.rejects(reg, "S_ADD_I32: duplicate variant AddU32")
|
||||
|
||||
# ---- references ----
|
||||
|
||||
def test_rejects_missing_guide_reference(self):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")["spec"] = [{"document": "xml", "section": "1", "page": 0}]
|
||||
self.rejects(reg, "S_ADD_U32: missing a guide section and page reference")
|
||||
|
||||
def test_rejects_undeclared_document(self):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")["spec"].append({"document": "blog", "section": "1", "page": 1})
|
||||
self.rejects(reg, "S_ADD_U32: spec cites undeclared document 'blog'")
|
||||
|
||||
# ---- operand rules ----
|
||||
|
||||
def test_rejects_unknown_operand_rule_on_a_form(self):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")["operands"] = "vop2_vgpr"
|
||||
self.rejects(reg, "S_ADD_U32: unknown operand rule 'vop2_vgpr'")
|
||||
|
||||
def test_rejects_operand_rule_the_decoder_does_not_implement(self):
|
||||
reg = registry()
|
||||
reg["operand_rules"]["vop2_vgpr"] = {"family": "VOP2"}
|
||||
self.rejects(reg, "operand rule vop2_vgpr: not implemented by the decoder")
|
||||
|
||||
def test_rejects_operand_rule_shape_differing_from_the_decoder(self):
|
||||
reg = registry()
|
||||
reg["operand_rules"]["sop2_sgpr"]["max_literals"] = 2
|
||||
self.rejects(reg, "operand rule sop2_sgpr: declaration differs")
|
||||
|
||||
def test_rejects_an_incomplete_unsupported_list(self):
|
||||
reg = registry()
|
||||
reg["operand_rules"]["sop2_sgpr"]["unsupported"].remove("two_literals")
|
||||
self.rejects(
|
||||
reg, "operand rule sop2_sgpr: unsupported combos differ from those the decoder rejects"
|
||||
)
|
||||
|
||||
def test_rejects_a_citation_to_another_file(self):
|
||||
reg = registry()
|
||||
reg["documents"]["guide"]["file"] = "missing.pdf"
|
||||
self.rejects(reg, "document guide: differs from the pinned public document")
|
||||
|
||||
def test_rejects_an_unenforced_wave_restriction(self):
|
||||
reg = registry()
|
||||
reg["form"][0]["wave"] = "wave32"
|
||||
self.rejects(reg, "S_ADD_U32: wave wave32 has no decoder enforcement yet")
|
||||
|
||||
def test_rejects_a_reserved_variant(self):
|
||||
reg = registry()
|
||||
reg["form"][0]["variant"] = "Self"
|
||||
self.rejects(reg, "S_ADD_U32: variant 'Self' is reserved")
|
||||
|
||||
def test_rejects_a_boolean_schema(self):
|
||||
reg = registry()
|
||||
reg["schema"] = True
|
||||
self.rejects(reg, "schema True is not 1")
|
||||
|
||||
def test_rejects_unknown_unsupported_combo(self):
|
||||
reg = registry()
|
||||
reg["operand_rules"]["sop2_sgpr"]["unsupported"].append("dst_lds")
|
||||
self.rejects(reg, "operand rule sop2_sgpr: unknown unsupported combos ['dst_lds']")
|
||||
|
||||
def test_rejects_duplicate_unsupported_combo(self):
|
||||
reg = registry()
|
||||
reg["operand_rules"]["sop2_sgpr"]["unsupported"].append("dst_vcc")
|
||||
self.rejects(reg, "operand rule sop2_sgpr: duplicate unsupported combos")
|
||||
|
||||
# ---- remaining vocabulary, identity and reference rules ----
|
||||
|
||||
def test_rejects_wrong_architecture(self):
|
||||
reg = registry()
|
||||
reg["architecture"] = "gfx1100"
|
||||
self.rejects(reg, "architecture 'gfx1100' is not gfx1030")
|
||||
|
||||
def test_rejects_unknown_document(self):
|
||||
reg = registry()
|
||||
reg["documents"]["blog"] = {"title": "blog"}
|
||||
self.rejects(reg, "unknown document blog")
|
||||
|
||||
def test_rejects_unknown_signedness_carry_in_exec_and_wave(self):
|
||||
for key, value in (
|
||||
("signedness", "float"), ("carry_in", "vcc"), ("exec", "written"), ("wave", "wave64"),
|
||||
):
|
||||
with self.subTest(key=key):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")[key] = value
|
||||
self.rejects(reg, f"S_ADD_U32: unknown {key} {value!r}")
|
||||
|
||||
def test_rejects_invalid_name_variant_and_opcode(self):
|
||||
for key, value, fragment in (
|
||||
("name", "s_add_u32", "s_add_u32: invalid name"),
|
||||
("variant", "add_u32", "S_ADD_U32: invalid variant 'add_u32'"),
|
||||
("opcode", -1, "S_ADD_U32: invalid opcode"),
|
||||
("opcode", True, "S_ADD_U32: invalid opcode"),
|
||||
):
|
||||
with self.subTest(key=key, value=value):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")[key] = value
|
||||
self.rejects(reg, fragment)
|
||||
|
||||
def test_rejects_declaration_no_primitive_implements(self):
|
||||
reg = registry()
|
||||
form(reg, "S_AND_B32")["operation"] = "sub"
|
||||
self.rejects(reg, "S_AND_B32: no primitive implements sub/bitwise")
|
||||
|
||||
def test_rejects_duplicate_evidence(self):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")["verify"] = ["reference", "reference"]
|
||||
self.rejects(reg, "S_ADD_U32: duplicate verification requirement")
|
||||
|
||||
def test_rejects_malformed_spec_references(self):
|
||||
for ref, fragment in (
|
||||
({"document": "guide", "section": "12.1"}, "spec reference needs exactly document, section, page"),
|
||||
({"document": "guide", "section": "12.x", "page": 101}, "invalid spec section '12.x'"),
|
||||
({"document": "guide", "section": "12.1", "page": -1}, "invalid spec page"),
|
||||
):
|
||||
with self.subTest(ref=ref):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")["spec"].append(ref)
|
||||
self.rejects(reg, f"S_ADD_U32: {fragment}")
|
||||
|
||||
def test_rejects_guide_reference_without_a_page(self):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")["spec"] = [{"document": "guide", "section": "12.1", "page": 0}]
|
||||
self.rejects(reg, "S_ADD_U32: missing a guide section and page reference")
|
||||
|
||||
def test_rejects_opcode_outside_the_encoding_identifiers(self):
|
||||
snap = snapshot()
|
||||
snap["encodings"]["ENC_SOP2"]["identifiers"].remove(0x80000000 | (14 << 23))
|
||||
self.rejects(registry(), "S_AND_B32: opcode 14 is not an identifier of ENC_SOP2", snap)
|
||||
|
||||
def test_rejects_xml_operand_disagreements(self):
|
||||
cases = (
|
||||
("missing", lambda ops: ops.pop(2), "S_ADD_U32: XML has no operand SSRC1"),
|
||||
("width", lambda ops: ops[1].__setitem__(3, 64), "S_ADD_U32: SSRC0 is 64 bits in the XML"),
|
||||
("direction", lambda ops: ops[0].__setitem__(4, True),
|
||||
"S_ADD_U32: SDST direction disagrees with the XML"),
|
||||
("extra", lambda ops: ops.append(["SIMM16", U32, "OPR_SIMM16", 16, True, False, False, True]),
|
||||
"S_ADD_U32: XML operands ['SIMM16'] are not covered by rule sop2_sgpr"),
|
||||
)
|
||||
for label, change, fragment in cases:
|
||||
with self.subTest(case=label):
|
||||
snap = snapshot()
|
||||
change(snap["variants"][("S_ADD_U32", "ENC_SOP2")]["operands"])
|
||||
self.rejects(registry(), fragment, snap)
|
||||
|
||||
|
||||
def _reorder(value):
|
||||
"""Reverse the key order of every mapping, keeping list order."""
|
||||
if isinstance(value, dict):
|
||||
return {key: _reorder(value[key]) for key in reversed(list(value))}
|
||||
if isinstance(value, list):
|
||||
return [_reorder(item) for item in value]
|
||||
return value
|
||||
|
||||
|
||||
class Render(unittest.TestCase):
|
||||
def test_two_renders_are_identical(self):
|
||||
self.assertEqual(gen.render(registry(), snapshot()), gen.render(registry(), snapshot()))
|
||||
|
||||
def test_render_ignores_mapping_key_order(self):
|
||||
reg = registry()
|
||||
reordered = _reorder(reg)
|
||||
self.assertNotEqual(list(reg["form"][0]), list(reordered["form"][0]))
|
||||
self.assertEqual(gen.render(reg, snapshot()), gen.render(reordered, snapshot()))
|
||||
|
||||
def test_dispatch_is_sorted_by_opcode(self):
|
||||
reg = registry()
|
||||
reg["form"].reverse()
|
||||
text = gen.render(reg, snapshot())
|
||||
body = text.split("match word & ", 1)[1].split("_ => None", 1)[0]
|
||||
words = [line.split(" => ")[0].strip() for line in body.splitlines()[1:] if "=>" in line]
|
||||
self.assertEqual(words, sorted(words))
|
||||
self.assertEqual(len(words), 4)
|
||||
|
||||
def test_real_registry_renders_the_committed_file(self):
|
||||
text = gen.render(gen.load_registry(), gen.load_snapshot())
|
||||
self.assertEqual(text, gen.RUST.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
class CommandLine(unittest.TestCase):
|
||||
def run_cli(self, *arguments):
|
||||
return subprocess.run(
|
||||
[sys.executable, str(SCRIPT), *map(str, arguments)],
|
||||
capture_output=True, text=True, check=False,
|
||||
)
|
||||
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.dir = Path(self.tmp.name)
|
||||
|
||||
def test_check_passes_on_the_committed_file(self):
|
||||
result = self.run_cli("--check")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
|
||||
def test_check_passes_on_a_fresh_file_and_fails_on_a_stale_one(self):
|
||||
output = self.dir / "semantics_gen.rs"
|
||||
result = self.run_cli("generate", "--output", output)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
fresh = output.read_text(encoding="utf-8")
|
||||
self.assertEqual(self.run_cli("--check", "--output", output).returncode, 0)
|
||||
|
||||
output.write_text(fresh.replace("pub const GENERATED_SCHEMA: u32 = 1;", "pub const GENERATED_SCHEMA: u32 = 2;"))
|
||||
stale = self.run_cli("--check", "--output", output)
|
||||
self.assertEqual(stale.returncode, 1)
|
||||
self.assertIn("is stale", stale.stderr)
|
||||
# --check never writes.
|
||||
self.assertNotEqual(output.read_text(encoding="utf-8"), fresh)
|
||||
|
||||
def test_check_fails_when_the_generated_file_is_missing(self):
|
||||
self.assertEqual(self.run_cli("--check", "--output", self.dir / "absent.rs").returncode, 1)
|
||||
|
||||
def test_invalid_registry_fails_every_mode_without_writing(self):
|
||||
bad = self.dir / "rdna2.toml"
|
||||
text = gen.REGISTRY.read_text(encoding="utf-8")
|
||||
bad.write_text(text.replace("\nschema = 1\n", "\nschema = 2\n", 1), encoding="utf-8")
|
||||
output = self.dir / "out.rs"
|
||||
for mode in (("validate",), ("generate",), ("--check",)):
|
||||
result = self.run_cli(*mode, "--registry", bad, "--output", output)
|
||||
self.assertEqual(result.returncode, 1, mode)
|
||||
self.assertIn("error: schema 2 is not 1", result.stderr)
|
||||
self.assertFalse(output.exists())
|
||||
|
||||
def test_validate_reports_the_form_count(self):
|
||||
result = self.run_cli("validate")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(result.stdout.strip(), f"registry valid: {len(gen.load_registry()['form'])} forms")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user