mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-26 03:39:52 +00:00
isa, scripts: review fixes for the registry split and encoding variants (#215)
- Includes must be `<root stem>/<family>.toml`, so a family file cannot live outside the registry directory or be aliased past the repeat guard. The coverage report (and through it the RDNA2 planner) now uses the generator's loader, so the family-file guards apply to every consumer. - A variant's explicit XML operand formats, destination included, must equal its base encoding's; malformed variant fields are diagnosed instead of raising. - Variants get their own generated enum (VectorAluVop3Op: from_word, base, assembly_name, semantics), so Instruction::VectorAluVop3 cannot name an undeclared encoding and formatting cannot panic. - The planner no longer counts a variant-only operand rule as a rule that can host new forms of its family (V_FMA_F32 was shown as reuse-ready). - The isa test checks that no first word of another 64-bit family (VOP3B) selects a VOP3 variant; docs describe the variant files. Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
This commit is contained in:
1 parent
516976fb9f
commit
6bc88d6c51
14 files changed
+263
-83
No files matched your search
@@ -4,7 +4,8 @@ use std::fmt;
|
||||
|
||||
pub use xenora_isa::{
|
||||
Architecture, CompareRelation, ExportTarget, Instruction, InterpolationPhase, ScalarAluOp,
|
||||
ScalarCompareOp, ScalarSource, ScalarUnaryOp, VectorAluOp, VectorCompareOp, VectorSource,
|
||||
ScalarCompareOp, ScalarSource, ScalarUnaryOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp,
|
||||
VectorSource,
|
||||
};
|
||||
use xenora_isa::{
|
||||
BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_BRANCH, S_CBRANCH_EXECZ,
|
||||
@@ -326,7 +327,7 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
|
||||
if let Some(op) = VectorCompareOp::from_word(first) {
|
||||
return vector_compare(op, first, bytes);
|
||||
}
|
||||
if let Some(op) = VectorAluOp::from_vop3_word(first) {
|
||||
if let Some(op) = VectorAluVop3Op::from_word(first) {
|
||||
let second = word(bytes, 8)?;
|
||||
return Ok((vop3_vgpr2(op, first, second)?, 8));
|
||||
}
|
||||
@@ -749,13 +750,16 @@ fn move_b32(first: u32, bytes: &[u8]) -> Result<(Instruction, u8), DecodeErrorKi
|
||||
/// in bits 0-8 and 9-17 of the second (RDNA 2 ISA section 13.3.4, VOP3A). Both sources
|
||||
/// are VGPRs, ABS, OP_SEL, CLAMP, OMOD and NEG are clear, and the unused SRC2 is
|
||||
/// the gfx1030 assembler's inline-zero operand encoding.
|
||||
fn vop3_vgpr2(op: VectorAluOp, first: u32, second: u32) -> Result<Instruction, DecodeErrorKind> {
|
||||
fn vop3_vgpr2(
|
||||
op: VectorAluVop3Op,
|
||||
first: u32,
|
||||
second: u32,
|
||||
) -> Result<Instruction, DecodeErrorKind> {
|
||||
let src0 = second & 0x1ff;
|
||||
let src1 = (second >> 9) & 0x1ff;
|
||||
if first & 0xff00 != 0 || second >> 18 != 128 || src0 < 256 || src1 < 256 {
|
||||
return Err(unsupported(
|
||||
op.vop3_assembly_name()
|
||||
.expect("VOP3 dispatch selects only declared variants"),
|
||||
op.assembly_name(),
|
||||
"expected two VGPR sources and no modifiers",
|
||||
));
|
||||
}
|
||||
|
||||
@@ -4,7 +4,8 @@ use std::process::{Command, Stdio};
|
||||
|
||||
use xenora_decoder::{
|
||||
Architecture, CompareRelation, DecodeError, DecodeErrorKind, DecodedInstruction, Instruction,
|
||||
ScalarAluOp, ScalarSource, ScalarUnaryOp, VectorAluOp, VectorSource, decode, decode_at,
|
||||
ScalarAluOp, ScalarSource, ScalarUnaryOp, VectorAluOp, VectorAluVop3Op, VectorSource, decode,
|
||||
decode_at,
|
||||
};
|
||||
use xenora_isa::semantics::Signedness;
|
||||
use xenora_ref::{
|
||||
@@ -44,7 +45,7 @@ fn decodes_each_fixture_instruction_with_offset_and_length() {
|
||||
20,
|
||||
8,
|
||||
Instruction::VectorAluVop3 {
|
||||
op: VectorAluOp::AddNcU32,
|
||||
op: VectorAluVop3Op::AddNcU32,
|
||||
dst: 1,
|
||||
src0: 1,
|
||||
src1: 2,
|
||||
@@ -376,12 +377,11 @@ fn reference_op(instruction: Instruction) -> Op {
|
||||
),
|
||||
// The reference's VOP3 add; it is the only VOP3 variant so far.
|
||||
Instruction::VectorAluVop3 {
|
||||
op: VectorAluOp::AddNcU32,
|
||||
op: VectorAluVop3Op::AddNcU32,
|
||||
dst,
|
||||
src0,
|
||||
src1,
|
||||
} => Op::Add(dst, src0, src1),
|
||||
Instruction::VectorAluVop3 { op, .. } => panic!("no reference VOP3 mapping for {op:?}"),
|
||||
Instruction::ScalarMoveB32 { dst, src } => Op::ScalarMove(dst, reference_scalar(src)),
|
||||
Instruction::ScalarUnary { op, dst, src } => Op::ScalarUnary(
|
||||
match op {
|
||||
@@ -1007,7 +1007,7 @@ fn accepts_scalar_destination_105_and_vgpr_zero_add_sources() {
|
||||
assert_eq!(
|
||||
decode(Architecture::Gfx1030, &bytes).unwrap()[0].instruction,
|
||||
Instruction::VectorAluVop3 {
|
||||
op: VectorAluOp::AddNcU32,
|
||||
op: VectorAluVop3Op::AddNcU32,
|
||||
dst: 1,
|
||||
src0: 0,
|
||||
src1: 0
|
||||
|
||||
@@ -320,6 +320,8 @@ OPERAND_RULES = {
|
||||
"kind": "vector_vop3",
|
||||
# Only encoding variants of forms whose rule has this kind may use it.
|
||||
"variant_of": "vector",
|
||||
# The generated enum of this rule's variants; base() maps to "enum".
|
||||
"variant_enum": "VectorAluVop3Op",
|
||||
},
|
||||
"vop2_vgpr": {
|
||||
"rust": "Vop2Vgpr",
|
||||
@@ -354,6 +356,8 @@ class RegistryError(ValueError):
|
||||
"""A registry file set that cannot be merged into one registry."""
|
||||
|
||||
|
||||
# An include names a family file as `<root stem>/<lower-case family>.toml`.
|
||||
INCLUDE = re.compile(r"^[a-z0-9_]+/[a-z0-9]+\.toml$")
|
||||
# Keys a family file may hold; everything else lives in the root file.
|
||||
FAMILY_FILE_KEYS = {"operand_rules", "form", "encoding_variant"}
|
||||
|
||||
@@ -373,6 +377,13 @@ def load_registry(path=REGISTRY):
|
||||
includes = registry.pop("include", [])
|
||||
if not isinstance(includes, list) or not all(isinstance(item, str) for item in includes):
|
||||
raise RegistryError(f"{path.name}: include must be a list of file names")
|
||||
# Family files live directly in the directory named after the root
|
||||
# (rdna2.toml -> rdna2/), as `<stem>/<family>.toml`; nothing else resolves.
|
||||
for include in includes:
|
||||
if not INCLUDE.match(include) or include.split("/", 1)[0] != path.stem:
|
||||
raise RegistryError(
|
||||
f"{path.name}: include {include!r} is not {path.stem}/<family>.toml"
|
||||
)
|
||||
if len(set(includes)) != len(includes):
|
||||
raise RegistryError(f"{path.name}: a family file is included twice")
|
||||
rules = registry.setdefault("operand_rules", {})
|
||||
@@ -740,7 +751,7 @@ def _check_variants(registry, rules, documents, snapshot, seen, errors):
|
||||
forms = {form.get("name"): form for form in registry.get("form", [])}
|
||||
identities = {(form.get("name"), form.get("family")) for form in registry.get("form", [])}
|
||||
for index, variant in enumerate(registry.get("encoding_variant", [])):
|
||||
label = f"{variant.get('of', f'variant #{index}')} ({variant.get('family')})"
|
||||
label = f"{variant.get('of', f'variant #{index}')!s} ({variant.get('family')!s})"
|
||||
missing = sorted(VARIANT_KEYS - set(variant))
|
||||
extra = sorted(set(variant) - VARIANT_KEYS)
|
||||
if missing:
|
||||
@@ -749,6 +760,10 @@ def _check_variants(registry, rules, documents, snapshot, seen, errors):
|
||||
errors.append(f"{label}: unknown keys {extra}")
|
||||
if missing:
|
||||
continue
|
||||
malformed = [key for key in ("of", "family", "operands") if not isinstance(variant[key], str)]
|
||||
if malformed:
|
||||
errors.append(f"{label}: {malformed} must be strings")
|
||||
continue
|
||||
base = forms.get(variant["of"])
|
||||
if base is None:
|
||||
errors.append(f"{label}: encoding variant of an undeclared form")
|
||||
@@ -783,6 +798,18 @@ def _check_variants(registry, rules, documents, snapshot, seen, errors):
|
||||
# The XML check runs on the re-encoded declaration, so the variant's
|
||||
# operands must agree with the base form's widths, signedness and effects.
|
||||
_check_xml(variant_row(registry, variant), rule, snapshot, errors)
|
||||
# Every explicit operand, destination included, has the base encoding's
|
||||
# data format, in the same order (VSRC1 of VOP2 is SRC1 of VOP3).
|
||||
base_xml = snapshot["variants"].get((base["name"], _family_encoding(base["family"])))
|
||||
own_xml = snapshot["variants"].get((variant["of"], _family_encoding(variant["family"])))
|
||||
if base_xml and own_xml:
|
||||
formats = [
|
||||
[row[1] for row in record["operands"] if row[0]] for record in (base_xml, own_xml)
|
||||
]
|
||||
if formats[0] != formats[1]:
|
||||
errors.append(
|
||||
f"{label}: XML operand formats {formats[1]} differ from the form's {formats[0]}"
|
||||
)
|
||||
|
||||
|
||||
def _implemented_rule(form):
|
||||
@@ -844,9 +871,12 @@ def render(registry, snapshot):
|
||||
selected = [form for form in forms if form["operands"] == rule_name]
|
||||
out += _render_enum(rule_name, selected, snapshot, positions)
|
||||
variants = registry.get("encoding_variant", [])
|
||||
variant_positions = {
|
||||
(variant["of"], variant["family"]): len(forms) + index for index, variant in enumerate(variants)
|
||||
}
|
||||
for rule_name in sorted({variant["operands"] for variant in variants}):
|
||||
selected = [variant for variant in variants if variant["operands"] == rule_name]
|
||||
out += _render_variants(rule_name, selected, registry, snapshot)
|
||||
out += _render_variants(rule_name, selected, registry, snapshot, variant_positions)
|
||||
# Encoding variants follow the forms, as rows of their own.
|
||||
forms = forms + [variant_row(registry, variant) for variant in variants]
|
||||
out += [
|
||||
@@ -897,9 +927,10 @@ def render(registry, snapshot):
|
||||
return "\n".join(out)
|
||||
|
||||
|
||||
def _render_variants(rule_name, variants, registry, snapshot):
|
||||
"""Dispatch of one operand rule's encoding variants onto the base enum."""
|
||||
enum = OPERAND_RULES[rule_name]["enum"]
|
||||
def _render_variants(rule_name, variants, registry, snapshot, positions):
|
||||
"""One enum per variant rule: exactly its declared variants, with dispatch."""
|
||||
base_enum = OPERAND_RULES[rule_name]["enum"]
|
||||
enum = OPERAND_RULES[rule_name]["variant_enum"]
|
||||
family = variants[0]["family"]
|
||||
encoding = snapshot["encodings"][_family_encoding(family)]
|
||||
(offset, size), = dict((name, ranges) for name, ranges in encoding["fields"])["OP"]
|
||||
@@ -908,16 +939,35 @@ def _render_variants(rule_name, variants, registry, snapshot):
|
||||
fixed_bits = encoding["identifiers"][0] & fixed_mask
|
||||
if any(identifier & fixed_mask != fixed_bits for identifier in encoding["identifiers"]):
|
||||
raise ValueError(f"{family}: identifiers do not split into fixed bits and OP")
|
||||
lower = family.lower()
|
||||
variant_of = {form["name"]: form["variant"] for form in registry["form"]}
|
||||
rows = sorted(variants, key=lambda variant: variant["opcode"])
|
||||
suffix = ASSEMBLY_SUFFIX[family]
|
||||
out = [
|
||||
"",
|
||||
f"/// {family} encodings of registry forms (operand rule `{rule_name}`).",
|
||||
"#[derive(Clone, Copy, Debug, Eq, PartialEq)]",
|
||||
f"pub enum {enum} {{",
|
||||
]
|
||||
for variant in variants:
|
||||
out += [
|
||||
f" /// `{variant['of'].lower()}{suffix}` ({family} opcode {variant['opcode']}).",
|
||||
f" {variant_of[variant['of']]},",
|
||||
]
|
||||
out += [
|
||||
"}",
|
||||
"",
|
||||
f"impl {enum} {{",
|
||||
f" /// Selects the operation from the first word of its {family} encoding (operand",
|
||||
f" /// rule `{rule_name}`): the encoding bits (mask 0x{fixed_mask:09_x}) and then",
|
||||
f" /// the OP field (bits {offset}-{offset + size - 1}). `None` for undeclared opcodes.",
|
||||
f" pub const fn from_{lower}_word(word: u32) -> Option<Self> {{",
|
||||
" /// Every variant, in registry order.",
|
||||
f" pub const ALL: [Self; {len(variants)}] = [",
|
||||
]
|
||||
out += [f" Self::{variant_of[variant['of']]}," for variant in variants]
|
||||
out += [
|
||||
" ];",
|
||||
"",
|
||||
f" /// Selects the variant from the first word of its {family} encoding: the",
|
||||
f" /// encoding bits (mask 0x{fixed_mask:09_x}) and then the OP field (bits",
|
||||
f" /// {offset}-{offset + size - 1}). `None` for undeclared opcodes.",
|
||||
" pub const fn from_word(word: u32) -> Option<Self> {",
|
||||
f" if word & 0x{fixed_mask:09_x} != 0x{fixed_bits:09_x} {{",
|
||||
" return None;",
|
||||
" }",
|
||||
@@ -929,16 +979,39 @@ def _render_variants(rule_name, variants, registry, snapshot):
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
f" /// Assembler name of the {family} encoding, as LLVM prints it, if declared.",
|
||||
f" pub const fn {lower}_assembly_name(self) -> Option<&'static str> {{",
|
||||
" /// The form this encodes, whose declaration it inherits.",
|
||||
f" pub const fn base(self) -> {base_enum} {{",
|
||||
" match self {",
|
||||
]
|
||||
out += [
|
||||
f" Self::{variant_of[row['of']]} => "
|
||||
f"Some(\"{row['of'].lower()}{ASSEMBLY_SUFFIX[family]}\"),"
|
||||
for row in variants
|
||||
f" Self::{variant_of[variant['of']]} => {base_enum}::{variant_of[variant['of']]},"
|
||||
for variant in variants
|
||||
]
|
||||
out += [" #[allow(unreachable_patterns)]", " _ => None,", " }", " }", "}"]
|
||||
out += [
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
f" /// Assembler name of the {family} encoding, as LLVM prints it.",
|
||||
" pub const fn assembly_name(self) -> &'static str {",
|
||||
" match self {",
|
||||
]
|
||||
out += [
|
||||
f" Self::{variant_of[variant['of']]} => \"{variant['of'].lower()}{suffix}\","
|
||||
for variant in variants
|
||||
]
|
||||
out += [
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
" /// The validated registry row of this encoding.",
|
||||
" pub fn semantics(self) -> &'static FormSemantics {",
|
||||
" &FORMS[match self {",
|
||||
]
|
||||
out += [
|
||||
f" Self::{variant_of[variant['of']]} => {positions[(variant['of'], variant['family'])]},"
|
||||
for variant in variants
|
||||
]
|
||||
out += [" }]", " }", "}"]
|
||||
return out
|
||||
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ pub use rdna2::{
|
||||
V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32,
|
||||
};
|
||||
pub use semantics_gen::{
|
||||
ScalarAluOp, ScalarCompareOp, ScalarUnaryOp, VectorAluOp, VectorCompareOp,
|
||||
ScalarAluOp, ScalarCompareOp, ScalarUnaryOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp,
|
||||
};
|
||||
|
||||
/// SGPR index of `vcc_lo`, the Wave32 vector condition code.
|
||||
@@ -157,7 +157,7 @@ pub enum Instruction {
|
||||
/// VOP3 encoding of a registry VOP2 integer operation (operand rule
|
||||
/// `vop3_vgpr2`): two VGPR sources and no input or output modifiers.
|
||||
VectorAluVop3 {
|
||||
op: VectorAluOp,
|
||||
op: VectorAluVop3Op,
|
||||
dst: u8,
|
||||
src0: u8,
|
||||
src1: u8,
|
||||
@@ -277,9 +277,7 @@ impl Instruction {
|
||||
Self::WaitLoad => "s_waitcnt",
|
||||
Self::WaitStore => "s_waitcnt_vscnt",
|
||||
Self::MoveB32 { .. } => "v_mov_b32_e32",
|
||||
Self::VectorAluVop3 { op, .. } => op
|
||||
.vop3_assembly_name()
|
||||
.expect("decoded VOP3 variants have a VOP3 name"),
|
||||
Self::VectorAluVop3 { op, .. } => op.assembly_name(),
|
||||
Self::ScalarMoveB32 { .. } => "s_mov_b32",
|
||||
Self::ScalarUnary { op, .. } => op.mnemonic(),
|
||||
Self::ScalarAlu { op, .. } => op.mnemonic(),
|
||||
|
||||
@@ -1872,11 +1872,23 @@ impl VectorCompareOp {
|
||||
}
|
||||
}
|
||||
|
||||
impl VectorAluOp {
|
||||
/// Selects the operation from the first word of its VOP3 encoding (operand
|
||||
/// rule `vop3_vgpr2`): the encoding bits (mask 0xfc00_0000) and then
|
||||
/// the OP field (bits 16-25). `None` for undeclared opcodes.
|
||||
pub const fn from_vop3_word(word: u32) -> Option<Self> {
|
||||
/// VOP3 encodings of registry forms (operand rule `vop3_vgpr2`).
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum VectorAluVop3Op {
|
||||
/// `v_add_nc_u32_e64` (VOP3 opcode 293).
|
||||
AddNcU32,
|
||||
}
|
||||
|
||||
impl VectorAluVop3Op {
|
||||
/// Every variant, in registry order.
|
||||
pub const ALL: [Self; 1] = [
|
||||
Self::AddNcU32,
|
||||
];
|
||||
|
||||
/// Selects the variant from the first word of its VOP3 encoding: the
|
||||
/// encoding bits (mask 0xfc00_0000) and then the OP field (bits
|
||||
/// 16-25). `None` for undeclared opcodes.
|
||||
pub const fn from_word(word: u32) -> Option<Self> {
|
||||
if word & 0xfc00_0000 != 0xd400_0000 {
|
||||
return None;
|
||||
}
|
||||
@@ -1886,14 +1898,26 @@ impl VectorAluOp {
|
||||
}
|
||||
}
|
||||
|
||||
/// Assembler name of the VOP3 encoding, as LLVM prints it, if declared.
|
||||
pub const fn vop3_assembly_name(self) -> Option<&'static str> {
|
||||
/// The form this encodes, whose declaration it inherits.
|
||||
pub const fn base(self) -> VectorAluOp {
|
||||
match self {
|
||||
Self::AddNcU32 => Some("v_add_nc_u32_e64"),
|
||||
#[allow(unreachable_patterns)]
|
||||
_ => None,
|
||||
Self::AddNcU32 => VectorAluOp::AddNcU32,
|
||||
}
|
||||
}
|
||||
|
||||
/// Assembler name of the VOP3 encoding, as LLVM prints it.
|
||||
pub const fn assembly_name(self) -> &'static str {
|
||||
match self {
|
||||
Self::AddNcU32 => "v_add_nc_u32_e64",
|
||||
}
|
||||
}
|
||||
|
||||
/// The validated registry row of this encoding.
|
||||
pub fn semantics(self) -> &'static FormSemantics {
|
||||
&FORMS[match self {
|
||||
Self::AddNcU32 => 84,
|
||||
}]
|
||||
}
|
||||
}
|
||||
|
||||
/// Identity of every registry form and encoding variant, in registry order.
|
||||
|
||||
@@ -5,7 +5,8 @@ use xenora_isa::semantics::{
|
||||
CarryIn, FORM_IDS, FORMS, GENERATED_SCHEMA, MaskEffect, SCHEMA, SccEffect, Signedness, Wave,
|
||||
};
|
||||
use xenora_isa::{
|
||||
CompareRelation, ScalarAluOp, ScalarCompareOp, ScalarUnaryOp, VectorAluOp, VectorCompareOp,
|
||||
CompareRelation, ScalarAluOp, ScalarCompareOp, ScalarUnaryOp, VectorAluOp, VectorAluVop3Op,
|
||||
VectorCompareOp,
|
||||
};
|
||||
|
||||
#[test]
|
||||
@@ -163,15 +164,9 @@ fn vector_compare_dispatch_selects_exactly_the_registry_vopc_forms() {
|
||||
|
||||
#[test]
|
||||
fn vop3_variant_dispatch_selects_exactly_the_registry_vop3_rows() {
|
||||
for row in FORMS
|
||||
.iter()
|
||||
.filter(|row| row.family == EncodingFamily::Vop3)
|
||||
{
|
||||
let op = VectorAluOp::ALL
|
||||
.into_iter()
|
||||
.find(|op| op.semantics().name == row.name)
|
||||
.unwrap_or_else(|| panic!("{} has no base VOP2 form", row.name));
|
||||
let base = op.semantics();
|
||||
for op in VectorAluVop3Op::ALL {
|
||||
let (row, base) = (op.semantics(), op.base().semantics());
|
||||
assert_eq!((row.name, row.family), (base.name, EncodingFamily::Vop3));
|
||||
// The variant inherits the base declaration; only identity and the
|
||||
// operand rule differ.
|
||||
assert_eq!(
|
||||
@@ -184,12 +179,23 @@ fn vop3_variant_dispatch_selects_exactly_the_registry_vop3_rows() {
|
||||
),
|
||||
(row.operation, row.signedness, row.scc, row.vcc, row.exec)
|
||||
);
|
||||
assert_eq!(
|
||||
op.vop3_assembly_name(),
|
||||
Some(format!("{}_e64", op.mnemonic()).as_str())
|
||||
);
|
||||
assert_eq!(row.swap_sources, base.swap_sources);
|
||||
assert_eq!(op.assembly_name(), format!("{}_e64", op.base().mnemonic()));
|
||||
}
|
||||
dispatch_selects_exactly(EncodingFamily::Vop3, |word| {
|
||||
VectorAluOp::from_vop3_word(word).map(|op| op.semantics().name)
|
||||
VectorAluVop3Op::from_word(word).map(|op| op.semantics().name)
|
||||
});
|
||||
// No first word of the other 64-bit families (VOP3B shares VOP3's
|
||||
// encoding bits) selects a variant.
|
||||
for meta in META_FORMS
|
||||
.iter()
|
||||
.filter(|form| form.family != EncodingFamily::Vop3 && form.bytes == 8)
|
||||
{
|
||||
assert_eq!(
|
||||
VectorAluVop3Op::from_word(meta.bits as u32),
|
||||
None,
|
||||
"{}",
|
||||
meta.name
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,7 @@ pub use graphics::{PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics};
|
||||
|
||||
pub use xenora_decoder::Architecture;
|
||||
use xenora_decoder::{
|
||||
DecodeError, DecodedInstruction, Instruction, ScalarSource, VectorAluOp, VectorBinary,
|
||||
DecodeError, DecodedInstruction, Instruction, ScalarSource, VectorAluVop3Op, VectorBinary,
|
||||
VectorCompareOp, VectorSource,
|
||||
};
|
||||
|
||||
@@ -685,7 +685,7 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
|
||||
Instruction::MoveB32 { dst, .. }
|
||||
// Of the VOP3 variants, the contract admits only v_add_nc_u32_e64.
|
||||
| Instruction::VectorAluVop3 {
|
||||
op: VectorAluOp::AddNcU32,
|
||||
op: VectorAluVop3Op::AddNcU32,
|
||||
dst,
|
||||
..
|
||||
}
|
||||
@@ -840,6 +840,7 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
|
||||
src0,
|
||||
src1,
|
||||
} => {
|
||||
let op = op.base();
|
||||
let (left, right) = if op.swaps_sources() {
|
||||
(read(src1)?, read(src0)?)
|
||||
} else {
|
||||
|
||||
@@ -33,7 +33,7 @@ ignored.
|
||||
Sources are normal SGPRs, inline integers (-16 to 64) or one literal word.
|
||||
|
||||
These forms are declared as data in the semantic registry,
|
||||
`crates/isa/semantics/rdna2.toml`: opcode, operation, signedness, carry-in,
|
||||
`crates/isa/semantics/rdna2/sop2.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
|
||||
|
||||
@@ -13,7 +13,7 @@ The registry covers the nine SOP2 forms listed in [SOP2 scalar ALU](scalar-alu.m
|
||||
| File | Role |
|
||||
| --- | --- |
|
||||
| `crates/isa/semantics/rdna2.toml` | The registry root: schema, architecture, the snapshot hash, the cited documents and the ordered `include` list of family files. |
|
||||
| `crates/isa/semantics/rdna2/<family>.toml` | One file per encoding family (`sop2.toml`, `sopc.toml`, `sop1.toml`, `vop2.toml`, `vopc.toml`): that family's operand rules and forms only. Data only: every value comes from a closed vocabulary. |
|
||||
| `crates/isa/semantics/rdna2/<family>.toml` | One file per encoding family (`sop2.toml`, `sopc.toml`, `sop1.toml`, `vop2.toml`, `vopc.toml`, `vop3.toml`): that family's operand rules, forms and encoding variants only. 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. |
|
||||
@@ -27,10 +27,12 @@ The root lists its family files under `include`. The generator merges them in
|
||||
that order, and forms keep their order within each file, so the merged registry
|
||||
equals one file with the parts concatenated (splitting the original single file
|
||||
left `semantics_gen.rs` byte-identical). A family file may hold only
|
||||
`[operand_rules.*]` and `[[form]]` entries of the family it is named after:
|
||||
`rdna2/vop2.toml` holds VOP2 rules and forms and nothing else. The loader
|
||||
rejects a form or rule of another family, a rule declared in two files, root
|
||||
keys in a family file, and a missing or repeated include. Work on different
|
||||
`[operand_rules.*]`, `[[form]]` and `[[encoding_variant]]` entries of the family
|
||||
it is named after: `rdna2/vop2.toml` holds VOP2 rules and forms and nothing else.
|
||||
Each include must be `rdna2/<lower-case family>.toml`. The loader rejects a form,
|
||||
rule or variant of another family, a rule declared in two files, root keys in a
|
||||
family file, any other include path, and a missing or repeated include. The
|
||||
coverage report and the RDNA2 planner use the same loader. Work on different
|
||||
families therefore never edits the same registry file. To add a family, create
|
||||
`rdna2/<family>.toml` and append it to `include`; the generated order (and so
|
||||
the generated file) changes only where the new file is placed.
|
||||
@@ -52,9 +54,13 @@ file of its encoding (`rdna2/vop3.toml`) and has exactly these fields:
|
||||
Everything else (operation, signedness, effects, source order) is inherited
|
||||
from the base form, and the XML check runs on that inherited declaration with
|
||||
the variant's family, opcode and operand rule, so the VOP3 operand widths and
|
||||
formats must agree with it. The generator emits, on the base enum,
|
||||
`from_<family>_word` (encoding bits, then an explicit match on the OP field) and
|
||||
`<family>_assembly_name`, and one `FORMS` row per variant after the forms. A
|
||||
formats must agree with it. The generator emits one enum per variant rule (`VectorAluVop3Op` for
|
||||
`vop3_vgpr2`) holding exactly the declared variants, with `from_word` (encoding
|
||||
bits, then an explicit match on the OP field), `base()` (the inherited form),
|
||||
`assembly_name()` and `semantics()`, and one `FORMS` row per variant after the
|
||||
forms. Because the enum has no undeclared members, an instruction cannot name a
|
||||
VOP3 encoding that does not exist. Every explicit XML operand of the variant,
|
||||
destination included, must have the base encoding's data format. A
|
||||
variant-only rule (one marked `variant_of` in the generator) cannot be used by a
|
||||
form. The validator rejects a variant of an undeclared form, one in the form's
|
||||
own family, a duplicate encoding of a form or a duplicate `(family, opcode)`, a
|
||||
|
||||
@@ -143,21 +143,21 @@ def parse_generated(source):
|
||||
|
||||
|
||||
def load_registry(path):
|
||||
"""The root registry with its `include`d family files merged in order.
|
||||
"""The root registry with its family files merged, by the generator's loader.
|
||||
|
||||
Only the merge is done here; crates/isa/generate_semantics.py validates
|
||||
which family each file may hold.
|
||||
One loader for every consumer, so the family-file guards (one family per
|
||||
file, include paths, duplicates) apply here too.
|
||||
"""
|
||||
registry = tomllib.loads(path.read_text(encoding="utf-8"))
|
||||
for include in registry.pop("include", []):
|
||||
part = tomllib.loads((path.parent / include).read_text(encoding="utf-8"))
|
||||
for name, rule in part.get("operand_rules", {}).items():
|
||||
if name in registry.setdefault("operand_rules", {}):
|
||||
raise ValueError(f"{REGISTRY}: operand rule {name} is declared twice")
|
||||
registry["operand_rules"][name] = rule
|
||||
registry.setdefault("form", []).extend(part.get("form", []))
|
||||
registry.setdefault("encoding_variant", []).extend(part.get("encoding_variant", []))
|
||||
return registry
|
||||
import importlib.util
|
||||
|
||||
script = ROOT / "crates/isa/generate_semantics.py"
|
||||
spec = importlib.util.spec_from_file_location("generate_semantics", script)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
try:
|
||||
return module.load_registry(path)
|
||||
except module.RegistryError as error:
|
||||
raise ValueError(f"{REGISTRY}: {error}") from error
|
||||
|
||||
|
||||
def read_declarations(registry, identified):
|
||||
|
||||
@@ -200,6 +200,10 @@ def classify_unsupported(
|
||||
registry = data["registry"]
|
||||
rules = data["rules"]
|
||||
ops = _declared_ops(registry)
|
||||
form_rules = {form.get("operands") for form in registry.get("form", [])}
|
||||
variant_only_rules = {
|
||||
variant.get("operands") for variant in registry.get("encoding_variant", [])
|
||||
} - form_rules
|
||||
family_widths: dict[str, set[int]] = defaultdict(set)
|
||||
family_types: dict[str, set[str]] = defaultdict(set)
|
||||
for form in registry.get("form", []):
|
||||
@@ -221,7 +225,11 @@ def classify_unsupported(
|
||||
continue
|
||||
opcode = identified[(family, name)]
|
||||
reusable = sorted(op for op in ops if op)
|
||||
family_rule_names = [n for n, (fam, _) in rules.items() if fam == family]
|
||||
# Rules that only encoding variants use (another encoding of an already
|
||||
# declared form) cannot host a new form, so they do not count here.
|
||||
family_rule_names = [
|
||||
n for n, (fam, _) in rules.items() if fam == family and n not in variant_only_rules
|
||||
]
|
||||
missing_rules = []
|
||||
if not family_rule_names:
|
||||
missing_rules.append(f"no operand_rules for family {family}")
|
||||
|
||||
@@ -66,6 +66,20 @@ class Rdna2Plan(unittest.TestCase):
|
||||
ranks = [c.priority_rank for c in mixed]
|
||||
self.assertEqual(ranks, sorted(ranks))
|
||||
|
||||
def test_variant_only_rules_do_not_make_a_family_reuse_ready(self):
|
||||
# A rule that only encoding variants use (vop3_vgpr2 re-encodes declared
|
||||
# VOP2 forms) cannot host a new VOP3 form such as V_FMA_F32.
|
||||
variant_rules = {
|
||||
variant["operands"] for variant in self.data["registry"].get("encoding_variant", [])
|
||||
}
|
||||
if not variant_rules:
|
||||
self.skipTest("no encoding variants declared")
|
||||
vop3 = classify_unsupported(self.data, families=["VOP3"])
|
||||
self.assertTrue(vop3)
|
||||
for cand in vop3:
|
||||
self.assertNotIn(cand.operand_layout, variant_rules, cand.name)
|
||||
self.assertNotEqual(cand.status, "reuse-primitives", cand.name)
|
||||
|
||||
def test_manifests_exclude_claims_and_stay_deterministic(self):
|
||||
cands = classify_unsupported(self.data, statuses=["reuse-primitives"], limit=50)
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from audit import semantic_coverage as coverage
|
||||
|
||||
@@ -113,5 +115,23 @@ class SemanticCoverageTests(unittest.TestCase):
|
||||
coverage.parse_decoder(f"{header}\n unknown!(),\n];")
|
||||
|
||||
|
||||
class RegistryLoading(unittest.TestCase):
|
||||
def test_family_file_guards_apply_to_the_report(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp) / "rdna2.toml"
|
||||
(Path(tmp) / "rdna2").mkdir()
|
||||
root.write_text('schema = 1\ninclude = ["rdna2/sop2.toml"]\n', encoding="utf-8")
|
||||
(Path(tmp) / "rdna2" / "sop2.toml").write_text(
|
||||
'[[form]]\nname = "V_X"\nfamily = "VOP2"\n', encoding="utf-8"
|
||||
)
|
||||
with self.assertRaisesRegex(ValueError, "form V_X is not a SOP2 form"):
|
||||
coverage.load_registry(root)
|
||||
|
||||
def test_loads_the_real_split_registry(self):
|
||||
registry = coverage.load_registry(coverage.ROOT / coverage.REGISTRY)
|
||||
self.assertNotIn("include", registry)
|
||||
self.assertGreater(len(registry["form"]), 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -876,12 +876,31 @@ class Validate(unittest.TestCase):
|
||||
row[1] = U32
|
||||
self.rejects(variants(), "V_MIN_I32: signedness signed contradicts XML format FMT_NUM_U32", snap)
|
||||
|
||||
def test_rejects_a_variant_destination_format_that_differs_from_the_form(self):
|
||||
snap = snapshot()
|
||||
snap["variants"][("V_MIN_I32", "ENC_VOP3")]["operands"][0][1] = "FMT_NUM_F32"
|
||||
self.rejects(
|
||||
variants(),
|
||||
"V_MIN_I32 (VOP3): XML operand formats ['FMT_NUM_F32', 'FMT_NUM_I32', 'FMT_NUM_I32'] "
|
||||
"differ from the form's ['FMT_NUM_I32', 'FMT_NUM_I32', 'FMT_NUM_I32']",
|
||||
snap,
|
||||
)
|
||||
|
||||
def test_rejects_malformed_variant_fields_without_a_traceback(self):
|
||||
for key in ("of", "operands", "family"):
|
||||
with self.subTest(key=key):
|
||||
reg = variants()
|
||||
reg["encoding_variant"][0][key] = []
|
||||
self.rejects(reg, f"[{key!r}] must be strings")
|
||||
|
||||
def test_renders_variant_dispatch_and_rows(self):
|
||||
text = gen.render(variants(), snapshot())
|
||||
self.assertIn("pub const fn from_vop3_word(word: u32) -> Option<Self> {", text)
|
||||
self.assertIn("pub enum VectorAluVop3Op {", text)
|
||||
self.assertIn("pub const fn from_word(word: u32) -> Option<Self> {", text.split("pub enum VectorAluVop3Op", 1)[1])
|
||||
self.assertIn("if word & 0xfc00_0000 != 0xd400_0000 {", text)
|
||||
self.assertIn("273 => Some(Self::AddU32),", text) # V_MIN_I32's variant name
|
||||
self.assertIn('Self::SubrevNcU32 => Some("v_subrev_nc_u32_e64"),', text)
|
||||
self.assertIn("Self::AddU32 => VectorAluOp::AddU32,", text)
|
||||
self.assertIn('Self::SubrevNcU32 => "v_subrev_nc_u32_e64",', text)
|
||||
self.assertIn('("V_MIN_I32", EncodingFamily::Vop3),', text)
|
||||
self.assertIn("operands: OperandRule::Vop3Vgpr2,", text)
|
||||
# The VOP3 row inherits SUBREV's reversed sources.
|
||||
@@ -1210,6 +1229,13 @@ class LoadRegistry(unittest.TestCase):
|
||||
root = self.write('include = ["rdna2/sop2.toml"]\n', {"sop2.toml": "schema = 1\n"})
|
||||
self.fails(root, "rdna2/sop2.toml: keys ['schema'] belong in the root file")
|
||||
|
||||
def test_rejects_includes_outside_the_family_directory(self):
|
||||
for include in ("../sop2.toml", "./rdna2/sop2.toml", "other/sop2.toml", "rdna2/SOP2.toml",
|
||||
"rdna2/sub/sop2.toml"):
|
||||
with self.subTest(include=include):
|
||||
root = self.write(f'include = ["{include}"]\n', {"sop2.toml": ""})
|
||||
self.fails(root, f"include {include!r} is not rdna2/<family>.toml")
|
||||
|
||||
def test_rejects_a_missing_or_repeated_include(self):
|
||||
self.fails(self.write('include = ["rdna2/sop2.toml"]\n', {}), "included family file rdna2/sop2.toml does not exist")
|
||||
root = self.write('include = ["rdna2/sop2.toml", "rdna2/sop2.toml"]\n', {"sop2.toml": ""})
|
||||
|
||||
Reference in new issue
Block a user