From 544ee8de83611007b821504b758d315f029a1370 Mon Sep 17 00:00:00 2001 From: elforeign <324243036+elforeign@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:33:50 -0600 Subject: [PATCH 01/15] isa, decoder, shader: move the twelve Wave32 VOPC compares into the semantic registry (#215) The v_cmp_{lt,eq,le,gt,ne,ge}_{i32,u32}_e32 forms from #239 are now registry data under a new vopc_vcc operand rule (SRC0 a vector_source, VSRC1 a VGPR, destination implicitly vcc_lo). The decoder dispatches them through the generated VectorCompareOp instead of a hand-written opcode table, and the hand-written VectorCompareOp struct in xenora-isa is gone. No behaviour change: goldens, known answers and the LLVM oracle are unchanged. The vocabulary gains vcc = "lane_mask", allowed exactly for the VOPC rule and required to account for the XML's implicit VCC output, and wave = "wave32", now allowed exactly for that rule (its one entry point is the Wave32 compute fixture ABI) and still rejected elsewhere. exec must stay unchanged, so v_cmpx cannot be declared. Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com> --- crates/decoder/src/lib.rs | 44 +- crates/decoder/tests/gfx1030.rs | 4 +- crates/isa/generate_semantics.py | 95 ++- crates/isa/semantics/rdna2.toml | 273 ++++++- crates/isa/src/lib.rs | 67 +- crates/isa/src/semantics.rs | 10 +- crates/isa/src/semantics_gen.rs | 694 +++++++++++++++++- crates/isa/tests/semantics.rs | 59 +- crates/shader/src/lib.rs | 6 +- docs/shaders/semantic-coverage.md | 5 +- docs/shaders/semantic-registry.md | 16 +- docs/shaders/vector-compare.md | 3 + .../test_generate_semantics.py | 105 ++- 13 files changed, 1245 insertions(+), 136 deletions(-) diff --git a/crates/decoder/src/lib.rs b/crates/decoder/src/lib.rs index 8896435..d259189 100644 --- a/crates/decoder/src/lib.rs +++ b/crates/decoder/src/lib.rs @@ -9,10 +9,8 @@ pub use xenora_isa::{ use xenora_isa::{ BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_BRANCH, S_CBRANCH_EXECZ, S_CBRANCH_SCC0, S_CBRANCH_VCCZ, 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, VCC_LO, + V_ADD_NC_U32, V_AND_B32, V_ASHRREV_I32, 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, VCC_LO, }; use xenora_isa::meta::EncodingFamily; @@ -42,7 +40,7 @@ const fn concat_forms() -> [(&'static str, EncodingFamily); N] { } /// Decoded forms not yet described by the semantic registry. -const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 36] = [ +const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 24] = [ ("BUFFER_LOAD_DWORD", EncodingFamily::Mubuf), ("BUFFER_STORE_DWORD", EncodingFamily::Mubuf), ("EXP", EncodingFamily::Exp), @@ -59,18 +57,6 @@ const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 36] = [ ("V_ADD_NC_U32", EncodingFamily::Vop3), ("V_AND_B32", EncodingFamily::Vop2), ("V_ASHRREV_I32", EncodingFamily::Vop2), - ("V_CMP_EQ_I32", EncodingFamily::Vopc), - ("V_CMP_EQ_U32", EncodingFamily::Vopc), - ("V_CMP_GE_I32", EncodingFamily::Vopc), - ("V_CMP_GE_U32", EncodingFamily::Vopc), - ("V_CMP_GT_I32", EncodingFamily::Vopc), - ("V_CMP_GT_U32", EncodingFamily::Vopc), - ("V_CMP_LE_I32", EncodingFamily::Vopc), - ("V_CMP_LE_U32", EncodingFamily::Vopc), - ("V_CMP_LT_I32", EncodingFamily::Vopc), - ("V_CMP_LT_U32", EncodingFamily::Vopc), - ("V_CMP_NE_I32", EncodingFamily::Vopc), - ("V_CMP_NE_U32", EncodingFamily::Vopc), ("V_INTERP_P1_F32", EncodingFamily::Vintrp), ("V_INTERP_P2_F32", EncodingFamily::Vintrp), ("V_LSHLREV_B32", EncodingFamily::Vop2), @@ -338,26 +324,8 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco if V_MOV_B32.matches(first) { return move_b32(first, bytes); } - { - use CompareRelation::{Equal, Greater, GreaterOrEqual, Less, LessOrEqual, NotEqual}; - for (opcode, relation, signed) in [ - (V_CMP_LT_I32, Less, true), - (V_CMP_EQ_I32, Equal, true), - (V_CMP_LE_I32, LessOrEqual, true), - (V_CMP_GT_I32, Greater, true), - (V_CMP_NE_I32, NotEqual, true), - (V_CMP_GE_I32, GreaterOrEqual, true), - (V_CMP_LT_U32, Less, false), - (V_CMP_EQ_U32, Equal, false), - (V_CMP_LE_U32, LessOrEqual, false), - (V_CMP_GT_U32, Greater, false), - (V_CMP_NE_U32, NotEqual, false), - (V_CMP_GE_U32, GreaterOrEqual, false), - ] { - if opcode.matches(first) { - return vector_compare(VectorCompareOp { relation, signed }, first, bytes); - } - } + if let Some(op) = VectorCompareOp::from_word(first) { + return vector_compare(op, first, bytes); } if V_ADD_NC_U32.matches(first) { let len = V_ADD_NC_U32.byte_len(); @@ -715,7 +683,7 @@ fn vector_compare( bytes: &[u8], ) -> Result<(Instruction, u8), DecodeErrorKind> { let src1 = ((first >> 9) & 0xff) as u8; - let (src0, len) = vector_src0(first, bytes, op.mnemonic())?; + let (src0, len) = vector_src0(first, bytes, op.assembly_name())?; Ok((Instruction::VectorCompare { op, src0, src1 }, len)) } diff --git a/crates/decoder/tests/gfx1030.rs b/crates/decoder/tests/gfx1030.rs index 3fa797f..257ee62 100644 --- a/crates/decoder/tests/gfx1030.rs +++ b/crates/decoder/tests/gfx1030.rs @@ -454,7 +454,7 @@ fn reference_op(instruction: Instruction) -> Op { Instruction::VectorCompare { op, src0, src1 } => Op::Compare( Comparison { - offset: match op.relation { + offset: match op.relation() { CompareRelation::Less => 1, CompareRelation::Equal => 2, CompareRelation::LessOrEqual => 3, @@ -462,7 +462,7 @@ fn reference_op(instruction: Instruction) -> Op { CompareRelation::NotEqual => 5, CompareRelation::GreaterOrEqual => 6, }, - signed: op.signed, + signed: op.signed(), }, match src0 { VectorSource::Register(reg) => CompareSource::Vector(reg), diff --git a/crates/isa/generate_semantics.py b/crates/isa/generate_semantics.py index 2d16376..4612a69 100755 --- a/crates/isa/generate_semantics.py +++ b/crates/isa/generate_semantics.py @@ -113,11 +113,16 @@ SCC = { "relation": "Relation", "selected_src0": "SelectedSrc0", } -MASK = {"unchanged": "Unchanged"} +# lane_mask: the Wave32 VOPC result written to VCC_LO (vcc only; EXEC writes +# such as v_cmpx have no contract yet, so exec must stay unchanged). +MASK = {"unchanged": "Unchanged", "lane_mask": "LaneMask"} 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"} +# Which wave declaration each operand-rule kind must make. The decoder has no +# wave-size input, so "wave32" is only true where the caller's ABI fixes the +# wave size: the lane-mask compares, whose one entry point is the Wave32 +# compute fixture ABI (docs/shaders/vector-compare.md section 2). Every other +# kind must be "any". +WAVE_BY_KIND = {"vector_compare": "wave32"} EVIDENCE = { "reference": "Reference", "independent": "Independent", @@ -253,6 +258,25 @@ OPERAND_RULES = { "unsupported": {combo for combo in UNSUPPORTED_COMBOS if combo != "two_literals"}, "kind": "unary", }, + "vopc_vcc": { + "rust": "VopcVcc", + "enum": "VectorCompareOp", + "shape": { + "family": "VOPC", + "src": [ + {"field": "SRC0", "class": "vector_source"}, + {"field": "VSRC1", "class": "vgpr"}, + ], + "max_literals": 1, + }, + # The destination is implicitly vcc_lo; the decoder rejects these SRC0 + # selectors (the same vector_source as VOP2). + "unsupported": { + "src_vcc_hi", "src_exec", "src_m0", "src_ttmp", "src_null", "src_float_inline", + "src_special", + }, + "kind": "vector_compare", + }, "vop2_vgpr": { "rust": "Vop2Vgpr", "enum": "VectorAluOp", @@ -364,8 +388,12 @@ def _check_xml(form, rule, snapshot, errors): operands[field] = (data_format, size, is_input, is_output) else: implicit.add(kind) - # The vocabulary can state only SCC effects (vcc and exec are "unchanged"), - # so any other implicit XML operand, such as VCC, is undeclared. + # The vocabulary states SCC effects and a lane-mask VCC write; any other + # implicit XML operand (such as an EXEC write) is undeclared. + if form["vcc"] == "lane_mask": + if "OPR_VCC" not in implicit: + errors.append(f"{label}: vcc lane_mask but the XML has no implicit VCC output") + implicit.discard("OPR_VCC") if implicit: errors.append(f"{label}: XML implicit operands {sorted(implicit)} are not declared") if scc_in != (form["carry_in"] == "scc"): @@ -471,8 +499,17 @@ def validate(registry, snapshot): 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") + wave = WAVE_BY_KIND.get(_rule_kind(form), "any") + if form["wave"] in WAVE and form["wave"] != wave: + errors.append(f"{label}: wave {form['wave']} is not enforced for this rule (requires {wave})") + lane_mask = _rule_kind(form) == "vector_compare" + if form["vcc"] in MASK and (form["vcc"] == "lane_mask") != lane_mask: + errors.append( + f"{label}: vcc {form['vcc']} contradicts rule {form['operands']} " + f"(requires {'lane_mask' if lane_mask else 'unchanged'})" + ) + if form["exec"] != "unchanged": + errors.append(f"{label}: exec {form['exec']} has no contract (requires unchanged)") 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 ( @@ -527,11 +564,13 @@ def validate(registry, snapshot): errors.append(f"{label}: unknown or missing {RELATION_KEY} {relation!r}") elif (relation, form["signedness"]) not in COMPARE_PRIMITIVES: errors.append(f"{label}: no primitive implements {relation}/{form['signedness']}") - if form["scc"] != "relation": - errors.append(f"{label}: scc {form['scc']} contradicts compare (requires relation)") + # SOPC compares write SCC; VOPC compares write VCC and leave SCC. + scc = "unchanged" if _rule_kind(form) == "vector_compare" else "relation" + if form["scc"] != scc: + errors.append(f"{label}: scc {form['scc']} contradicts compare (requires {scc})") if form["carry_in"] != "none": errors.append(f"{label}: carry_in {form['carry_in']} contradicts compare") - primitive = ("relation", None, False) + primitive = (scc, None, False) elif _rule_kind(form) == "vector": if RELATION_KEY in form: errors.append(f"{label}: {RELATION_KEY} on a non-compare operation") @@ -558,7 +597,8 @@ def validate(registry, snapshot): elif rule.get("family") != form["family"]: errors.append(f"{label}: operand rule {form['operands']} is for {rule.get('family')}") elif form["operands"] in OPERAND_RULES and OPERAND_RULES[form["operands"]]["kind"] != ( - "compare" if form["operation"] == "compare" + ("vector_compare" if _rule_kind(form) == "vector_compare" else "compare") + if form["operation"] == "compare" else "unary" if form["operation"] in UNARY else "vector" if _rule_kind(form) == "vector" and form["operation"] not in UNARY else "alu" @@ -707,10 +747,11 @@ def _render_enum(rule_name, forms, snapshot, positions): ] for form in forms: carry = " plus SCC" if form["carry_in"] == "scc" else "" - what = f"compare {form[RELATION_KEY]}" if kind == "compare" else form["operation"] + what = f"compare {form[RELATION_KEY]}" if RELATION_KEY in form else form["operation"] + effect = f"VCC = {form['vcc']}" if form["vcc"] != "unchanged" else f"SCC = {form['scc']}" out += [ f" /// `{form['name'].lower()}` ({family} opcode {form['opcode']}): " - f"{form['signedness']} {what}{carry}, SCC = {form['scc']}.", + f"{form['signedness']} {what}{carry}, {effect}.", f" {form['variant']},", ] by_opcode = {form["opcode"]: form["variant"] for form in forms} @@ -834,7 +875,29 @@ def _render_enum(rule_name, forms, snapshot, positions): ] out += [" }", " }", "}"] return out - if kind == "compare": + if kind == "vector_compare": + out += [ + "", + " /// Assembler name of the 32-bit (VOPC) encoding, as LLVM prints it.", + " pub const fn assembly_name(self) -> &'static str {", + " match self {", + ] + out += [f" Self::{form['variant']} => \"{form['name'].lower()}_e32\"," for form in forms] + out += [ + " }", + " }", + "", + " /// Whether the operands compare as two's-complement values.", + " pub const fn signed(self) -> bool {", + " match self {", + ] + out += [ + f" Self::{form['variant']} => {'true' if form['signedness'] == 'signed' else 'false'}," + for form in forms + ] + out += [" }", " }"] + if kind in ("compare", "vector_compare"): + result = "SCC" if kind == "compare" else "per-lane result" out += [ "", " /// The relation tested, with S0 on the left.", @@ -849,7 +912,7 @@ def _render_enum(rule_name, forms, snapshot, positions): " }", " }", "", - " /// The new SCC: whether the relation holds for S0 and S1.", + f" /// The {result}: whether the relation holds for S0 and S1.", " pub const fn test(self, src0: u32, src1: u32) -> bool {", " match self {", ] diff --git a/crates/isa/semantics/rdna2.toml b/crates/isa/semantics/rdna2.toml index 2b05269..eba44be 100644 --- a/crates/isa/semantics/rdna2.toml +++ b/crates/isa/semantics/rdna2.toml @@ -54,8 +54,8 @@ unsupported = [ # carry_in none | scc (scc for unsigned add/sub carry and the cselect condition) # width operand and result width in bits # scc unchanged | carry_out | borrow | signed_overflow | nonzero | relation | selected_src0 -# vcc, exec unchanged (stated, not implied) -# wave any | wave32 +# vcc, exec unchanged (stated, not implied) | lane_mask (vcc of a Wave32 VOPC compare) +# wave any | wave32 (wave32 exactly for the VOPC lane-mask compares) # 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 @@ -1409,3 +1409,272 @@ wave = "any" operands = "vop2_vgpr" spec = [{ document = "guide", section = "12.7", page = 134 }] verify = ["reference", "independent", "metal", "llvm_encoding"] + +# ---- VOPC Wave32 32-bit integer compares (migrated from #239) ---- +# VCC_LO := lanes where EXEC and the relation (S0 = SRC0 on the left) hold; +# the contract is docs/shaders/vector-compare.md. relation "lg" is the guide's +# LG/NE offset 5 (Table 59), named V_CMP_NE_* in the XML. v_cmpx (EXEC writes), +# the VOP3 encoding and Wave64 stay unsupported. +[operand_rules.vopc_vcc] +family = "VOPC" +src = [ + { field = "SRC0", class = "vector_source" }, + { field = "VSRC1", class = "vgpr" }, +] +# The destination is implicitly vcc_lo; SRC0 is a vector_source as for VOP2. +max_literals = 1 +unsupported = [ + "src_vcc_hi", "src_exec", "src_m0", "src_ttmp", "src_null", "src_float_inline", "src_special", +] + +[[form]] +name = "V_CMP_LT_I32" +family = "VOPC" +opcode = 129 +variant = "CmpLtI32" +operation = "compare" +relation = "lt" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_CMP_EQ_I32" +family = "VOPC" +opcode = 130 +variant = "CmpEqI32" +operation = "compare" +relation = "eq" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_CMP_LE_I32" +family = "VOPC" +opcode = 131 +variant = "CmpLeI32" +operation = "compare" +relation = "le" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_CMP_GT_I32" +family = "VOPC" +opcode = 132 +variant = "CmpGtI32" +operation = "compare" +relation = "gt" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_CMP_NE_I32" +family = "VOPC" +opcode = 133 +variant = "CmpNeI32" +operation = "compare" +relation = "lg" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_CMP_GE_I32" +family = "VOPC" +opcode = 134 +variant = "CmpGeI32" +operation = "compare" +relation = "ge" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_CMP_LT_U32" +family = "VOPC" +opcode = 193 +variant = "CmpLtU32" +operation = "compare" +relation = "lt" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_CMP_EQ_U32" +family = "VOPC" +opcode = 194 +variant = "CmpEqU32" +operation = "compare" +relation = "eq" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_CMP_LE_U32" +family = "VOPC" +opcode = 195 +variant = "CmpLeU32" +operation = "compare" +relation = "le" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_CMP_GT_U32" +family = "VOPC" +opcode = 196 +variant = "CmpGtU32" +operation = "compare" +relation = "gt" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_CMP_NE_U32" +family = "VOPC" +opcode = 197 +variant = "CmpNeU32" +operation = "compare" +relation = "lg" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_CMP_GE_U32" +family = "VOPC" +opcode = 198 +variant = "CmpGeU32" +operation = "compare" +relation = "ge" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] diff --git a/crates/isa/src/lib.rs b/crates/isa/src/lib.rs index 160e3c0..a9269db 100644 --- a/crates/isa/src/lib.rs +++ b/crates/isa/src/lib.rs @@ -18,7 +18,9 @@ pub use rdna2::{ 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, ScalarCompareOp, ScalarUnaryOp, VectorAluOp}; +pub use semantics_gen::{ + ScalarAluOp, ScalarCompareOp, ScalarUnaryOp, VectorAluOp, VectorCompareOp, +}; /// SGPR index of `vcc_lo`, the Wave32 vector condition code. pub const VCC_LO: u8 = 106; @@ -93,7 +95,8 @@ impl fmt::Display for ScalarSource { } } -/// Relation tested by a VOPC integer compare; S0 is SRC0 and S1 is VSRC1. +/// Relation tested by a SOPC or VOPC integer compare; S0 (SSRC0 or SRC0) is on +/// the left. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum CompareRelation { /// S0 < S1 (opcode offset 1). @@ -110,64 +113,6 @@ pub enum CompareRelation { GreaterOrEqual, } -/// A 32-bit VOPC integer compare: one relation over signed or unsigned operands. -/// -/// The per-lane test follows the RDNA 2 ISA guide, section 12.9 (Table 59) and -/// the pinned XML descriptions. VCC and EXEC rules are in -/// docs/shaders/vector-compare.md. -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub struct VectorCompareOp { - /// The tested relation. - pub relation: CompareRelation, - /// `_i32` (two's complement) when true, `_u32` when false. - pub signed: bool, -} - -impl VectorCompareOp { - /// Lower-case mnemonic of the 32-bit VOPC encoding. - pub fn mnemonic(self) -> &'static str { - const SIGNED: [&str; 6] = [ - "v_cmp_lt_i32_e32", - "v_cmp_eq_i32_e32", - "v_cmp_le_i32_e32", - "v_cmp_gt_i32_e32", - "v_cmp_ne_i32_e32", - "v_cmp_ge_i32_e32", - ]; - const UNSIGNED: [&str; 6] = [ - "v_cmp_lt_u32_e32", - "v_cmp_eq_u32_e32", - "v_cmp_le_u32_e32", - "v_cmp_gt_u32_e32", - "v_cmp_ne_u32_e32", - "v_cmp_ge_u32_e32", - ]; - let index = self.relation as usize; - if self.signed { - SIGNED[index] - } else { - UNSIGNED[index] - } - } - - /// The per-lane test result for operand bits S0 and S1. - pub fn test(self, src0: u32, src1: u32) -> bool { - let ordering = if self.signed { - (src0 as i32).cmp(&(src1 as i32)) - } else { - src0.cmp(&src1) - }; - match self.relation { - CompareRelation::Less => ordering.is_lt(), - CompareRelation::Equal => ordering.is_eq(), - CompareRelation::LessOrEqual => ordering.is_le(), - CompareRelation::Greater => ordering.is_gt(), - CompareRelation::NotEqual => ordering.is_ne(), - CompareRelation::GreaterOrEqual => ordering.is_ge(), - } - } -} - /// Output targeted by a supported uncompressed four-component export. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum ExportTarget { @@ -327,7 +272,7 @@ impl Instruction { Self::ScalarUnary { op, .. } => op.mnemonic(), Self::ScalarAlu { op, .. } => op.mnemonic(), Self::ScalarCompare { op, .. } => op.mnemonic(), - Self::VectorCompare { op, .. } => op.mnemonic(), + Self::VectorCompare { op, .. } => op.assembly_name(), Self::VectorAlu { op, .. } => op.assembly_name(), Self::BranchSccZero { .. } => "s_cbranch_scc0", Self::BranchExecZero { .. } => "s_cbranch_execz", diff --git a/crates/isa/src/semantics.rs b/crates/isa/src/semantics.rs index cd76804..ff67cb6 100644 --- a/crates/isa/src/semantics.rs +++ b/crates/isa/src/semantics.rs @@ -160,11 +160,15 @@ pub enum SccEffect { SelectedSrc0, } -/// What a form writes to VCC or EXEC. Stage A forms leave both unchanged. +/// What a form writes to VCC or EXEC. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum MaskEffect { /// Not written. Unchanged, + /// Wave32 VOPC result (VCC only): `VCC_LO` bit n is EXEC[n] & (lane n + /// exists) & test(lane n), fully written; `VCC_HI` has no known value after + /// it (docs/shaders/vector-compare.md section 3). + LaneMask, } /// Wave-size restriction. @@ -188,6 +192,10 @@ pub enum OperandRule { /// SOP1 unary: SDST is s0-s105; SSRC0 is s0-s105, an inline integer -16..64 or /// a literal word. Everything else is rejected as unsupported. Sop1Sgpr, + /// VOPC vector compare: the destination is `vcc_lo` (Wave32); SRC0 is a VGPR, + /// s0-s105, `vcc_lo`, an inline integer -16..64 or a literal word; VSRC1 is a + /// VGPR. Everything else is rejected as unsupported. + VopcVcc, /// VOP2 vector: VDST is v0-v255; SRC0 is a VGPR, s0-s105, `vcc_lo`, an inline /// integer -16..64 or a literal word; VSRC1 is a VGPR. Everything else is /// rejected as unsupported. diff --git a/crates/isa/src/semantics_gen.rs b/crates/isa/src/semantics_gen.rs index 1d35de2..0366a2b 100644 --- a/crates/isa/src/semantics_gen.rs +++ b/crates/isa/src/semantics_gen.rs @@ -1179,7 +1179,7 @@ impl ScalarCompareOp { } } - /// The new SCC: whether the relation holds for S0 and S1. + /// The SCC: whether the relation holds for S0 and S1. pub const fn test(self, src0: u32, src1: u32) -> bool { match self { Self::CmpEqI32 => primitive::eq_b32(src0, src1), @@ -1412,8 +1412,432 @@ impl VectorAluOp { } } +/// VOPC operations declared in the semantic registry (operand rule `vopc_vcc`). +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum VectorCompareOp { + /// `v_cmp_lt_i32` (VOPC opcode 129): signed compare lt, VCC = lane_mask. + CmpLtI32, + /// `v_cmp_eq_i32` (VOPC opcode 130): signed compare eq, VCC = lane_mask. + CmpEqI32, + /// `v_cmp_le_i32` (VOPC opcode 131): signed compare le, VCC = lane_mask. + CmpLeI32, + /// `v_cmp_gt_i32` (VOPC opcode 132): signed compare gt, VCC = lane_mask. + CmpGtI32, + /// `v_cmp_ne_i32` (VOPC opcode 133): signed compare lg, VCC = lane_mask. + CmpNeI32, + /// `v_cmp_ge_i32` (VOPC opcode 134): signed compare ge, VCC = lane_mask. + CmpGeI32, + /// `v_cmp_lt_u32` (VOPC opcode 193): unsigned compare lt, VCC = lane_mask. + CmpLtU32, + /// `v_cmp_eq_u32` (VOPC opcode 194): unsigned compare eq, VCC = lane_mask. + CmpEqU32, + /// `v_cmp_le_u32` (VOPC opcode 195): unsigned compare le, VCC = lane_mask. + CmpLeU32, + /// `v_cmp_gt_u32` (VOPC opcode 196): unsigned compare gt, VCC = lane_mask. + CmpGtU32, + /// `v_cmp_ne_u32` (VOPC opcode 197): unsigned compare lg, VCC = lane_mask. + CmpNeU32, + /// `v_cmp_ge_u32` (VOPC opcode 198): unsigned compare ge, VCC = lane_mask. + CmpGeU32, +} + +/// VectorCompareOp by VOPC OP field value; `None` for undeclared opcodes. +const VECTOR_COMPARE_OP_BY_OPCODE: [Option; 256] = [ + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + Some(VectorCompareOp::CmpLtI32), + Some(VectorCompareOp::CmpEqI32), + Some(VectorCompareOp::CmpLeI32), + Some(VectorCompareOp::CmpGtI32), + Some(VectorCompareOp::CmpNeI32), + Some(VectorCompareOp::CmpGeI32), + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + Some(VectorCompareOp::CmpLtU32), + Some(VectorCompareOp::CmpEqU32), + Some(VectorCompareOp::CmpLeU32), + Some(VectorCompareOp::CmpGtU32), + Some(VectorCompareOp::CmpNeU32), + Some(VectorCompareOp::CmpGeU32), + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, +]; + +impl VectorCompareOp { + /// Every operation, in registry order. + pub const ALL: [Self; 12] = [ + Self::CmpLtI32, + Self::CmpEqI32, + Self::CmpLeI32, + Self::CmpGtI32, + Self::CmpNeI32, + Self::CmpGeI32, + Self::CmpLtU32, + Self::CmpEqU32, + Self::CmpLeU32, + Self::CmpGtU32, + Self::CmpNeU32, + Self::CmpGeU32, + ]; + + /// Selects the operation from a first instruction word: the VOPC encoding + /// bits (mask 0xfe00_0000) and then the OP field (bits 17-24). + pub const fn from_word(word: u32) -> Option { + if word & 0xfe00_0000 != 0x7c00_0000 { + return None; + } + VECTOR_COMPARE_OP_BY_OPCODE[((word >> 17) & 0xff) as usize] + } + + /// Lower-case mnemonic. + pub const fn mnemonic(self) -> &'static str { + match self { + Self::CmpLtI32 => "v_cmp_lt_i32", + Self::CmpEqI32 => "v_cmp_eq_i32", + Self::CmpLeI32 => "v_cmp_le_i32", + Self::CmpGtI32 => "v_cmp_gt_i32", + Self::CmpNeI32 => "v_cmp_ne_i32", + Self::CmpGeI32 => "v_cmp_ge_i32", + Self::CmpLtU32 => "v_cmp_lt_u32", + Self::CmpEqU32 => "v_cmp_eq_u32", + Self::CmpLeU32 => "v_cmp_le_u32", + Self::CmpGtU32 => "v_cmp_gt_u32", + Self::CmpNeU32 => "v_cmp_ne_u32", + Self::CmpGeU32 => "v_cmp_ge_u32", + } + } + + /// The validated registry row. + pub fn semantics(self) -> &'static FormSemantics { + &FORMS[match self { + Self::CmpLtI32 => 68, + Self::CmpEqI32 => 69, + Self::CmpLeI32 => 70, + Self::CmpGtI32 => 71, + Self::CmpNeI32 => 72, + Self::CmpGeI32 => 73, + Self::CmpLtU32 => 74, + Self::CmpEqU32 => 75, + Self::CmpLeU32 => 76, + Self::CmpGtU32 => 77, + Self::CmpNeU32 => 78, + Self::CmpGeU32 => 79, + }] + } + + /// Assembler name of the 32-bit (VOPC) encoding, as LLVM prints it. + pub const fn assembly_name(self) -> &'static str { + match self { + Self::CmpLtI32 => "v_cmp_lt_i32_e32", + Self::CmpEqI32 => "v_cmp_eq_i32_e32", + Self::CmpLeI32 => "v_cmp_le_i32_e32", + Self::CmpGtI32 => "v_cmp_gt_i32_e32", + Self::CmpNeI32 => "v_cmp_ne_i32_e32", + Self::CmpGeI32 => "v_cmp_ge_i32_e32", + Self::CmpLtU32 => "v_cmp_lt_u32_e32", + Self::CmpEqU32 => "v_cmp_eq_u32_e32", + Self::CmpLeU32 => "v_cmp_le_u32_e32", + Self::CmpGtU32 => "v_cmp_gt_u32_e32", + Self::CmpNeU32 => "v_cmp_ne_u32_e32", + Self::CmpGeU32 => "v_cmp_ge_u32_e32", + } + } + + /// Whether the operands compare as two's-complement values. + pub const fn signed(self) -> bool { + match self { + Self::CmpLtI32 => true, + Self::CmpEqI32 => true, + Self::CmpLeI32 => true, + Self::CmpGtI32 => true, + Self::CmpNeI32 => true, + Self::CmpGeI32 => true, + Self::CmpLtU32 => false, + Self::CmpEqU32 => false, + Self::CmpLeU32 => false, + Self::CmpGtU32 => false, + Self::CmpNeU32 => false, + Self::CmpGeU32 => false, + } + } + + /// The relation tested, with S0 on the left. + pub const fn relation(self) -> CompareRelation { + match self { + Self::CmpLtI32 => CompareRelation::Less, + Self::CmpEqI32 => CompareRelation::Equal, + Self::CmpLeI32 => CompareRelation::LessOrEqual, + Self::CmpGtI32 => CompareRelation::Greater, + Self::CmpNeI32 => CompareRelation::NotEqual, + Self::CmpGeI32 => CompareRelation::GreaterOrEqual, + Self::CmpLtU32 => CompareRelation::Less, + Self::CmpEqU32 => CompareRelation::Equal, + Self::CmpLeU32 => CompareRelation::LessOrEqual, + Self::CmpGtU32 => CompareRelation::Greater, + Self::CmpNeU32 => CompareRelation::NotEqual, + Self::CmpGeU32 => CompareRelation::GreaterOrEqual, + } + } + + /// The per-lane result: whether the relation holds for S0 and S1. + pub const fn test(self, src0: u32, src1: u32) -> bool { + match self { + Self::CmpLtI32 => primitive::lt_i32(src0, src1), + Self::CmpEqI32 => primitive::eq_b32(src0, src1), + Self::CmpLeI32 => primitive::le_i32(src0, src1), + Self::CmpGtI32 => primitive::gt_i32(src0, src1), + Self::CmpNeI32 => primitive::ne_b32(src0, src1), + Self::CmpGeI32 => primitive::ge_i32(src0, src1), + Self::CmpLtU32 => primitive::lt_u32(src0, src1), + Self::CmpEqU32 => primitive::eq_b32(src0, src1), + Self::CmpLeU32 => primitive::le_u32(src0, src1), + Self::CmpGtU32 => primitive::gt_u32(src0, src1), + Self::CmpNeU32 => primitive::ne_b32(src0, src1), + Self::CmpGeU32 => primitive::ge_u32(src0, src1), + } + } +} + /// Identity of every registry form, in registry order. -pub const FORM_IDS: [(&str, EncodingFamily); 68] = [ +pub const FORM_IDS: [(&str, EncodingFamily); 80] = [ ("S_ADD_U32", EncodingFamily::Sop2), ("S_SUB_U32", EncodingFamily::Sop2), ("S_ADD_I32", EncodingFamily::Sop2), @@ -1482,10 +1906,22 @@ pub const FORM_IDS: [(&str, EncodingFamily); 68] = [ ("V_ADD_NC_U32", EncodingFamily::Vop2), ("V_SUB_NC_U32", EncodingFamily::Vop2), ("V_SUBREV_NC_U32", EncodingFamily::Vop2), + ("V_CMP_LT_I32", EncodingFamily::Vopc), + ("V_CMP_EQ_I32", EncodingFamily::Vopc), + ("V_CMP_LE_I32", EncodingFamily::Vopc), + ("V_CMP_GT_I32", EncodingFamily::Vopc), + ("V_CMP_NE_I32", EncodingFamily::Vopc), + ("V_CMP_GE_I32", EncodingFamily::Vopc), + ("V_CMP_LT_U32", EncodingFamily::Vopc), + ("V_CMP_EQ_U32", EncodingFamily::Vopc), + ("V_CMP_LE_U32", EncodingFamily::Vopc), + ("V_CMP_GT_U32", EncodingFamily::Vopc), + ("V_CMP_NE_U32", EncodingFamily::Vopc), + ("V_CMP_GE_U32", EncodingFamily::Vopc), ]; /// One validated row per registry form, in registry order. -pub static FORMS: [FormSemantics; 68] = [ +pub static FORMS: [FormSemantics; 80] = [ FormSemantics { name: "S_ADD_U32", family: EncodingFamily::Sop2, @@ -2914,4 +3350,256 @@ pub static FORMS: [FormSemantics; 68] = [ spec: &[SpecRef { document: Document::Guide, section: "12.7", page: 134 }], verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], }, + FormSemantics { + name: "V_CMP_LT_I32", + family: EncodingFamily::Vopc, + opcode: 129, + operation: Operation::Compare, + signedness: Signedness::Signed, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: Some(CompareRelation::Less), + scc: SccEffect::Unchanged, + vcc: MaskEffect::LaneMask, + exec: MaskEffect::Unchanged, + wave: Wave::Wave32, + operands: OperandRule::VopcVcc, + spec: &[SpecRef { document: Document::Guide, section: "12.9", page: 150 }, SpecRef { document: Document::Guide, section: "3.9", page: 19 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_CMP_EQ_I32", + family: EncodingFamily::Vopc, + opcode: 130, + operation: Operation::Compare, + signedness: Signedness::Signed, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: Some(CompareRelation::Equal), + scc: SccEffect::Unchanged, + vcc: MaskEffect::LaneMask, + exec: MaskEffect::Unchanged, + wave: Wave::Wave32, + operands: OperandRule::VopcVcc, + spec: &[SpecRef { document: Document::Guide, section: "12.9", page: 150 }, SpecRef { document: Document::Guide, section: "3.9", page: 19 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_CMP_LE_I32", + family: EncodingFamily::Vopc, + opcode: 131, + operation: Operation::Compare, + signedness: Signedness::Signed, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: Some(CompareRelation::LessOrEqual), + scc: SccEffect::Unchanged, + vcc: MaskEffect::LaneMask, + exec: MaskEffect::Unchanged, + wave: Wave::Wave32, + operands: OperandRule::VopcVcc, + spec: &[SpecRef { document: Document::Guide, section: "12.9", page: 150 }, SpecRef { document: Document::Guide, section: "3.9", page: 19 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_CMP_GT_I32", + family: EncodingFamily::Vopc, + opcode: 132, + operation: Operation::Compare, + signedness: Signedness::Signed, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: Some(CompareRelation::Greater), + scc: SccEffect::Unchanged, + vcc: MaskEffect::LaneMask, + exec: MaskEffect::Unchanged, + wave: Wave::Wave32, + operands: OperandRule::VopcVcc, + spec: &[SpecRef { document: Document::Guide, section: "12.9", page: 150 }, SpecRef { document: Document::Guide, section: "3.9", page: 19 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_CMP_NE_I32", + family: EncodingFamily::Vopc, + opcode: 133, + operation: Operation::Compare, + signedness: Signedness::Signed, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: Some(CompareRelation::NotEqual), + scc: SccEffect::Unchanged, + vcc: MaskEffect::LaneMask, + exec: MaskEffect::Unchanged, + wave: Wave::Wave32, + operands: OperandRule::VopcVcc, + spec: &[SpecRef { document: Document::Guide, section: "12.9", page: 150 }, SpecRef { document: Document::Guide, section: "3.9", page: 19 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_CMP_GE_I32", + family: EncodingFamily::Vopc, + opcode: 134, + operation: Operation::Compare, + signedness: Signedness::Signed, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: Some(CompareRelation::GreaterOrEqual), + scc: SccEffect::Unchanged, + vcc: MaskEffect::LaneMask, + exec: MaskEffect::Unchanged, + wave: Wave::Wave32, + operands: OperandRule::VopcVcc, + spec: &[SpecRef { document: Document::Guide, section: "12.9", page: 150 }, SpecRef { document: Document::Guide, section: "3.9", page: 19 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_CMP_LT_U32", + family: EncodingFamily::Vopc, + opcode: 193, + operation: Operation::Compare, + signedness: Signedness::Unsigned, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: Some(CompareRelation::Less), + scc: SccEffect::Unchanged, + vcc: MaskEffect::LaneMask, + exec: MaskEffect::Unchanged, + wave: Wave::Wave32, + operands: OperandRule::VopcVcc, + spec: &[SpecRef { document: Document::Guide, section: "12.9", page: 150 }, SpecRef { document: Document::Guide, section: "3.9", page: 19 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_CMP_EQ_U32", + family: EncodingFamily::Vopc, + opcode: 194, + operation: Operation::Compare, + signedness: Signedness::Unsigned, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: Some(CompareRelation::Equal), + scc: SccEffect::Unchanged, + vcc: MaskEffect::LaneMask, + exec: MaskEffect::Unchanged, + wave: Wave::Wave32, + operands: OperandRule::VopcVcc, + spec: &[SpecRef { document: Document::Guide, section: "12.9", page: 150 }, SpecRef { document: Document::Guide, section: "3.9", page: 19 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_CMP_LE_U32", + family: EncodingFamily::Vopc, + opcode: 195, + operation: Operation::Compare, + signedness: Signedness::Unsigned, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: Some(CompareRelation::LessOrEqual), + scc: SccEffect::Unchanged, + vcc: MaskEffect::LaneMask, + exec: MaskEffect::Unchanged, + wave: Wave::Wave32, + operands: OperandRule::VopcVcc, + spec: &[SpecRef { document: Document::Guide, section: "12.9", page: 150 }, SpecRef { document: Document::Guide, section: "3.9", page: 19 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_CMP_GT_U32", + family: EncodingFamily::Vopc, + opcode: 196, + operation: Operation::Compare, + signedness: Signedness::Unsigned, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: Some(CompareRelation::Greater), + scc: SccEffect::Unchanged, + vcc: MaskEffect::LaneMask, + exec: MaskEffect::Unchanged, + wave: Wave::Wave32, + operands: OperandRule::VopcVcc, + spec: &[SpecRef { document: Document::Guide, section: "12.9", page: 150 }, SpecRef { document: Document::Guide, section: "3.9", page: 19 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_CMP_NE_U32", + family: EncodingFamily::Vopc, + opcode: 197, + operation: Operation::Compare, + signedness: Signedness::Unsigned, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: Some(CompareRelation::NotEqual), + scc: SccEffect::Unchanged, + vcc: MaskEffect::LaneMask, + exec: MaskEffect::Unchanged, + wave: Wave::Wave32, + operands: OperandRule::VopcVcc, + spec: &[SpecRef { document: Document::Guide, section: "12.9", page: 150 }, SpecRef { document: Document::Guide, section: "3.9", page: 19 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_CMP_GE_U32", + family: EncodingFamily::Vopc, + opcode: 198, + operation: Operation::Compare, + signedness: Signedness::Unsigned, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: Some(CompareRelation::GreaterOrEqual), + scc: SccEffect::Unchanged, + vcc: MaskEffect::LaneMask, + exec: MaskEffect::Unchanged, + wave: Wave::Wave32, + operands: OperandRule::VopcVcc, + spec: &[SpecRef { document: Document::Guide, section: "12.9", page: 150 }, SpecRef { document: Document::Guide, section: "3.9", page: 19 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, ]; diff --git a/crates/isa/tests/semantics.rs b/crates/isa/tests/semantics.rs index fb3de7f..b46b692 100644 --- a/crates/isa/tests/semantics.rs +++ b/crates/isa/tests/semantics.rs @@ -1,8 +1,12 @@ //! Ties the generated semantic registry tables to the independent XML metadata table. use xenora_isa::meta::{EncodingFamily, FORMS as META_FORMS}; -use xenora_isa::semantics::{CarryIn, FORM_IDS, FORMS, GENERATED_SCHEMA, SCHEMA, SccEffect}; -use xenora_isa::{ScalarAluOp, ScalarCompareOp, ScalarUnaryOp, VectorAluOp}; +use xenora_isa::semantics::{ + CarryIn, FORM_IDS, FORMS, GENERATED_SCHEMA, MaskEffect, SCHEMA, SccEffect, Signedness, Wave, +}; +use xenora_isa::{ + CompareRelation, ScalarAluOp, ScalarCompareOp, ScalarUnaryOp, VectorAluOp, VectorCompareOp, +}; #[test] fn generated_tables_match_the_schema_and_the_metadata_forms() { @@ -103,3 +107,54 @@ fn vector_alu_dispatch_selects_exactly_the_registry_vop2_forms() { VectorAluOp::from_word(word).map(|op| op.semantics().name) }); } + +#[test] +fn vector_compare_dispatch_selects_exactly_the_registry_vopc_forms() { + const OPERANDS: [u32; 6] = [0, 1, 0x7fff_ffff, 0x8000_0000, 0xffff_fffe, 0xffff_ffff]; + for op in VectorCompareOp::ALL { + let row = op.semantics(); + assert_eq!(row.family, EncodingFamily::Vopc); + assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic()); + assert_eq!(op.assembly_name(), format!("{}_e32", op.mnemonic())); + assert_eq!(row.relation, Some(op.relation())); + assert_eq!(op.signed(), row.signedness == Signedness::Signed); + assert_eq!( + (row.scc, row.vcc, row.exec, row.wave), + ( + SccEffect::Unchanged, + MaskEffect::LaneMask, + MaskEffect::Unchanged, + Wave::Wave32 + ) + ); + // The per-lane test is the declared relation over the declared + // signedness, with SRC0 on the left. + for src0 in OPERANDS { + for src1 in OPERANDS { + let ordering = if op.signed() { + (src0 as i32).cmp(&(src1 as i32)) + } else { + src0.cmp(&src1) + }; + let expected = match op.relation() { + CompareRelation::Less => ordering.is_lt(), + CompareRelation::Equal => ordering.is_eq(), + CompareRelation::LessOrEqual => ordering.is_le(), + CompareRelation::Greater => ordering.is_gt(), + CompareRelation::NotEqual => ordering.is_ne(), + CompareRelation::GreaterOrEqual => ordering.is_ge(), + }; + assert_eq!( + op.test(src0, src1), + expected, + "{} {src0:#x} {src1:#x}", + row.name + ); + } + } + } + // v_cmpx, F/T and the 16-, 64-bit and float compares must not be dispatched. + dispatch_selects_exactly(EncodingFamily::Vopc, |word| { + VectorCompareOp::from_word(word).map(|op| op.semantics().name) + }); +} diff --git a/crates/shader/src/lib.rs b/crates/shader/src/lib.rs index bd41abe..50a8130 100644 --- a/crates/shader/src/lib.rs +++ b/crates/shader/src/lib.rs @@ -195,7 +195,7 @@ impl Op { fn compare_expression(op: VectorCompareOp, left: &str, right: &str) -> String { use xenora_decoder::CompareRelation; - let symbol = match op.relation { + let symbol = match op.relation() { CompareRelation::Less => "<", CompareRelation::Equal => "==", CompareRelation::LessOrEqual => "<=", @@ -203,7 +203,7 @@ fn compare_expression(op: VectorCompareOp, left: &str, right: &str) -> String { CompareRelation::NotEqual => "!=", CompareRelation::GreaterOrEqual => ">=", }; - if op.signed { + if op.signed() { format!("as_type({left}) {symbol} as_type({right})") } else { format!("{left} {symbol} {right}") @@ -485,7 +485,7 @@ pub fn compile(architecture: Architecture, bytes: &[u8]) -> Result= S1 | `_i32` compares the 32-bit two's-complement values, `_u32` the unsigned values. +The forms are declared in the semantic registry +(`crates/isa/semantics/rdna2.toml`, operand rule `vopc_vcc`); the decoder +dispatches them from the generated `VectorCompareOp`. Operand order matters (S0 is SRC0): lt with swapped operands is gt. SRC0 selectors, exhaustively: 0-105 (normal SGPR), 106 (VCC_LO, see 5), diff --git a/tests/semantics_generator/test_generate_semantics.py b/tests/semantics_generator/test_generate_semantics.py index 5384ffb..71b39f5 100644 --- a/tests/semantics_generator/test_generate_semantics.py +++ b/tests/semantics_generator/test_generate_semantics.py @@ -144,9 +144,31 @@ def snapshot(): "instruction": name, "encoding": "ENC_VOP2", "opcode": opcode, "operands": vector(data_format), } + vopc = { + "name": "ENC_VOPC", + "bits": 32, + "fields": [ + ["SRC0", [[0, 9]]], ["VSRC1", [[9, 8]]], ["OP", [[17, 8]]], ["ENCODING", [[25, 7]]], + ], + "identifier_mask": 0xFFFE0000, + "identifiers": [0x7C000000 | (op << 17) for op in (129, 197)], + } + for name, opcode, data_format in (("V_CMP_LT_I32", 129, I32), ("V_CMP_NE_U32", 197, U32)): + variants[(name, "ENC_VOPC")] = { + "instruction": name, "encoding": "ENC_VOPC", "opcode": opcode, + # Values copied from the AMD XML snapshot: an implicit 64-bit VCC output. + "operands": [ + ["", "FMT_NUM_M64", "OPR_VCC", 64, False, True, False, False], + ["SRC0", data_format, "OPR_SRC", 32, True, False, False, True], + ["VSRC1", data_format, "OPR_VGPR", 32, True, False, False, True], + ], + } return { "source": {"sha256": SHA}, - "encodings": {"ENC_SOP2": encoding, "ENC_SOPC": sopc, "ENC_SOP1": sop1, "ENC_VOP2": vop2}, + "encodings": { + "ENC_SOP2": encoding, "ENC_SOPC": sopc, "ENC_SOP1": sop1, "ENC_VOP2": vop2, + "ENC_VOPC": vopc, + }, "variants": variants, } @@ -217,6 +239,27 @@ def vectors(): return reg +def vector_compares(): + reg = registry() + rule = copy.deepcopy(gen.OPERAND_RULES["vopc_vcc"]["shape"]) + rule["unsupported"] = sorted(gen.OPERAND_RULES["vopc_vcc"]["unsupported"]) + reg["operand_rules"]["vopc_vcc"] = rule + + def compare(name, opcode, variant, relation, signedness): + form = _form(name, opcode, variant, "compare", signedness, "unchanged") + form.update( + family="VOPC", relation=relation, operands="vopc_vcc", vcc="lane_mask", wave="wave32" + ) + return form + + reg["form"] += [ + # The same variant name as a SOPC form: variants are per enum. + compare("V_CMP_LT_I32", 129, "CmpLtI32", "lt", "signed"), + compare("V_CMP_NE_U32", 197, "CmpNeU32", "lg", "unsigned"), + ] + return reg + + def compares(): reg = registry() reg["form"] += [ @@ -738,7 +781,65 @@ class Validate(unittest.TestCase): 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") + self.rejects(reg, "S_ADD_U32: wave wave32 is not enforced for this rule (requires any)") + + # ---- VOPC lane-mask compares ---- + + def test_accepts_vector_compares(self): + self.assertEqual(self.errors(vector_compares()), []) + + def test_rejects_a_vector_compare_declared_for_any_wave(self): + reg = vector_compares() + form(reg, "V_CMP_LT_I32")["wave"] = "any" + self.rejects(reg, "V_CMP_LT_I32: wave any is not enforced for this rule (requires wave32)") + + def test_rejects_a_vector_compare_without_its_vcc_write(self): + reg = vector_compares() + form(reg, "V_CMP_LT_I32")["vcc"] = "unchanged" + self.rejects(reg, "V_CMP_LT_I32: vcc unchanged contradicts rule vopc_vcc (requires lane_mask)") + # The XML VCC output is then undeclared as well. + self.rejects(reg, "V_CMP_LT_I32: XML implicit operands ['OPR_VCC'] are not declared") + + def test_rejects_a_lane_mask_outside_vopc(self): + reg = registry() + reg["form"][0]["vcc"] = "lane_mask" + self.rejects(reg, "S_ADD_U32: vcc lane_mask contradicts rule sop2_sgpr (requires unchanged)") + self.rejects(reg, "S_ADD_U32: vcc lane_mask but the XML has no implicit VCC output") + + def test_rejects_an_exec_write(self): + reg = vector_compares() + form(reg, "V_CMP_LT_I32")["exec"] = "lane_mask" + self.rejects(reg, "V_CMP_LT_I32: exec lane_mask has no contract (requires unchanged)") + + def test_rejects_a_vector_compare_that_writes_scc(self): + reg = vector_compares() + form(reg, "V_CMP_LT_I32")["scc"] = "relation" + self.rejects(reg, "V_CMP_LT_I32: scc relation contradicts compare (requires unchanged)") + + def test_rejects_a_vector_compare_without_a_relation(self): + reg = vector_compares() + del form(reg, "V_CMP_NE_U32")["relation"] + self.rejects(reg, "V_CMP_NE_U32: unknown or missing relation None") + + def test_rejects_a_vector_compare_under_a_scalar_rule(self): + reg = vector_compares() + form(reg, "V_CMP_LT_I32")["operands"] = "sopc_scalar" + self.rejects(reg, "V_CMP_LT_I32: operand rule sopc_scalar is for SOPC") + + def test_rejects_a_vector_compare_signedness_against_the_xml(self): + reg = vector_compares() + form(reg, "V_CMP_LT_I32")["signedness"] = "unsigned" + self.rejects(reg, "V_CMP_LT_I32: signedness unsigned contradicts XML format FMT_NUM_I32") + + def test_renders_vector_compare_dispatch(self): + text = gen.render(vector_compares(), snapshot()) + self.assertIn("pub enum VectorCompareOp {", text) + self.assertIn("if word & 0xfe00_0000 != 0x7c00_0000 {", text) + self.assertIn('Self::CmpNeU32 => "v_cmp_ne_u32_e32",', text) + self.assertIn("Self::CmpLtI32 => true,", text.split("fn signed", 1)[1]) + self.assertIn("Self::CmpNeU32 => primitive::ne_b32(src0, src1),", text) + self.assertIn("vcc: MaskEffect::LaneMask,", text) + self.assertIn("wave: Wave::Wave32,", text) def test_rejects_a_reserved_variant(self): reg = registry() From 1ac4f82d7a9fe4013746ba684da37adeff4a41ee Mon Sep 17 00:00:00 2001 From: elforeign <324243036+elforeign@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:34:38 -0600 Subject: [PATCH 02/15] test(vopc): independent oracle for v_cmp_{f,t}_{i32,u32}_e32 (#215) The registry stage adds the four constant 32-bit integer VOPC compares, which nothing could check: the reference and the second interpreter both rejected them. Derive them from the RDNA 2 guide only (12.9 Table 61: D = 0 / D = 1; 3.9: VCC[n] = EXEC[n] & test, fully written) under the #239 Wave32 contract, so T writes EXEC_LO masked to existing lanes, F writes 0, and sources keep the allowlist and initialization rules. vopc_f_t.rs covers every SRC0 class, aliasing, full, partial and empty EXEC with a stale VCC_LO, a partial final wave, s_cbranch_vccz on both edges and the rejections; the native Metal part is ignored until the translator side lands. known_answers no longer expects F and T to be rejected. Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com> --- crates/ref/src/lib.rs | 12 +- tests/validation/independent_ref.rs | 14 +- tests/validation/known_answers.rs | 10 +- tests/validation/tests/vopc_f_t.rs | 649 ++++++++++++++++++++++++++++ 4 files changed, 670 insertions(+), 15 deletions(-) create mode 100644 tests/validation/tests/vopc_f_t.rs diff --git a/crates/ref/src/lib.rs b/crates/ref/src/lib.rs index 59f171a..e391d45 100644 --- a/crates/ref/src/lib.rs +++ b/crates/ref/src/lib.rs @@ -79,10 +79,10 @@ pub enum Op { /// /// AMD RDNA 2 ISA guide section 12.9, Tables 59 and 61: opcode 128 + offset /// for signed and 192 + offset for unsigned 32-bit operands, with offsets -/// LT 1, EQ 2, LE 3, GT 4, NE 5, GE 6. +/// F 0, LT 1, EQ 2, LE 3, GT 4, NE 5, GE 6, T 7. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct Comparison { - /// Opcode offset 1-6 within the 32-bit integer group. + /// Opcode offset 0-7 within the 32-bit integer group. pub offset: u8, /// Whether the operands are two's-complement integers. pub signed: bool, @@ -100,12 +100,16 @@ impl Comparison { }; let (s0, s1) = (widen(s0), widen(s1)); match self.offset { + // Table 61: V_CMP_F_{I,U}32 `D[threadId] = 0`. + 0 => false, 1 => s0 < s1, 2 => s0 == s1, 3 => s0 <= s1, 4 => s0 > s1, 5 => s0 != s1, - _ => s0 >= s1, + 6 => s0 >= s1, + // Table 61: V_CMP_T_{I,U}32 `D[threadId] = 1`. + _ => true, } } } @@ -579,7 +583,7 @@ pub fn decode(code: &[u8]) -> Result, ReferenceError> { [lo, packed, upper, tag @ 0x7c..=0x7d, tail @ ..] if matches!( (u16::from(*tag & 1) << 7) | u16::from(*upper >> 1), - 129..=134 | 193..=198 + 128..=135 | 192..=199 ) => { let opcode = (u16::from(*tag & 1) << 7) | u16::from(*upper >> 1); diff --git a/tests/validation/independent_ref.rs b/tests/validation/independent_ref.rs index 8076a9a..f4fc5f2 100644 --- a/tests/validation/independent_ref.rs +++ b/tests/validation/independent_ref.rs @@ -27,7 +27,7 @@ //! production operator. SOP2 arithmetic runs through a bit-serial ripple //! adder (subtraction as addition of the complement), not host integer ops. //! -//! Wave32 VOPC integer compares (`v_cmp_{lt,eq,le,gt,ne,ge}_{i32,u32}_e32`, +//! Wave32 VOPC integer compares (`v_cmp_{f,lt,eq,le,gt,ne,ge,t}_{i32,u32}_e32`, //! contract `docs/shaders/vector-compare.md`) need all lanes of a wave, so execution //! runs lockstep waves of 32 consecutive dispatch indices with wave-uniform //! scalar state and per-lane vector state. A lane-local failure stops only that @@ -75,7 +75,7 @@ enum Insn { VMovFromSgpr(u8, u8), /// `v_mov_b32_e32 vD, vcc_lo`. VMovFromVcc(u8), - /// VOPC compare into VCC_LO: relation 1 lt, 2 eq, 3 le, 4 gt, 5 ne, 6 ge. + /// VOPC compare into VCC_LO: relation 0 f, 1 lt, 2 eq, 3 le, 4 gt, 5 ne, 6 ge, 7 t. VCmp { relation: u8, signed: bool, @@ -585,13 +585,17 @@ fn compare( } else { (a, b) }; + // Guide 12.9 Table 59 offsets; F (0) and T (7) ignore the operand + // values but still read them (contract 5: sources are validated). let pass = match relation { + 0 => false, 1 => a < b, 2 => a == b, 3 => a <= b, 4 => a > b, 5 => a != b, - _ => a >= b, + 6 => a >= b, + _ => true, }; mask |= u32::from(pass) << n; } @@ -1039,8 +1043,8 @@ fn decode_one(code: &[u8], offset: usize) -> Result<(Insn, usize), String> { if first >> 25 == 0b011_1110 { let opcode = (first >> 17) & 0xff; let (signed, relation) = match opcode { - 129..=134 => (true, opcode - 128), - 193..=198 => (false, opcode - 192), + 128..=135 => (true, opcode - 128), + 192..=199 => (false, opcode - 192), _ => return Err(fail("unsupported VOPC opcode")), }; let (src0, len) = vector_src0(code, offset, first, "VOPC")?; diff --git a/tests/validation/known_answers.rs b/tests/validation/known_answers.rs index ca406d9..6aa3cd3 100644 --- a/tests/validation/known_answers.rs +++ b/tests/validation/known_answers.rs @@ -1802,12 +1802,10 @@ mod review { let mut code = base.clone(); code[0x14..0x18].copy_from_slice(&vopc(129, 256 + 1, 9).to_le_bytes()); rejected_at(&code, 0x14); - // v_cmpx (writes EXEC), F and T forms, and the VOP3 encoding. - for word in [vopc(210, 257, 3), vopc(128, 257, 3), vopc(135, 257, 3)] { - let mut code = base.clone(); - code[0x14..0x18].copy_from_slice(&word.to_le_bytes()); - rejected_at(&code, 0x14); - } + // v_cmpx (writes EXEC) and the VOP3 encoding. + let mut code = base.clone(); + code[0x14..0x18].copy_from_slice(&vopc(210, 257, 3).to_le_bytes()); + rejected_at(&code, 0x14); let mut e64 = base[..0x14].to_vec(); e64.extend(words(&[0xd481_006a, 0x0002_0701])); e64.extend_from_slice(&base[0x18..]); diff --git a/tests/validation/tests/vopc_f_t.rs b/tests/validation/tests/vopc_f_t.rs new file mode 100644 index 0000000..53b74b1 --- /dev/null +++ b/tests/validation/tests/vopc_f_t.rs @@ -0,0 +1,649 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Independent per-lane expected values for the four constant Wave32 VOPC +//! integer compares (#215): `v_cmp_f_i32`, `v_cmp_t_i32`, `v_cmp_f_u32` and +//! `v_cmp_t_u32`, `_e32` only, under the contract in +//! `docs/shaders/vector-compare.md` (sections 2-7). +//! +//! The expectations are written below from the public AMD "RDNA 2" Instruction +//! Set Architecture Reference Guide only: section 12.9 "VOPC Instructions" +//! (Table 59 "Eight Compare Operations" and Table 61 "VOPC Compare Opcodes"), +//! section 3.9 "Vector Compares: VCC and VCCZ", and the VOPC word layout of +//! section 13.3.3. Nothing here comes from the ISA crate, the semantic +//! registry, the decoder or the shader compiler. Every case runs on the +//! reference interpreter `xenora_ref` and on the second interpreter +//! `independent_ref`; the ignored test also runs the translated MSL on native +//! Metal. +//! +//! Readings of the guide (not hardware evidence): +//! - Table 61: F is `D[threadId] = 0`, T is `D[threadId] = 1`, with "D = VCC in +//! VOPC encoding"; Table 59 gives the same as offsets F 0 and TRU 7. +//! - Section 3.9: `V_CMP_* => VCC[n] = EXEC[n] & (test passed for thread[n])` +//! and "VCC is fully written; there are no partial mask updates". So T writes +//! EXEC_LO masked to the lanes that exist, F writes 0 even for active lanes, +//! and stale VCC bits never survive either. +//! - Section 3.9: in wave32 only VCC_LO contributes to VCCZ, so +//! `s_cbranch_vccz` after F is taken, after T with EXEC_LO != 0 it is not, +//! and after T with EXEC_LO = 0 it is. +//! - The guide does not say that F and T skip their sources. They keep the +//! SRC0 allowlist and the contract section 5 rule: with EXEC_LO != 0 every +//! source must be valid and initialized; with EXEC_LO = 0 the encoding is +//! validated and no source is read. A lane-derived VCC_LO stays +//! lane-derived even though F's value is always 0 (contract section 5). + +#[path = "operand_domains/harness.rs"] +#[allow(dead_code)] +mod harness; +#[path = "../independent_ref.rs"] +mod independent_ref; + +use std::collections::BTreeMap; + +use harness::{Case, words}; +use xenora_shader::{Architecture, CompileError, compile}; + +/// The four forms with their ENC_VOPC opcodes (guide 12.9, Table 61). +#[derive(Clone, Copy, Debug, PartialEq)] +enum Form { + FI32 = 128, + TI32 = 135, + FU32 = 192, + TU32 = 199, +} + +const FORMS: [(Form, &str); 4] = [ + (Form::FI32, "v_cmp_f_i32"), + (Form::TI32, "v_cmp_t_i32"), + (Form::FU32, "v_cmp_f_u32"), + (Form::TU32, "v_cmp_t_u32"), +]; + +/// The per-lane test. The operands are taken so every call site names them, +/// but neither form depends on them. +fn test(form: Form, _s0: u32, _s1: u32) -> bool { + match form { + // 128 V_CMP_F_I32 / 192 V_CMP_F_U32: D[threadId] = 0. + Form::FI32 | Form::FU32 => false, + // 135 V_CMP_T_I32 / 199 V_CMP_T_U32: D[threadId] = 1. + Form::TI32 | Form::TU32 => true, + } +} + +/// Section 3.9 and contract section 3: VCC_LO = OR over the lanes n that +/// exist (`present`) of (EXEC[n] & test(n)) << n, with S0 and S1 of lane n +/// from `operands(n)`. +fn vcc(form: Form, exec: u32, present: u32, operands: impl Fn(usize) -> (u32, u32)) -> u32 { + (0..32) + .filter(|&n| (present & exec) >> n & 1 == 1) + .filter(|&n| { + let (s0, s1) = operands(n); + test(form, s0, s1) + }) + .fold(0, |mask, n| mask | 1 << n) +} + +/// Boundary operands. +const VALUES: [u32; 8] = [ + 0, + 1, + 0x1234_5678, + 0x7fff_ffff, + 0x8000_0000, + 0x8000_0001, + 0xffff_fffe, + 0xffff_ffff, +]; +/// Per-lane inputs: the boundary values first, then 24 more, all different. +const MORE_LANES: [u32; 24] = [ + 2, + 0x0000_00ff, + 0x0000_ffff, + 0x00ff_ffff, + 0x0f0f_0f0f, + 0x4000_0000, + 0x5555_5555, + 0x7fff_fffe, + 0x8765_4321, + 0xaaaa_aaaa, + 0xc000_0000, + 0xf0f0_f0f0, + 0xff00_0000, + 0xffff_0000, + 0xffff_ff00, + 0xffff_fff0, + 3, + 16, + 64, + 65, + 0x0000_0100, + 0x00c0_ffee, + 0x1fff_ffff, + 0xdead_beef, +]; +const LITERALS: [u32; 5] = [0, 1, 0x7fff_ffff, 0x8000_0000, u32::MAX]; +const SGPR_VALUES: [u32; 3] = [0, 0x8000_0000, u32::MAX]; +/// The last one is set explicitly, as a full EXEC written by `s_mov_b32`. +const EXEC_MASKS: [u32; 7] = [ + 0, + 0x5555_5555, + 0xaaaa_aaaa, + 0x8000_0001, + 0x0000_ffff, + 0x7fff_fffe, + u32::MAX, +]; +/// VCC_LO before the compare in the EXEC cases: bits inside and outside every +/// mask above, so a partial VCC update would show. +const STALE_VCC: u32 = 0xa5a5_c33c; + +const COUNTS: [(&str, usize); 11] = [ + ("vopc domain", 4 * 8 * 2), + ("vopc aliasing", 4 * 2), + ("vopc inline integer", 4 * 81), + ("vopc literal", 4 * 5), + ("vopc sgpr source", 4 * 2 * 3), + ("vopc vcc_lo source", 4 * 4), + ("vopc max register", 4 * 3), + ("vopc exec", 4 * (7 + 2)), + ("vopc empty exec reads nothing", 4 * 3), + ("vopc partial wave", 4 * 3), + ("vopc vccz branch", 4 * 3), +]; +/// Per form: 4 uninitialized sources, a missing literal, 9 float inline +/// constants, 9 other special SRC0 selectors, a float constant under empty +/// EXEC, SDWA, DPP16 and two DPP8 forms, the VOP3 `_e64` form, the matching +/// `v_cmpx`, and a lane-derived F result branching over a scalar instruction. +const REJECTIONS: usize = 4 * (4 + 1 + 9 + 9 + 1 + 4 + 1 + 1 + 1); + +const LITERAL: u32 = 255; +const VCC_LO: u32 = 106; +const EXEC_LO: u32 = 126; + +/// ENCODING 0b0111110 in bits 25-31, OP 17-24, VSRC1 9-16, SRC0 0-8 (guide +/// 13.3.3); SRC0 256 + n is VGPR n. +fn vopc(op: u32, src0: u32, vsrc1: u32) -> u32 { + 0b011_1110 << 25 | op << 17 | vsrc1 << 9 | src0 +} + +const fn vgpr(n: u32) -> u32 { + 256 + n +} + +/// `v_mov_b32 v, literal` (VOP1 opcode 1). +fn vmov(reg: u32, value: u32) -> [u32; 2] { + [0x7e00_02ff | reg << 17, value] +} + +/// `s_mov_b32 s, literal` (SOP1 opcode 3). +fn smov(reg: u32, value: u32) -> [u32; 2] { + [0xbe80_03ff | reg << 16, value] +} + +/// `s_mov_b32 exec_lo, -1`. +const FULL_EXEC: u32 = 0xbefe_03c1; +/// `v_mov_b32 v2, vcc_lo`. +const READ_VCC: u32 = 0x7e04_026a; +/// `v_cmp_lt_u32 vcc_lo, v1, v3`: a supported compare, so VCC_LO becomes +/// lane-derived from v1 < v3. +const LT_U32_V1_V3: u32 = 0x7d82_0701; +/// `s_cbranch_vccz` over one word (SOPP opcode 6, SIMM16 = 1). +const VCCZ_OVER_ONE: u32 = 0xbf86_0001; +/// `v_xor_b32 v2, v1, v2` (VOP2 opcode 29), the skipped region. +const XOR_V2_V1: u32 = 29 << 25 | 2 << 17 | 2 << 9 | (256 + 1); + +const PREFIX: [u32; 3] = [0xe030_2000, 0x8000_0100, 0xbf8c_3f70]; +const STORE_V2: [u32; 4] = [0xe070_2000, 0x8001_0200, 0xbbfd_0000, 0xbf81_0000]; + +/// Load v1 = lane input, `setup`, EXEC_LO = `exec` (unless `None`), the compare +/// words, EXEC_LO = -1 again, v2 = vcc_lo, `tail`, then store v2. Returns the +/// program and the compare's byte offset. +fn program(setup: &[u32], exec: Option, compare: &[u32], tail: &[u32]) -> (Vec, usize) { + let mut code = PREFIX.to_vec(); + code.extend(setup); + if let Some(exec) = exec { + code.extend(smov(EXEC_LO, exec)); + } + let offset = 4 * code.len(); + code.extend(compare); + if exec.is_some() { + code.push(FULL_EXEC); + } + code.push(READ_VCC); + code.extend(tail); + code.extend(STORE_V2); + (words(&code), offset) +} + +fn lanes() -> Vec { + VALUES.iter().chain(&MORE_LANES).copied().collect() +} + +/// The lanes of each wave of `input` that exist, as a mask per dispatch index. +fn present(input: &[u32], n: usize) -> u32 { + let in_wave = (input.len() - n / 32 * 32).min(32); + if in_wave == 32 { + u32::MAX + } else { + (1 << in_wave) - 1 + } +} + +/// A case whose lane `n` (dispatch index) of `input` expects +/// `lane(n, x, present-lane mask of its wave)`. +fn case( + (_, name): (Form, &'static str), + family: &'static str, + label: String, + code: Vec, + input: Vec, + lane: impl Fn(usize, u32, u32) -> u32, +) -> Case { + let expected = input + .iter() + .enumerate() + .map(|(n, &x)| lane(n, x, present(&input, n))) + .collect(); + Case { + form: name, + family, + label: format!("{name} {label}"), + code, + input, + expected, + } +} + +fn inline_integer(selector: u32) -> u32 { + match selector { + 128..=192 => selector - 128, + 193..=208 => (-((selector - 192) as i32)) as u32, + _ => unreachable!("not an integer inline constant"), + } +} + +/// The expected lane output under full EXEC: VCC_LO of the lane's wave. +fn full(form: Form, operands: impl Fn(usize) -> (u32, u32)) -> impl Fn(usize, u32, u32) -> u32 { + move |_, _, present| vcc(form, u32::MAX, present, &operands) +} + +fn cases() -> Vec { + let mut cases = Vec::new(); + let input = lanes(); + // S0/S1 for lane n of a wave of `input`, with v1 = input. + let v1 = |n: usize| input[n % 32]; + for entry @ (form, _) in FORMS { + let op = form as u32; + // Every boundary value against all 32 lane inputs, in each slot. + for b in VALUES { + let setup = vmov(3, b); + let (code, _) = program(&setup, None, &[vopc(op, vgpr(1), 3)], &[]); + let label = format!("v1, {b:#x}"); + let f = full(form, |n| (v1(n), b)); + cases.push(case(entry, "vopc domain", label, code, lanes(), f)); + let (code, _) = program(&setup, None, &[vopc(op, vgpr(3), 1)], &[]); + let label = format!("{b:#x}, v1"); + let f = full(form, |n| (b, v1(n))); + cases.push(case(entry, "vopc domain", label, code, lanes(), f)); + } + // Both sources the same register. + let b = 0x8000_0000; + let family = "vopc aliasing"; + let (code, _) = program(&vmov(3, b), None, &[vopc(op, vgpr(1), 1)], &[]); + let f = full(form, |n| (v1(n), v1(n))); + cases.push(case(entry, family, "v1, v1".into(), code, lanes(), f)); + let (code, _) = program(&vmov(3, b), None, &[vopc(op, vgpr(3), 3)], &[]); + let f = full(form, |_| (b, b)); + cases.push(case(entry, family, "v3, v3".into(), code, lanes(), f)); + // Every integer inline constant (-16..64) as SRC0. + for selector in 128..=208 { + let value = inline_integer(selector); + let (code, _) = program(&[], None, &[vopc(op, selector, 1)], &[]); + let label = format!("inline {selector} ({value:#x}), v1"); + let f = full(form, |n| (value, v1(n))); + cases.push(case(entry, "vopc inline integer", label, code, lanes(), f)); + } + // One literal dword after the VOPC word as SRC0. + for literal in LITERALS { + let (code, _) = program(&[], None, &[vopc(op, LITERAL, 1), literal], &[]); + let label = format!("literal {literal:#x}, v1"); + let f = full(form, |n| (literal, v1(n))); + cases.push(case(entry, "vopc literal", label, code, lanes(), f)); + } + // SGPR SRC0: s8 and s105, the highest SGPR. + for reg in [8, 105] { + for value in SGPR_VALUES { + let (code, _) = program(&smov(reg, value), None, &[vopc(op, reg, 1)], &[]); + let label = format!("s{reg} = {value:#x}, v1"); + let f = full(form, |n| (value, v1(n))); + cases.push(case(entry, "vopc sgpr source", label, code, lanes(), f)); + } + } + // vcc_lo SRC0: known (three values), and lane-derived from a supported + // compare; the old VCC_LO is read before the new value is written. + let family = "vopc vcc_lo source"; + for value in SGPR_VALUES { + let (code, _) = program(&smov(VCC_LO, value), None, &[vopc(op, VCC_LO, 1)], &[]); + let label = format!("vcc_lo = {value:#x}, v1"); + let f = full(form, |n| (value, v1(n))); + cases.push(case(entry, family, label, code, lanes(), f)); + } + let b = 0x8000_0000; + let mut setup = vmov(3, b).to_vec(); + setup.push(LT_U32_V1_V3); + let (code, _) = program(&setup, None, &[vopc(op, VCC_LO, 1)], &[]); + // The earlier v_cmp_lt_u32 result, from its own guide relation. + let old = (0..32) + .filter(|&n| v1(n) < b) + .fold(0u32, |mask, n| mask | 1 << n); + let f = full(form, |n| (old, v1(n))); + let label = "vcc_lo lane-derived (v1 < 0x80000000), v1".into(); + cases.push(case(entry, family, label, code, lanes(), f)); + // v255, the highest VGPR, in each slot and both. + let b = 0x7fff_ffff; + let family = "vopc max register"; + let setup = vmov(255, b); + for (src0, vsrc1, label) in [ + (vgpr(255), 1, "v255, v1"), + (vgpr(1), 255, "v1, v255"), + (vgpr(255), 255, "v255, v255"), + ] { + let (code, _) = program(&setup, None, &[vopc(op, src0, vsrc1)], &[]); + let f = full(form, |n| { + let pick = |is_v255: bool| if is_v255 { b } else { v1(n) }; + (pick(src0 == vgpr(255)), pick(vsrc1 == 255)) + }); + cases.push(case(entry, family, label.into(), code, lanes(), f)); + } + // EXEC around the compare, with a stale VCC_LO: inactive lanes' bits + // are cleared, active lanes take the test. + let family = "vopc exec"; + let b = 0x0f0f_0f0f; + let mut setup = vmov(3, b).to_vec(); + setup.extend(smov(VCC_LO, STALE_VCC)); + for exec in EXEC_MASKS { + let (code, _) = program(&setup, Some(exec), &[vopc(op, vgpr(1), 3)], &[]); + let label = format!("exec {exec:#x}, vcc_lo was {STALE_VCC:#x}, v1, {b:#x}"); + cases.push(case(entry, family, label, code, lanes(), |_, _, p| { + vcc(form, exec, p, |n| (v1(n), b)) + })); + } + // A literal SRC0 under partial and empty EXEC: its dword is consumed. + for exec in [0x00f0_0f00, 0] { + let compare = [vopc(op, LITERAL, 3), 0x8000_0000]; + let (code, _) = program(&setup, Some(exec), &compare, &[]); + let label = format!("exec {exec:#x}, literal 0x80000000, v3"); + cases.push(case(entry, family, label, code, lanes(), |_, _, p| { + vcc(form, exec, p, |_| (0x8000_0000, b)) + })); + } + // EXEC_LO = 0: no source is read, so uninitialized ones are accepted + // (contract section 5) and VCC_LO becomes 0. + let family = "vopc empty exec reads nothing"; + for (src0, vsrc1, label) in [ + (20, 1, "s20 (unknown), v1"), + (VCC_LO, 1, "vcc_lo (uninitialized), v1"), + (vgpr(9), 9, "v9, v9 (uninitialized)"), + ] { + let (code, _) = program(&[], Some(0), &[vopc(op, src0, vsrc1)], &[]); + let label = format!("exec 0, {label}"); + cases.push(case(entry, family, label, code, lanes(), |_, _, p| { + vcc(form, 0, p, |_| (0, 0)) + })); + } + // A final wave with absent lanes: 7 lanes, and 45 lanes (one full wave + // and 13 lanes), also with partial EXEC in both waves. + let family = "vopc partial wave"; + let long: Vec = lanes() + .into_iter() + .chain(lanes().into_iter().take(13)) + .collect(); + // Lane k of the wave holding dispatch index n; `vcc` asks only for + // lanes that exist. + let wave_lane = |input: &[u32], n: usize, k: usize| input[n / 32 * 32 + k]; + let short = lanes()[..7].to_vec(); + for (exec, input, label) in [ + (u32::MAX, short, "7 lanes".to_string()), + (u32::MAX, long.clone(), "45 lanes".to_string()), + (0x5555_5555, long, "45 lanes, exec 0x55555555".to_string()), + ] { + let exec_word = (exec != u32::MAX).then_some(exec); + let (code, _) = program(&vmov(3, 5), exec_word, &[vopc(op, vgpr(1), 3)], &[]); + let copy = input.clone(); + cases.push(case(entry, family, label, code, input, |n, _, p| { + vcc(form, exec, p, |k| (wave_lane(©, n, k), 5)) + })); + } + // s_cbranch_vccz after the compare (guide 3.9: VCCZ = VCC_LO == 0 in + // wave32). Taken: v2 = VCC_LO (0). Not taken: v2 = VCC_LO ^ v1. + let family = "vopc vccz branch"; + for exec in [u32::MAX, 0x0000_8000, 0] { + let (code, _) = program( + &vmov(3, 5), + Some(exec), + &[vopc(op, vgpr(1), 3)], + &[VCCZ_OVER_ONE, XOR_V2_V1], + ); + let label = format!("exec {exec:#x}, then s_cbranch_vccz"); + cases.push(case(entry, family, label, code, lanes(), |_, x, p| { + let mask = vcc(form, exec, p, |n| (v1(n), 5)); + if mask == 0 { 0 } else { mask ^ x } + })); + } + } + cases +} + +/// Programs both interpreters must refuse, with the refusing byte offset. +fn rejections() -> Vec<(String, Vec, usize)> { + let setup = vmov(3, 7); + let mut all = Vec::new(); + for (form, name) in FORMS { + let op = form as u32; + let mut reject = |label: String, (code, offset): (Vec, usize)| { + all.push((format!("{name} {label}"), code, offset)); + }; + // Uninitialized sources under nonzero EXEC (contract sections 4 and 5). + for (src0, vsrc1, label) in [ + (20, 3, "s20 unknown"), + (VCC_LO, 3, "vcc_lo uninitialized"), + (vgpr(9), 3, "v9 uninitialized as SRC0"), + (vgpr(1), 9, "v9 uninitialized as VSRC1"), + ] { + reject( + label.into(), + program(&setup, None, &[vopc(op, src0, vsrc1)], &[]), + ); + } + // A literal SRC0 with no literal dword: the program ends at the word. + let mut code = PREFIX.to_vec(); + code.extend(setup); + let offset = 4 * code.len(); + code.push(vopc(op, LITERAL, 3)); + reject("missing literal".into(), (words(&code), offset)); + // Float inline constants 240-248, VCC_HI, TTMP-adjacent and special + // selectors outside the allowlist (contract section 2). + for src0 in (240..=248).chain([107, 124, 125, 126, 127, 251, 252, 253, 254]) { + let label = format!("src0 {src0}"); + reject(label, program(&setup, None, &[vopc(op, src0, 3)], &[])); + } + // Rejected at decode independent of EXEC. + let label = "src0 240 under empty exec".into(); + reject(label, program(&setup, Some(0), &[vopc(op, 240, 3)], &[])); + // SDWA (249), DPP16 (250), DPP8 (233) and DPP8FI (234) with SRC0 v1. + for (src0, extension) in [ + (249, 0x0606_0601), + (250, 0xff00_e401), + (233, 0xfac6_8801), + (234, 0xfac6_8801), + ] { + let label = format!("src0 {src0} extension"); + reject( + label, + program(&setup, None, &[vopc(op, src0, 3), extension], &[]), + ); + } + // The VOP3 `_e64` form (ENCODING 0b110101, OP = the VOPC opcode, + // SDST vcc_lo): v_cmp vcc_lo, v1, v3. + let vop3 = [0xd400_0000 | op << 16 | VCC_LO, vgpr(1) | vgpr(3) << 9]; + reject("_e64".into(), program(&setup, None, &vop3, &[])); + // The matching v_cmpx (writes EXEC): opcode + 16 (Table 61: 144, 151, + // 208, 215). + let label = format!("v_cmpx opcode {}", op + 16); + reject( + label, + program(&setup, None, &[vopc(op + 16, vgpr(1), 3)], &[]), + ); + // F under nonzero EXEC is lane-derived even though its value is 0, so + // a vccz branch over `s_mov_b32 s8, 0` is refused at that word. + // Layout: compare, v2 = vcc_lo, branch, then the s_mov at +12. + let tail = [VCCZ_OVER_ONE, 0xbe88_0380]; + let (code, compare) = program(&setup, None, &[vopc(op, vgpr(1), 3)], &tail); + reject("lane-derived vccz over s_mov".into(), (code, compare + 12)); + } + all +} + +fn assert_rejected_at(label: &str, code: &[u8], offset: usize, input: &[u32]) { + match xenora_ref::execute(code, input) { + Ok(_) => panic!("reference accepted {label}"), + Err(error) => assert_eq!( + error.offset, offset, + "reference rejected {label} elsewhere: {error:?}" + ), + } + match independent_ref::execute(code, input) { + Ok(_) => panic!("independent accepted {label}"), + Err(error) => assert!( + error.starts_with(&format!("{offset:#x}:")), + "independent rejected {label} elsewhere: {error}" + ), + } +} + +fn tally(cases: &[Case], key: fn(&Case) -> &'static str) -> BTreeMap<&'static str, usize> { + let mut counts = BTreeMap::new(); + for case in cases { + *counts.entry(key(case)).or_default() += 1; + } + counts +} + +/// Runs `execute` on every case and returns one line per failing family: the +/// number of failures and the first one. +fn failures( + cases: &[Case], + execute: impl Fn(&[u8], &[u32]) -> Result, String>, +) -> Vec { + let mut failed: BTreeMap<&str, (usize, String)> = BTreeMap::new(); + for case in cases { + let output = execute(&case.code, &case.input); + if output.as_deref().ok() != Some(case.expected.as_slice()) { + let first = format!("{}: {output:x?}, expected {:x?}", case.label, case.expected); + failed.entry(case.family).or_insert((0, first)).0 += 1; + } + } + failed + .into_iter() + .map(|(family, (n, first))| format!(" {family}: {n} failed, first: {first}")) + .collect() +} + +fn checked_cases() -> Vec { + let cases = cases(); + assert_eq!(tally(&cases, |case| case.family), BTreeMap::from(COUNTS)); + cases +} + +#[test] +fn expectations_follow_the_guide_examples() { + // Worked by hand from section 3.9 and Table 61. + for (form, exec, present, mask) in [ + (Form::TI32, u32::MAX, u32::MAX, u32::MAX), + (Form::TU32, 0x5555_5555, u32::MAX, 0x5555_5555), + (Form::TI32, u32::MAX, 0x7f, 0x7f), + (Form::TU32, 0xf0f0_f0f0, 0x1fff, 0x10f0), + (Form::TI32, 0, u32::MAX, 0), + (Form::FI32, u32::MAX, u32::MAX, 0), + (Form::FU32, 0x8000_0001, u32::MAX, 0), + ] { + assert_eq!( + vcc(form, exec, present, |_| (0, 0)), + mask, + "{form:?} {exec:#x}" + ); + } +} + +#[test] +fn vopc_f_t_match_the_guide_on_the_reference() { + let cases = checked_cases(); + let failed = failures(&cases, |code, input| { + xenora_ref::execute(code, input).map_err(|error| format!("{error:?}")) + }); + assert!( + failed.is_empty(), + "reference disagrees with the guide:\n{}", + failed.join("\n") + ); + eprintln!("vopc_f_t: {} reference cases", cases.len()); + for (form, n) in tally(&cases, |case| case.form) { + eprintln!(" form {form}: {n}"); + } +} + +#[test] +fn vopc_f_t_match_the_guide_on_the_independent_interpreter() { + let cases = checked_cases(); + let failed = failures(&cases, independent_ref::execute); + assert!( + failed.is_empty(), + "independent interpreter disagrees with the guide:\n{}", + failed.join("\n") + ); + eprintln!("vopc_f_t: {} independent-interpreter cases", cases.len()); +} + +#[test] +fn vopc_f_t_outside_the_contract_are_rejected() { + let rejections = rejections(); + assert_eq!(rejections.len(), REJECTIONS); + for (label, code, offset) in &rejections { + assert_rejected_at(label, code, *offset, &lanes()); + } + eprintln!("vopc_f_t: {} rejections", rejections.len()); +} + +#[test] +fn other_constant_compares_stay_unsupported() { + // F and T/TRU of the float, 64-bit and v_cmpx groups (Table 61): + // V_CMP_F_F32 0, V_CMP_TRU_F32 15, V_CMPX_F_F32 16, V_CMPX_TRU_F32 31, + // V_CMP_F_I64 160, V_CMP_T_I64 167, V_CMPX_F_I64 176, V_CMPX_T_I64 183, + // V_CMP_F_U64 224, V_CMP_T_U64 231, V_CMPX_F_U64 240, V_CMPX_T_U64 247. + let setup = vmov(3, 7); + for op in [0, 15, 16, 31, 160, 167, 176, 183, 224, 231, 240, 247] { + let (code, offset) = program(&setup, None, &[vopc(op, vgpr(1), 3)], &[]); + assert_rejected_at(&format!("opcode {op}"), &code, offset, &lanes()); + } +} + +#[test] +#[ignore = "requires a native Metal device with API and shader validation, and the translator's F/T forms"] +fn vopc_f_t_match_the_guide_on_native_metal() { + assert_eq!(std::env::var("MTL_DEBUG_LAYER").as_deref(), Ok("1")); + assert_eq!(std::env::var("MTL_SHADER_VALIDATION").as_deref(), Ok("1")); + for (label, code, offset) in rejections() { + let at = match compile(Architecture::Gfx1030, &code) { + Err(CompileError::Decode(error)) => error.offset, + Err(CompileError::Verify { offset, .. }) => offset, + other => panic!("compiler did not reject {label}: {other:?}"), + }; + assert_eq!(at, offset, "compiler rejected {label} elsewhere"); + } + let cases = checked_cases(); + let (failures, programs) = harness::check_metal(&cases); + failures.assert_none("native Metal disagrees with the guide"); + eprintln!( + "vopc_f_t: {} Metal cases in {programs} programs", + cases.len() + ); +} From b559fb575ca14e453fa4f6a02fabff3b43c360cc Mon Sep 17 00:00:00 2001 From: elforeign <324243036+elforeign@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:38:55 -0600 Subject: [PATCH 03/15] isa, decoder, shader: v_cmp_{f,t}_{i32,u32} through the semantic registry (#215) Adds the four constant Wave32 VOPC compares as registry forms with the relations f and t (guide Table 59 offsets 0 and 7), valid only for the vopc_vcc rule, backed by false_b32/true_b32 primitives. They keep the #239 contract: sources are decoded and checked as for every compare, VCC_LO := EXEC & existing lanes & test, fully written, and the mask is lane-derived. Their MSL wave mask reads no operand bits. A new LLVM-assembled fixture covers F clearing a stale VCC, T and F under partial EXEC, T reading vcc_lo and runtime s_cbranch_vccz on both results; the oracle merged from task/215-vopc-oracle supplies the reference side. Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com> --- CHANGELOG.md | 1 + crates/decoder/tests/gfx1030.rs | 9 +- crates/isa/generate_semantics.py | 8 +- crates/isa/semantics/rdna2.toml | 89 +++++++++++ crates/isa/src/lib.rs | 4 + crates/isa/src/primitive.rs | 10 ++ crates/isa/src/semantics_gen.rs | 138 +++++++++++++++++- crates/isa/tests/semantics.rs | 4 +- crates/shader/src/lib.rs | 13 +- crates/shader/tests/compiler.rs | 14 ++ docs/assets/xenora-progress.svg | 8 +- docs/shaders/instruction-coverage.md | 4 + docs/shaders/reference-interpreter.md | 2 +- docs/shaders/semantic-coverage.md | 4 +- docs/shaders/vector-compare.md | 12 +- docs/status.toml | 48 ++++++ fixtures/golden/vector-compare-ft.ir | 28 ++++ fixtures/golden/vector-compare-ft.metal | 76 ++++++++++ fixtures/rdna2/vector-compare-ft.bin | Bin 0 -> 164 bytes fixtures/rdna2/vector-compare-ft.s | 45 ++++++ scripts/assemble-fixture.sh | 2 +- .../test_generate_semantics.py | 16 ++ tests/validation/known_answers.rs | 43 ++++++ 23 files changed, 554 insertions(+), 24 deletions(-) create mode 100644 fixtures/golden/vector-compare-ft.ir create mode 100644 fixtures/golden/vector-compare-ft.metal create mode 100644 fixtures/rdna2/vector-compare-ft.bin create mode 100644 fixtures/rdna2/vector-compare-ft.s diff --git a/CHANGELOG.md b/CHANGELOG.md index acc1736..4efdfe2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,6 +30,7 @@ remains unsupported. - Added advisory infrastructure QA helpers under `scripts/qa/` and `scripts/release/` (issue #277): exit-status-preserving orchestration with JSON reports, PR scope/DCO/artifact checks, benchmark percentile analysis over existing samples, environment and repository health diagnostics, ARM64 Mach-O/bundle/codesign helpers, and checksum manifests. Covered by `tests/qa/` and `tests/release/`; checks stay advisory until reviewed. - Recorded agent-queue live smoke evidence for issue #180 against the disposable private repository `ranveersoni98/xenora-agent-queue-smoke`, including claim grant, overlap refusal, release, not-ready denial, progress renew and a successful audit dispatch after fixing comment-only `apply_actions` and audit permissions/argparse issues. - Added twelve gfx1030 VOP2 vector integer forms through the semantic registry: `v_mul_i32_i24`, `v_mul_hi_i32_i24`, `v_mul_u32_u24`, `v_mul_hi_u32_u24`, `v_min_i32`, `v_max_i32`, `v_min_u32`, `v_max_u32`, `v_xnor_b32`, `v_add_nc_u32`, `v_sub_nc_u32` and `v_subrev_nc_u32` (AMD guide section 12.7), with SRC0 a VGPR, an SGPR, `vcc_lo`, an inline integer or a literal. The registry gained a `vop2_vgpr` operand rule, the vector operations `mul24` and `mul_hi24`, a declared `source_order` for SUBREV, and a per-lane `VectorBinary` that selects one reusable MSL template per operation. Both reference interpreters, written separately from the guide, run the same twelve forms and are checked against 2,040 guide-derived cases, each asserting every lane of a 7-, 32- or 45-lane dispatch (partial, empty and full EXEC), on both CPU interpreters and on native Metal; 575 rejected programs are refused by both interpreters and by the compiler at the same word. A new LLVM-assembled fixture computes every lane from its own input. Part of #215. +- Moved the twelve Wave32 VOPC integer compares from #239 into the semantic registry (operand rule `vopc_vcc`, `vcc = "lane_mask"`, `wave = "wave32"`) with no behaviour change, and added `v_cmp_f_i32`, `v_cmp_t_i32`, `v_cmp_f_u32` and `v_cmp_t_u32` as registry forms under the same Wave32 VCC/EXEC contract, verified by an independent guide-derived oracle (`tests/validation/tests/vopc_f_t.rs`), a new LLVM-assembled fixture and native Metal (part of #215). `v_cmpx_*`, the VOP3 encoding and Wave64 stay unsupported. - Added sixteen gfx1030 SOP2 integer forms through the semantic registry: `s_min_i32`, `s_min_u32`, `s_max_i32`, `s_max_u32`, `s_cselect_b32`, `s_bfm_b32`, `s_mul_i32`, `s_bfe_u32`, `s_bfe_i32`, `s_absdiff_i32`, `s_lshl1_add_u32` to `s_lshl4_add_u32`, `s_mul_hi_u32` and `s_mul_hi_i32` (AMD guide section 12.1). Min and max set SCC from the strict compare (a tie gives S1 and SCC 0), `s_cselect_b32` reads SCC and is refused when SCC is unset, and BFM, MUL, MUL_HI and CSELECT leave SCC unchanged. The registry gained these primitives, a `selected_src0` SCC effect, the select's SCC input and a declared `shift_amount` for the shift-and-add forms; `ScalarAluOp::evaluate` now returns an optional SCC. Both reference interpreters, written separately from the guide, run the same sixteen forms and are checked against 21,070 guide-derived cases on both CPU interpreters and on native Metal; 597 rejected programs are refused by both interpreters and by the compiler. A new LLVM-assembled fixture covers all sixteen. Part of #215. - Added audio PCM streaming and sandboxed virtual filesystem (VFS) integration to the native application runtime (Gate 6, #284). The C interface gains audio management functions (`xenora_session_audio_init`, `xenora_session_audio_submit`, `xenora_session_audio_read`, `xenora_session_audio_status`, `xenora_session_audio_set_volume`) and virtual filesystem functions (`xenora_session_vfs_set_root`, `xenora_session_vfs_open`, `xenora_session_vfs_read`, `xenora_session_vfs_seek`, `xenora_session_vfs_close`, `xenora_session_run_audio_vfs_fixture`). The audio subsystem implements a bounded ring buffer supporting configurable sample rates, channel configurations, PCM formats (S16LE, F32LE), volume attenuation, mute, and buffer underrun tracking. The virtual filesystem operates within an explicitly configured, sandboxed directory root (`fixtures/assets`), strictly rejecting path traversal attempts (`..`, absolute paths, null bytes) and invalid or stale handles, while supporting sequential and seekable file reads (`XENORA_SEEK_SET`, `XENORA_SEEK_CUR`, `XENORA_SEEK_END`). An original PE fixture (`fixtures/pe/audio_vfs.exe`, generated by `fixtures/pe/audio_vfs.py` using only the supported ARM64 DBT instruction subset) opens `asset.bin` (generated by `fixtures/assets/generate.py`), loads a 2x2 RGBA texture and 256 PCM audio samples via VFS, initializes audio, submits the PCM audio queue, and renders the loaded texture on Metal. Verified with unit tests, four Metal acceptance tests in `crates/ffi/tests/audio_vfs.rs`, UI controls and a `--smoke-audio-vfs` CLI in `Xenora.app`. - Added persistent GPU resources, dynamic texture updates, and resource retirement to the native application (Gate 5, #279). The C interface gains `xenora_resource`, resource types (`XENORA_RESOURCE_TYPE_*`), `xenora_session_create_texture`, `xenora_session_update_texture`, `xenora_session_destroy_resource`, `xenora_session_resource_info`, `xenora_session_render_textured`, and `xenora_session_run_textured_fixture`. Persistent GPU resources (textures) are explicitly allocated and owned by the execution session, surviving across execution slices without re-allocation. Dynamic texture subregion updates modify GPU texture contents in-place on native Metal. Resource retirement is completion-aware: destroying a resource held by in-flight GPU execution marks it retired and safely defers destruction until in-flight work completes, while rejecting subsequent caller queries with typed error codes. An original PE fixture (`fixtures/pe/textured.exe`, generated by `fixtures/pe/textured.py` using only the supported ARM64 DBT instruction subset) creates a persistent 2x2 texture via `xenora.dll!texture_create`, renders frame 0, updates pixels via `xenora.dll!texture_update`, renders frame 1, and retires the resource via `xenora.dll!texture_destroy`. Xenora.app gains "Run textured fixture" controls and `--smoke-resources`. Six GPU acceptance tests with Metal validation verify persistent texture lifecycle across multiple frames, dynamic 1x1 and 2x1 subregion updates on native Metal, completion-aware deferred retirement, rejection of invalid/stale/double-destroyed handles, slot reuse across 200 cycles without leaking, and full guest fixture execution. Wired acceptance tests into `scripts/test-gpu.sh`. diff --git a/crates/decoder/tests/gfx1030.rs b/crates/decoder/tests/gfx1030.rs index 257ee62..d9c3f97 100644 --- a/crates/decoder/tests/gfx1030.rs +++ b/crates/decoder/tests/gfx1030.rs @@ -461,6 +461,8 @@ fn reference_op(instruction: Instruction) -> Op { CompareRelation::Greater => 4, CompareRelation::NotEqual => 5, CompareRelation::GreaterOrEqual => 6, + CompareRelation::False => 0, + CompareRelation::True => 7, }, signed: op.signed(), }, @@ -526,12 +528,13 @@ fn compares_fixture_instructions_against_llvm() { include_bytes!("../../../fixtures/rdna2/scalar-arith.bin"), include_bytes!("../../../fixtures/rdna2/vector-integer.bin"), include_bytes!("../../../fixtures/rdna2/vector-compare.bin"), + include_bytes!("../../../fixtures/rdna2/vector-compare-ft.bin"), high_registers, &matrix, ] { count += compare_against_llvm(fixture, &mut forms); } - assert_eq!(forms.len(), 100, "forms compared: {forms:?}"); + assert_eq!(forms.len(), 104, "forms compared: {forms:?}"); eprintln!( "{count} three-way instruction comparisons across {} forms", forms.len() @@ -596,7 +599,7 @@ fn assemble_matrix() -> Vec { ); // Every supported VOPC form with each source class: VGPR, SGPR, vcc_lo, // inline integers at both ends, inline zero and a literal. - for relation in ["lt", "eq", "le", "gt", "ne", "ge"] { + for relation in ["f", "lt", "eq", "le", "gt", "ne", "ge", "t"] { for kind in ["i32", "u32"] { for src0 in [ "v255", @@ -744,8 +747,6 @@ fn distinguishes_llvm_invalid_encodings_from_xenora_subset_rejections() { let outside_subset: &[&[u32]] = &[ &[0x7e04_026b], // VOP1 VCC_HI source &[0x7da2_0501], // v_cmpx_eq_u32_e32 - &[0x7d00_0501], // v_cmp_f_i32_e32 - &[0x7d0e_0501], // v_cmp_t_i32_e32 &[0xd482_006a, 0x0002_0501], // v_cmp_lt_i32_e64 &[0x8788_0908], // s_and_b64 &[0x8008_ffff, 0x1234_5678], // SOP2 with two literal sources diff --git a/crates/isa/generate_semantics.py b/crates/isa/generate_semantics.py index 4612a69..337b897 100755 --- a/crates/isa/generate_semantics.py +++ b/crates/isa/generate_semantics.py @@ -60,8 +60,10 @@ SOURCE_BITS = {8, 16} RELATION_KEY = "relation" RELATIONS = { "eq": "Equal", "lg": "NotEqual", "gt": "Greater", "ge": "GreaterOrEqual", - "lt": "Less", "le": "LessOrEqual", + "lt": "Less", "le": "LessOrEqual", "f": "False", "t": "True", } +# F and T exist only as VOPC compares (guide Table 59 offsets 0 and 7). +VECTOR_ONLY_RELATIONS = {"f", "t"} # (relation, signedness) -> primitive. Equality does not depend on signedness, # so both declared signednesses of EQ and LG share one primitive. COMPARE_PRIMITIVES = { @@ -71,6 +73,8 @@ COMPARE_PRIMITIVES = { ("ge", "signed"): "ge_i32", ("ge", "unsigned"): "ge_u32", ("lt", "signed"): "lt_i32", ("lt", "unsigned"): "lt_u32", ("le", "signed"): "le_i32", ("le", "unsigned"): "le_u32", + ("f", "signed"): "false_b32", ("f", "unsigned"): "false_b32", + ("t", "signed"): "true_b32", ("t", "unsigned"): "true_b32", } # Logical operations take untyped bits; arithmetic ones never do. Shifts take # the signedness their primitive names, and their S1 is an unsigned count. @@ -564,6 +568,8 @@ def validate(registry, snapshot): errors.append(f"{label}: unknown or missing {RELATION_KEY} {relation!r}") elif (relation, form["signedness"]) not in COMPARE_PRIMITIVES: errors.append(f"{label}: no primitive implements {relation}/{form['signedness']}") + elif relation in VECTOR_ONLY_RELATIONS and _rule_kind(form) != "vector_compare": + errors.append(f"{label}: relation {relation} exists only for VOPC compares") # SOPC compares write SCC; VOPC compares write VCC and leave SCC. scc = "unchanged" if _rule_kind(form) == "vector_compare" else "relation" if form["scc"] != scc: diff --git a/crates/isa/semantics/rdna2.toml b/crates/isa/semantics/rdna2.toml index eba44be..29f678a 100644 --- a/crates/isa/semantics/rdna2.toml +++ b/crates/isa/semantics/rdna2.toml @@ -1678,3 +1678,92 @@ spec = [ { document = "guide", section = "3.9", page = 19 }, ] verify = ["reference", "independent", "metal", "llvm_encoding"] + +# ---- VOPC F and T compares (guide Table 59 offsets 0 and 7) ---- +# The test is false or true for every lane, so VCC_LO := 0 or the EXEC lanes +# that exist. Sources are still decoded and checked as for the other compares +# (docs/shaders/vector-compare.md section 5). + +[[form]] +name = "V_CMP_F_I32" +family = "VOPC" +opcode = 128 +variant = "CmpFI32" +operation = "compare" +relation = "f" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_CMP_T_I32" +family = "VOPC" +opcode = 135 +variant = "CmpTI32" +operation = "compare" +relation = "t" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_CMP_F_U32" +family = "VOPC" +opcode = 192 +variant = "CmpFU32" +operation = "compare" +relation = "f" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_CMP_T_U32" +family = "VOPC" +opcode = 199 +variant = "CmpTU32" +operation = "compare" +relation = "t" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] diff --git a/crates/isa/src/lib.rs b/crates/isa/src/lib.rs index a9269db..b5edab6 100644 --- a/crates/isa/src/lib.rs +++ b/crates/isa/src/lib.rs @@ -111,6 +111,10 @@ pub enum CompareRelation { NotEqual, /// S0 >= S1 (offset 6). GreaterOrEqual, + /// Never holds (VOPC F, offset 0). + False, + /// Always holds (VOPC T, offset 7). + True, } /// Output targeted by a supported uncompressed four-component export. diff --git a/crates/isa/src/primitive.rs b/crates/isa/src/primitive.rs index 3395572..bc4eea8 100644 --- a/crates/isa/src/primitive.rs +++ b/crates/isa/src/primitive.rs @@ -99,6 +99,16 @@ pub const fn ashr_nonzero_i32(a: u32, count: u32) -> (u32, bool) { (value, value != 0) } +/// The VOPC F test: false for every operand pair. +pub const fn false_b32(_a: u32, _b: u32) -> bool { + false +} + +/// The VOPC T test: true for every operand pair. +pub const fn true_b32(_a: u32, _b: u32) -> bool { + true +} + /// `a == b` on the raw bits; signedness does not matter for equality. pub const fn eq_b32(a: u32, b: u32) -> bool { a == b diff --git a/crates/isa/src/semantics_gen.rs b/crates/isa/src/semantics_gen.rs index 0366a2b..8e889fb 100644 --- a/crates/isa/src/semantics_gen.rs +++ b/crates/isa/src/semantics_gen.rs @@ -1439,6 +1439,14 @@ pub enum VectorCompareOp { CmpNeU32, /// `v_cmp_ge_u32` (VOPC opcode 198): unsigned compare ge, VCC = lane_mask. CmpGeU32, + /// `v_cmp_f_i32` (VOPC opcode 128): signed compare f, VCC = lane_mask. + CmpFI32, + /// `v_cmp_t_i32` (VOPC opcode 135): signed compare t, VCC = lane_mask. + CmpTI32, + /// `v_cmp_f_u32` (VOPC opcode 192): unsigned compare f, VCC = lane_mask. + CmpFU32, + /// `v_cmp_t_u32` (VOPC opcode 199): unsigned compare t, VCC = lane_mask. + CmpTU32, } /// VectorCompareOp by VOPC OP field value; `None` for undeclared opcodes. @@ -1571,13 +1579,14 @@ const VECTOR_COMPARE_OP_BY_OPCODE: [Option; 256] = [ None, None, None, - None, + Some(VectorCompareOp::CmpFI32), Some(VectorCompareOp::CmpLtI32), Some(VectorCompareOp::CmpEqI32), Some(VectorCompareOp::CmpLeI32), Some(VectorCompareOp::CmpGtI32), Some(VectorCompareOp::CmpNeI32), Some(VectorCompareOp::CmpGeI32), + Some(VectorCompareOp::CmpTI32), None, None, None, @@ -1634,15 +1643,14 @@ const VECTOR_COMPARE_OP_BY_OPCODE: [Option; 256] = [ None, None, None, - None, - None, + Some(VectorCompareOp::CmpFU32), Some(VectorCompareOp::CmpLtU32), Some(VectorCompareOp::CmpEqU32), Some(VectorCompareOp::CmpLeU32), Some(VectorCompareOp::CmpGtU32), Some(VectorCompareOp::CmpNeU32), Some(VectorCompareOp::CmpGeU32), - None, + Some(VectorCompareOp::CmpTU32), None, None, None, @@ -1703,7 +1711,7 @@ const VECTOR_COMPARE_OP_BY_OPCODE: [Option; 256] = [ impl VectorCompareOp { /// Every operation, in registry order. - pub const ALL: [Self; 12] = [ + pub const ALL: [Self; 16] = [ Self::CmpLtI32, Self::CmpEqI32, Self::CmpLeI32, @@ -1716,6 +1724,10 @@ impl VectorCompareOp { Self::CmpGtU32, Self::CmpNeU32, Self::CmpGeU32, + Self::CmpFI32, + Self::CmpTI32, + Self::CmpFU32, + Self::CmpTU32, ]; /// Selects the operation from a first instruction word: the VOPC encoding @@ -1742,6 +1754,10 @@ impl VectorCompareOp { Self::CmpGtU32 => "v_cmp_gt_u32", Self::CmpNeU32 => "v_cmp_ne_u32", Self::CmpGeU32 => "v_cmp_ge_u32", + Self::CmpFI32 => "v_cmp_f_i32", + Self::CmpTI32 => "v_cmp_t_i32", + Self::CmpFU32 => "v_cmp_f_u32", + Self::CmpTU32 => "v_cmp_t_u32", } } @@ -1760,6 +1776,10 @@ impl VectorCompareOp { Self::CmpGtU32 => 77, Self::CmpNeU32 => 78, Self::CmpGeU32 => 79, + Self::CmpFI32 => 80, + Self::CmpTI32 => 81, + Self::CmpFU32 => 82, + Self::CmpTU32 => 83, }] } @@ -1778,6 +1798,10 @@ impl VectorCompareOp { Self::CmpGtU32 => "v_cmp_gt_u32_e32", Self::CmpNeU32 => "v_cmp_ne_u32_e32", Self::CmpGeU32 => "v_cmp_ge_u32_e32", + Self::CmpFI32 => "v_cmp_f_i32_e32", + Self::CmpTI32 => "v_cmp_t_i32_e32", + Self::CmpFU32 => "v_cmp_f_u32_e32", + Self::CmpTU32 => "v_cmp_t_u32_e32", } } @@ -1796,6 +1820,10 @@ impl VectorCompareOp { Self::CmpGtU32 => false, Self::CmpNeU32 => false, Self::CmpGeU32 => false, + Self::CmpFI32 => true, + Self::CmpTI32 => true, + Self::CmpFU32 => false, + Self::CmpTU32 => false, } } @@ -1814,6 +1842,10 @@ impl VectorCompareOp { Self::CmpGtU32 => CompareRelation::Greater, Self::CmpNeU32 => CompareRelation::NotEqual, Self::CmpGeU32 => CompareRelation::GreaterOrEqual, + Self::CmpFI32 => CompareRelation::False, + Self::CmpTI32 => CompareRelation::True, + Self::CmpFU32 => CompareRelation::False, + Self::CmpTU32 => CompareRelation::True, } } @@ -1832,12 +1864,16 @@ impl VectorCompareOp { Self::CmpGtU32 => primitive::gt_u32(src0, src1), Self::CmpNeU32 => primitive::ne_b32(src0, src1), Self::CmpGeU32 => primitive::ge_u32(src0, src1), + Self::CmpFI32 => primitive::false_b32(src0, src1), + Self::CmpTI32 => primitive::true_b32(src0, src1), + Self::CmpFU32 => primitive::false_b32(src0, src1), + Self::CmpTU32 => primitive::true_b32(src0, src1), } } } /// Identity of every registry form, in registry order. -pub const FORM_IDS: [(&str, EncodingFamily); 80] = [ +pub const FORM_IDS: [(&str, EncodingFamily); 84] = [ ("S_ADD_U32", EncodingFamily::Sop2), ("S_SUB_U32", EncodingFamily::Sop2), ("S_ADD_I32", EncodingFamily::Sop2), @@ -1918,10 +1954,14 @@ pub const FORM_IDS: [(&str, EncodingFamily); 80] = [ ("V_CMP_GT_U32", EncodingFamily::Vopc), ("V_CMP_NE_U32", EncodingFamily::Vopc), ("V_CMP_GE_U32", EncodingFamily::Vopc), + ("V_CMP_F_I32", EncodingFamily::Vopc), + ("V_CMP_T_I32", EncodingFamily::Vopc), + ("V_CMP_F_U32", EncodingFamily::Vopc), + ("V_CMP_T_U32", EncodingFamily::Vopc), ]; /// One validated row per registry form, in registry order. -pub static FORMS: [FormSemantics; 80] = [ +pub static FORMS: [FormSemantics; 84] = [ FormSemantics { name: "S_ADD_U32", family: EncodingFamily::Sop2, @@ -3602,4 +3642,88 @@ pub static FORMS: [FormSemantics; 80] = [ spec: &[SpecRef { document: Document::Guide, section: "12.9", page: 150 }, SpecRef { document: Document::Guide, section: "3.9", page: 19 }], verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], }, + FormSemantics { + name: "V_CMP_F_I32", + family: EncodingFamily::Vopc, + opcode: 128, + operation: Operation::Compare, + signedness: Signedness::Signed, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: Some(CompareRelation::False), + scc: SccEffect::Unchanged, + vcc: MaskEffect::LaneMask, + exec: MaskEffect::Unchanged, + wave: Wave::Wave32, + operands: OperandRule::VopcVcc, + spec: &[SpecRef { document: Document::Guide, section: "12.9", page: 150 }, SpecRef { document: Document::Guide, section: "3.9", page: 19 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_CMP_T_I32", + family: EncodingFamily::Vopc, + opcode: 135, + operation: Operation::Compare, + signedness: Signedness::Signed, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: Some(CompareRelation::True), + scc: SccEffect::Unchanged, + vcc: MaskEffect::LaneMask, + exec: MaskEffect::Unchanged, + wave: Wave::Wave32, + operands: OperandRule::VopcVcc, + spec: &[SpecRef { document: Document::Guide, section: "12.9", page: 150 }, SpecRef { document: Document::Guide, section: "3.9", page: 19 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_CMP_F_U32", + family: EncodingFamily::Vopc, + opcode: 192, + operation: Operation::Compare, + signedness: Signedness::Unsigned, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: Some(CompareRelation::False), + scc: SccEffect::Unchanged, + vcc: MaskEffect::LaneMask, + exec: MaskEffect::Unchanged, + wave: Wave::Wave32, + operands: OperandRule::VopcVcc, + spec: &[SpecRef { document: Document::Guide, section: "12.9", page: 150 }, SpecRef { document: Document::Guide, section: "3.9", page: 19 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_CMP_T_U32", + family: EncodingFamily::Vopc, + opcode: 199, + operation: Operation::Compare, + signedness: Signedness::Unsigned, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: Some(CompareRelation::True), + scc: SccEffect::Unchanged, + vcc: MaskEffect::LaneMask, + exec: MaskEffect::Unchanged, + wave: Wave::Wave32, + operands: OperandRule::VopcVcc, + spec: &[SpecRef { document: Document::Guide, section: "12.9", page: 150 }, SpecRef { document: Document::Guide, section: "3.9", page: 19 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, ]; diff --git a/crates/isa/tests/semantics.rs b/crates/isa/tests/semantics.rs index b46b692..895b7ff 100644 --- a/crates/isa/tests/semantics.rs +++ b/crates/isa/tests/semantics.rs @@ -143,6 +143,8 @@ fn vector_compare_dispatch_selects_exactly_the_registry_vopc_forms() { CompareRelation::Greater => ordering.is_gt(), CompareRelation::NotEqual => ordering.is_ne(), CompareRelation::GreaterOrEqual => ordering.is_ge(), + CompareRelation::False => false, + CompareRelation::True => true, }; assert_eq!( op.test(src0, src1), @@ -153,7 +155,7 @@ fn vector_compare_dispatch_selects_exactly_the_registry_vopc_forms() { } } } - // v_cmpx, F/T and the 16-, 64-bit and float compares must not be dispatched. + // v_cmpx and the 16-, 64-bit and float compares must not be dispatched. dispatch_selects_exactly(EncodingFamily::Vopc, |word| { VectorCompareOp::from_word(word).map(|op| op.semantics().name) }); diff --git a/crates/shader/src/lib.rs b/crates/shader/src/lib.rs index 50a8130..3eae65c 100644 --- a/crates/shader/src/lib.rs +++ b/crates/shader/src/lib.rs @@ -202,6 +202,9 @@ fn compare_expression(op: VectorCompareOp, left: &str, right: &str) -> String { CompareRelation::Greater => ">", CompareRelation::NotEqual => "!=", CompareRelation::GreaterOrEqual => ">=", + // F and T read no operand bits. + CompareRelation::False => return "false".to_owned(), + CompareRelation::True => return "true".to_owned(), }; if op.signed() { format!("as_type({left}) {symbol} as_type({right})") @@ -523,7 +526,15 @@ fn emit_lane_mask( exec: u32, ) { let mut cone = vec![false; index]; - let mut pending = vec![src0, src1]; + // F and T do not depend on the operands, so their lanes compute none. + let mut pending = if matches!( + op.relation(), + xenora_decoder::CompareRelation::False | xenora_decoder::CompareRelation::True + ) { + Vec::new() + } else { + vec![src0, src1] + }; while let Some(value) = pending.pop() { if uniform[value.0] || cone[value.0] { continue; diff --git a/crates/shader/tests/compiler.rs b/crates/shader/tests/compiler.rs index e72291a..6d94175 100644 --- a/crates/shader/tests/compiler.rs +++ b/crates/shader/tests/compiler.rs @@ -350,6 +350,20 @@ fn vector_integer_forms_lower_to_per_lane_templates() { ); } +#[test] +fn vector_f_and_t_compares_lower_to_operand_free_wave_masks() { + let code = include_bytes!("../../../fixtures/rdna2/vector-compare-ft.bin"); + let result = compile(Architecture::Gfx1030, code).unwrap(); + assert_eq!( + result.ir, + include_str!("../../../fixtures/golden/vector-compare-ft.ir") + ); + assert_eq!( + result.msl, + include_str!("../../../fixtures/golden/vector-compare-ft.metal") + ); +} + #[test] fn vector_compares_lower_to_per_thread_wave_masks_and_selects() { let code = include_bytes!("../../../fixtures/rdna2/vector-compare.bin"); diff --git a/docs/assets/xenora-progress.svg b/docs/assets/xenora-progress.svg index d5ef3f6..7e30221 100644 --- a/docs/assets/xenora-progress.svg +++ b/docs/assets/xenora-progress.svg @@ -1,17 +1,17 @@ Xenora · recorded progress -Decoded gfx1030 forms: 100 of 100. Accepted Metal forms · Apple M5: 18 of 100. Accepted guest milestones · X1–X4: 4 of 4 +Decoded gfx1030 forms: 104 of 104. Accepted Metal forms · Apple M5: 18 of 104. Accepted guest milestones · X1–X4: 4 of 4 RECORDED FIXTURE PROGRESS Decoded gfx1030 forms -100 / 100 +104 / 104 Accepted Metal forms · Apple M5 -18 / 100 +18 / 104 - + Accepted guest milestones · X1–X4 4 / 4 diff --git a/docs/shaders/instruction-coverage.md b/docs/shaders/instruction-coverage.md index 448d6bc..d3f72f4 100644 --- a/docs/shaders/instruction-coverage.md +++ b/docs/shaders/instruction-coverage.md @@ -89,6 +89,10 @@ The wider LLVM operand matrix exercises decoding only. ABI means application bin | `v_cmp_gt_u32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (unsigned S0 > S1), fully written | `7D8802C0` | yes | yes | three-way passed | per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | | `v_cmp_ne_u32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (unsigned S0 != S1), fully written | `7D8A026A` | yes | yes | three-way passed | per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | | `v_cmp_ge_u32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (unsigned S0 >= S1), fully written | `7D8C0D01` | yes | yes | three-way passed | per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `v_cmp_f_i32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0 (signed); VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & false, fully written | `7D000501` | yes | yes | three-way passed | per-thread Wave32 mask over the dispatch's own 32 lanes, reading no operand bits; runtime s_cbranch_vccz as a join select | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `v_cmp_t_i32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0 (signed); VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & true, fully written | `7D0E0501` | yes | yes | three-way passed | per-thread Wave32 mask over the dispatch's own 32 lanes, reading no operand bits; runtime s_cbranch_vccz as a join select | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `v_cmp_f_u32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0 (unsigned); VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & false, fully written | `7D800501` | yes | yes | three-way passed | per-thread Wave32 mask over the dispatch's own 32 lanes, reading no operand bits; runtime s_cbranch_vccz as a join select | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | +| `v_cmp_t_u32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0 (unsigned); VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & true, fully written | `7D8E0501` | yes | yes | three-way passed | per-thread Wave32 mask over the dispatch's own 32 lanes, reading no operand bits; runtime s_cbranch_vccz as a join select | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending | | `s_cbranch_scc0` | Nonnegative signed dword displacement | `BF840002` | yes | yes | three-way passed | resolved conditional branch | implemented | fixture verified | fixture verified | | `s_branch` | Nonnegative signed dword displacement | `BF820001` | yes | yes | three-way passed | resolved branch | implemented | fixture verified | fixture verified | | `v_and_b32_e32` | Two VGPR sources and one VGPR destination | `36020702` | yes | yes | three-way passed | MSL bitwise AND | implemented | fixture verified | fixture verified | diff --git a/docs/shaders/reference-interpreter.md b/docs/shaders/reference-interpreter.md index 60a3059..9b55af5 100644 --- a/docs/shaders/reference-interpreter.md +++ b/docs/shaders/reference-interpreter.md @@ -12,7 +12,7 @@ | SOP1 `S_NOT_B32`, `S_BREV_B32`, `S_BCNT{0,1}_I32_B32`, `S_FF{0,1}_I32_B32`, `S_FLBIT_I32_B32`, `S_FLBIT_I32`, `S_SEXT_I32_I{8,16}`, `S_ABS_I32` | The guide's section 12.3 result; a search that finds nothing gives -1, and `S_ABS_I32` of 0x80000000 is 0x80000000. Only NOT, BCNT0, BCNT1 and ABS write SCC (= D != 0). Descriptor SGPRs are reserved. | | SOP1 `S_MOV_B32`, SOPC `S_CMP_{EQ,LG,GT,GE,LT,LE}_{I32,U32}` | Copy 32 bits into a scalar register, or compare SSRC0 with SSRC1 (signed for `_I32` ordering, unsigned for `_U32`; EQ and LG on the raw bits) and set only SCC. Descriptor SGPRs are reserved. | | SOP2 `S_ADD_U32`, `S_SUB_U32`, `S_ADD_I32`, `S_SUB_I32`, `S_ADDC_U32`, `S_SUBB_U32`, `S_AND_B32`, `S_OR_B32`, `S_XOR_B32`, `S_ANDN2_B32`, `S_ORN2_B32`, `S_NAND_B32`, `S_NOR_B32`, `S_XNOR_B32`, `S_LSHL_B32`, `S_LSHR_B32`, `S_ASHR_I32` | Exact integer result reduced modulo 2^32; shifts use S1[4:0]; SCC is the carry-out, the borrow, signed overflow (the exact signed result does not fit in i32), or a nonzero logical or shift result, and ADDC/SUBB consume SCC ([SOP2 scalar ALU](scalar-alu.md)). Descriptor SGPRs are reserved. | -| VOPC `V_CMP_{LT,EQ,LE,GT,NE,GE}_{I32,U32}` | Compare widened 64-bit values per active lane. VCC_LO gets EXEC & the test results and is fully written, so empty EXEC gives 0. A later `S_CBRANCH_VCCZ` on such a mask checks the skipped code statically ([VOPC integer compares](vector-compare.md)). | +| VOPC `V_CMP_{F,LT,EQ,LE,GT,NE,GE,T}_{I32,U32}` | Compare widened 64-bit values per active lane (F is false and T true for every lane). VCC_LO gets EXEC & the test results and is fully written, so empty EXEC gives 0. A later `S_CBRANCH_VCCZ` on such a mask checks the skipped code statically ([VOPC integer compares](vector-compare.md)). | | SOPP `S_BRANCH`, `S_CBRANCH_SCC0` | Use a signed dword displacement from the next instruction (CLAIM-RDNA2-SOPP-BRANCH-DISPLACEMENT). Require a nonnegative word displacement to a decoded instruction boundary, including for untaken edges. | | VOP2 `V_AND_B32`, `V_XOR_B32` | Apply the bitwise operator to two VGPRs. | | VOP2 `V_MUL_{I32_I24,HI_I32_I24,U32_U24,HI_U32_U24}`, `V_MIN_{I32,U32}`, `V_MAX_{I32,U32}`, `V_XNOR_B32`, `V_ADD_NC_U32`, `V_SUB_NC_U32`, `V_SUBREV_NC_U32` | The guide's section 12.7 result per active lane, computed exactly: the 24-bit multiplies use S0[23:0] and S1[23:0] (sign-extended for I24) and keep bits 31:0 or 63:32; SUBREV gives S1 - S0. SRC0 is a VGPR, s0-s105, `vcc_lo`, an inline integer or a literal. Inactive lanes keep VDST; no SCC or VCC write. | diff --git a/docs/shaders/semantic-coverage.md b/docs/shaders/semantic-coverage.md index 3b51194..04f437a 100644 --- a/docs/shaders/semantic-coverage.md +++ b/docs/shaders/semantic-coverage.md @@ -35,8 +35,8 @@ acceptance remain outside the verified count. All results concern synthetic fixt | 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 | 12 | 12 | 12 | 12 | 0 | 0 | 7 | -| **Total** | 1465 | 100 | 80 | 104 | 100 | 100 | 18 | 18 | 44 | +| VOPC | 190 | 16 | 16 | 16 | 16 | 16 | 0 | 0 | 7 | +| **Total** | 1465 | 104 | 84 | 108 | 104 | 104 | 18 | 18 | 44 | ## Unsupported operand variants diff --git a/docs/shaders/vector-compare.md b/docs/shaders/vector-compare.md index 9d8a8ca..a9b1dec 100644 --- a/docs/shaders/vector-compare.md +++ b/docs/shaders/vector-compare.md @@ -53,6 +53,8 @@ The 32-bit VOPC encoding (bits 31:25 = 0b0111110), no SDWA or DPP: | v_cmp_gt_i32 / v_cmp_gt_u32 | S0 > S1 | | v_cmp_ne_i32 / v_cmp_ne_u32 | S0 != S1 | | v_cmp_ge_i32 / v_cmp_ge_u32 | S0 >= S1 | +| v_cmp_f_i32 / v_cmp_f_u32 | false (Table 59 offset 0) | +| v_cmp_t_i32 / v_cmp_t_u32 | true (offset 7) | `_i32` compares the 32-bit two's-complement values, `_u32` the unsigned values. The forms are declared in the semantic registry @@ -98,7 +100,7 @@ this wave (all 32 except in a final partial wave, see 7). As an unsigned - V_CMPX_* (writes EXEC: divergent execution; needs its own contract). - The VOP3 encoding of any compare (arbitrary SGPR destination, modifiers). -- SDWA and DPP forms; F/T, 16-bit, 64-bit and float compares; v_cmp_class. +- SDWA and DPP forms; 16-bit, 64-bit and float compares; v_cmp_class. - SRC0 inline float constants (240-248), SGPRs other than s0-s106, TTMPs, M0, EXEC_LO/HI, VCC_HI, SCC/VCCZ/EXECZ selectors, LDS direct. - A normal-SGPR SRC0 without a known value, when EXEC_LO != 0. @@ -197,7 +199,7 @@ instructions are pure 32-bit ALU and are evaluated unconditionally. ## 9. Verification `fixtures/rdna2/vector-compare.s` is an original program, assembled by LLVM. -It uses all twelve forms with VGPR, SGPR, inline, literal and `vcc_lo` +It uses the twelve relational forms with VGPR, SGPR, inline, literal and `vcc_lo` sources, a compare and a mask move under partial EXEC, a compare under empty EXEC that must clear a stale VCC, SCC kept across compares, and a runtime `s_cbranch_vccz`. Its expected output is written in @@ -205,6 +207,12 @@ EXEC that must clear a stale VCC, SCC kept across compares, and a runtime relation for each row. The test input has a wave whose branch is taken, one whose branch is not, and a final partial wave of 9 lanes. +`fixtures/rdna2/vector-compare-ft.s` does the same for the four F and T +forms: an F that clears a stale VCC, T and F under partial EXEC, a T reading +`vcc_lo`, and runtime `s_cbranch_vccz` on a T result (never taken) and an F +result (always taken). The independent oracle for F and T is +`tests/validation/tests/vopc_f_t.rs`. + The same file runs each form against 10 boundary values (0, 1, 0x7ffffffe, 0x7fffffff, 0x80000000, 0x80000001, 0xfffffff0, 0xfffffffe, 0xffffffff, 0x0f0f0f0f), in both operand orders. That is 240 programs, checked against diff --git a/docs/status.toml b/docs/status.toml index f96bee7..01fb189 100644 --- a/docs/status.toml +++ b/docs/status.toml @@ -950,6 +950,54 @@ gpu = "local Apple M5 readback passed; acceptance pending" recognized = true decoded = true llvm = "three-way passed" +[[instruction]] +form = "v_cmp_f_i32_e32" +encoding = "VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0 (signed); VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & false, fully written" +representation = "`7D000501`" +lowering = "per-thread Wave32 mask over the dispatch's own 32 lanes, reading no operand bits; runtime s_cbranch_vccz as a join select" +reference = "implemented" +cpu = "local known-answer test passed" +gpu = "local Apple M5 readback passed; acceptance pending" +recognized = true +decoded = true +llvm = "three-way passed" + +[[instruction]] +form = "v_cmp_t_i32_e32" +encoding = "VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0 (signed); VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & true, fully written" +representation = "`7D0E0501`" +lowering = "per-thread Wave32 mask over the dispatch's own 32 lanes, reading no operand bits; runtime s_cbranch_vccz as a join select" +reference = "implemented" +cpu = "local known-answer test passed" +gpu = "local Apple M5 readback passed; acceptance pending" +recognized = true +decoded = true +llvm = "three-way passed" + +[[instruction]] +form = "v_cmp_f_u32_e32" +encoding = "VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0 (unsigned); VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & false, fully written" +representation = "`7D800501`" +lowering = "per-thread Wave32 mask over the dispatch's own 32 lanes, reading no operand bits; runtime s_cbranch_vccz as a join select" +reference = "implemented" +cpu = "local known-answer test passed" +gpu = "local Apple M5 readback passed; acceptance pending" +recognized = true +decoded = true +llvm = "three-way passed" + +[[instruction]] +form = "v_cmp_t_u32_e32" +encoding = "VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0 (unsigned); VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & true, fully written" +representation = "`7D8E0501`" +lowering = "per-thread Wave32 mask over the dispatch's own 32 lanes, reading no operand bits; runtime s_cbranch_vccz as a join select" +reference = "implemented" +cpu = "local known-answer test passed" +gpu = "local Apple M5 readback passed; acceptance pending" +recognized = true +decoded = true +llvm = "three-way passed" + [[instruction]] form = "s_cbranch_scc0" encoding = "Nonnegative signed dword displacement" diff --git a/fixtures/golden/vector-compare-ft.ir b/fixtures/golden/vector-compare-ft.ir new file mode 100644 index 0000000..f0e68ee --- /dev/null +++ b/fixtures/golden/vector-compare-ft.ir @@ -0,0 +1,28 @@ +0000: t0 = load.u32 input[index] +0014: t1 = const.u32 0x00000000 +0018: t2 = const.u32 0x00000001 +0020: t3 = wave.mask v_cmp_f_i32_e32 t0, t0 exec=0xffffffff +0028: t4 = xor.b32 t1, t3 +002c: t5 = const.u32 0x12345678 +002c: t6 = wave.mask v_cmp_t_i32_e32 t5, t0 exec=0xffffffff +0034: t7 = lshl.b32 t4, t2 +0038: t8 = xor.b32 t7, t6 +0044: t9 = const.u32 0xfffffff9 +0044: t10 = wave.mask v_cmp_t_u32_e32 t9, t0 exec=0x0f0f0f0f +0050: t11 = lshl.b32 t8, t2 +0054: t12 = xor.b32 t11, t10 +0058: t13 = wave.mask v_cmp_t_i32_e32 t0, t0 exec=0xffffffff +0064: t14 = const.u32 0xdeadbeef +0064: t15 = wave.mask v_cmp_f_u32_e32 t14, t0 exec=0x3c3c3c3c +0074: t16 = lshl.b32 t12, t2 +0078: t17 = xor.b32 t16, t15 +007c: t18 = wave.mask v_cmp_t_u32_e32 t15, t0 exec=0xffffffff +0080: branch.vccz t18 -> 0x0088 +0084: t20 = xor.b32 t17, t0 +0088: t21 = join.vccz t18, t20, t17 +0088: t22 = const.u32 0x00000040 +0088: t23 = wave.mask v_cmp_f_i32_e32 t22, t0 exec=0xffffffff +008c: branch.vccz t23 -> 0x0094 +0090: t25 = const.u32 0x00000000 +0094: t26 = join.vccz t23, t25, t21 +0094: store.u32 output[index], t26 diff --git a/fixtures/golden/vector-compare-ft.metal b/fixtures/golden/vector-compare-ft.metal new file mode 100644 index 0000000..b4c83e0 --- /dev/null +++ b/fixtures/golden/vector-compare-ft.metal @@ -0,0 +1,76 @@ +#include +using namespace metal; +kernel void xenora_compute( + device const uint* input [[buffer(0)]], + device uint* output [[buffer(1)]], + uint index [[thread_position_in_grid]], + uint grid [[threads_per_grid]]) { + uint t0 = input[index]; + uint t1 = 0x00000000u; + uint t2 = 0x00000001u; + uint t3 = 0u; + for (uint lane = 0u; lane < 32u; ++lane) { + uint lane_index = (index & ~31u) + lane; + if (lane_index >= grid) { break; } + uint pass = (false) ? 1u : 0u; + t3 |= ((0xffffffffu >> lane) & pass) << lane; + } + uint t4 = t1 ^ t3; + uint t5 = 0x12345678u; + uint t6 = 0u; + for (uint lane = 0u; lane < 32u; ++lane) { + uint lane_index = (index & ~31u) + lane; + if (lane_index >= grid) { break; } + uint pass = (true) ? 1u : 0u; + t6 |= ((0xffffffffu >> lane) & pass) << lane; + } + uint t7 = t4 << (t2 & 31u); + uint t8 = t7 ^ t6; + uint t9 = 0xfffffff9u; + uint t10 = 0u; + for (uint lane = 0u; lane < 32u; ++lane) { + uint lane_index = (index & ~31u) + lane; + if (lane_index >= grid) { break; } + uint pass = (true) ? 1u : 0u; + t10 |= ((0x0f0f0f0fu >> lane) & pass) << lane; + } + uint t11 = t8 << (t2 & 31u); + uint t12 = t11 ^ t10; + uint t13 = 0u; + for (uint lane = 0u; lane < 32u; ++lane) { + uint lane_index = (index & ~31u) + lane; + if (lane_index >= grid) { break; } + uint pass = (true) ? 1u : 0u; + t13 |= ((0xffffffffu >> lane) & pass) << lane; + } + uint t14 = 0xdeadbeefu; + uint t15 = 0u; + for (uint lane = 0u; lane < 32u; ++lane) { + uint lane_index = (index & ~31u) + lane; + if (lane_index >= grid) { break; } + uint pass = (false) ? 1u : 0u; + t15 |= ((0x3c3c3c3cu >> lane) & pass) << lane; + } + uint t16 = t12 << (t2 & 31u); + uint t17 = t16 ^ t15; + uint t18 = 0u; + for (uint lane = 0u; lane < 32u; ++lane) { + uint lane_index = (index & ~31u) + lane; + if (lane_index >= grid) { break; } + uint pass = (true) ? 1u : 0u; + t18 |= ((0xffffffffu >> lane) & pass) << lane; + } + uint t20 = t17 ^ t0; + uint t21 = t18 != 0u ? t20 : t17; + uint t22 = 0x00000040u; + uint t23 = 0u; + for (uint lane = 0u; lane < 32u; ++lane) { + uint lane_index = (index & ~31u) + lane; + if (lane_index >= grid) { break; } + uint pass = (false) ? 1u : 0u; + t23 |= ((0xffffffffu >> lane) & pass) << lane; + } + uint t25 = 0x00000000u; + uint t26 = t23 != 0u ? t25 : t21; + output[index] = t26; +} diff --git a/fixtures/rdna2/vector-compare-ft.bin b/fixtures/rdna2/vector-compare-ft.bin new file mode 100644 index 0000000000000000000000000000000000000000..a12df6665be972abe0f8909240387c255ba5c88b GIT binary patch literal 164 zcmZQjFnGYg$k0$=-?RTebH~1lFcYB$CYHKJCa$`J%&+z_GBea>F>%x}ak5x(F!6!e ztgI|1ApU>mfBX1>;5buX?Li$jny@lD7eZ|4a?F@As{}hpr|IsE?7MZ9fw; ei`4-p1~40BH-kdK0|q9>1_p+|yBQc7_X7Z|oiP9a literal 0 HcmV?d00001 diff --git a/fixtures/rdna2/vector-compare-ft.s b/fixtures/rdna2/vector-compare-ft.s new file mode 100644 index 0000000..7001d86 --- /dev/null +++ b/fixtures/rdna2/vector-compare-ft.s @@ -0,0 +1,45 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Original Wave32 VOPC vectors for the F and T compares: both signednesses +// with VGPR, SGPR, inline, literal and vcc_lo sources; F clearing a stale +// VCC; T and F under partial EXEC; and runtime s_cbranch_vccz on a T result +// (never taken) and an F result (always taken). Each wave folds its masks +// into v2 as v2 = (v2 << 1) ^ mask. Expected results come from exact +// definitions in tests/validation/known_answers.rs, not from this file. +.text +buffer_load_dword v1, v0, s[0:3], 0 idxen +s_waitcnt vmcnt(0) +s_mov_b32 s8, 0x12345678 +v_mov_b32_e32 v2, 0 // accumulator +v_mov_b32_e32 v5, 1 // shift count +s_mov_b32 vcc_lo, -1 // stale nonzero mask +v_cmp_f_i32_e32 vcc_lo, v1, v1 // VCC_LO = 0 +v_mov_b32_e32 v4, vcc_lo +v_xor_b32_e32 v2, v2, v4 +v_cmp_t_i32_e32 vcc_lo, s8, v1 // every lane of the wave +v_mov_b32_e32 v4, vcc_lo +v_lshlrev_b32_e32 v2, v5, v2 +v_xor_b32_e32 v2, v2, v4 +s_mov_b32 exec_lo, 0x0f0f0f0f +v_cmp_t_u32_e32 vcc_lo, -7, v1 // only the EXEC lanes +s_mov_b32 exec_lo, -1 +v_mov_b32_e32 v4, vcc_lo +v_lshlrev_b32_e32 v2, v5, v2 +v_xor_b32_e32 v2, v2, v4 +v_cmp_t_i32_e32 vcc_lo, v1, v1 // nonzero again before the F +s_mov_b32 exec_lo, 0x3c3c3c3c +v_cmp_f_u32_e32 vcc_lo, 0xdeadbeef, v1 // 0 even in active lanes +s_mov_b32 exec_lo, -1 +v_mov_b32_e32 v4, vcc_lo +v_lshlrev_b32_e32 v2, v5, v2 +v_xor_b32_e32 v2, v2, v4 +v_cmp_t_u32_e32 vcc_lo, vcc_lo, v1 // reads the zero mask; T anyway +s_cbranch_vccz .Lskip // runtime branch, never taken +v_xor_b32_e32 v2, v2, v1 +.Lskip: +v_cmp_f_i32_e32 vcc_lo, 64, v1 +s_cbranch_vccz .Ldone // runtime branch, always taken +v_mov_b32_e32 v2, 0 +.Ldone: +buffer_store_dword v2, v0, s[4:7], 0 idxen +s_waitcnt_vscnt null, 0 +s_endpgm diff --git a/scripts/assemble-fixture.sh b/scripts/assemble-fixture.sh index eb0a0f8..6109c31 100755 --- a/scripts/assemble-fixture.sh +++ b/scripts/assemble-fixture.sh @@ -12,7 +12,7 @@ case "${1:-}" in esac for name in add bitwise-branch float-exact or shifts ashr \ - x9-constant-vs x9-constant-ps x9-varying-vs x9-varying-ps x9-transform-vs scalar-alu vector-compare scalar-logic scalar-compare scalar-unary scalar-arith vector-integer; do + x9-constant-vs x9-constant-ps x9-varying-vs x9-varying-ps x9-transform-vs scalar-alu vector-compare scalar-logic scalar-compare scalar-unary scalar-arith vector-integer vector-compare-ft; do "$llvm_bin/llvm-mc" -triple=amdgcn-amd-amdhsa -mcpu=gfx1030 -mattr=+wavefrontsize32 \ -filetype=obj "fixtures/rdna2/$name.s" -o "$scratch/$name.o" "$llvm_bin/llvm-objcopy" -O binary --only-section=.text "$scratch/$name.o" "$scratch/$name.bin" diff --git a/tests/semantics_generator/test_generate_semantics.py b/tests/semantics_generator/test_generate_semantics.py index 71b39f5..90eb6fd 100644 --- a/tests/semantics_generator/test_generate_semantics.py +++ b/tests/semantics_generator/test_generate_semantics.py @@ -831,6 +831,22 @@ class Validate(unittest.TestCase): form(reg, "V_CMP_LT_I32")["signedness"] = "unsigned" self.rejects(reg, "V_CMP_LT_I32: signedness unsigned contradicts XML format FMT_NUM_I32") + def test_rejects_f_and_t_outside_vopc(self): + for relation in ("f", "t"): + with self.subTest(relation=relation): + reg = compares() + form(reg, "S_CMP_LT_I32")["relation"] = relation + self.rejects(reg, f"S_CMP_LT_I32: relation {relation} exists only for VOPC compares") + + def test_renders_f_and_t_primitives(self): + reg = vector_compares() + form(reg, "V_CMP_LT_I32")["relation"] = "t" + form(reg, "V_CMP_NE_U32")["relation"] = "f" + self.assertEqual(self.errors(reg), []) + text = gen.render(reg, snapshot()) + self.assertIn("Self::CmpLtI32 => primitive::true_b32(src0, src1),", text) + self.assertIn("Self::CmpNeU32 => CompareRelation::False,", text) + def test_renders_vector_compare_dispatch(self): text = gen.render(vector_compares(), snapshot()) self.assertIn("pub enum VectorCompareOp {", text) diff --git a/tests/validation/known_answers.rs b/tests/validation/known_answers.rs index 6aa3cd3..b4f1f62 100644 --- a/tests/validation/known_answers.rs +++ b/tests/validation/known_answers.rs @@ -1308,6 +1308,21 @@ mod review { // ---- VOPC integer compares (docs/shaders/vector-compare.md) ---- const COMPARE_FIXTURE: &[u8] = include_bytes!("../../fixtures/rdna2/vector-compare.bin"); + const COMPARE_FT_FIXTURE: &[u8] = include_bytes!("../../fixtures/rdna2/vector-compare-ft.bin"); + + /// fixtures/rdna2/vector-compare-ft.s, from its listing and guide 12.9 + /// Table 61 (F: D = 0, T: D = 1) with VCC_LO[n] = EXEC_LO[n] & test: every + /// F mask is 0 and every T mask is EXEC_LO & the lanes that exist, so the + /// T branch is never taken and the F branch always is. + fn compare_ft_expected(input: &[u32]) -> Vec { + let mut output = Vec::new(); + for wave in input.chunks(32) { + let exists = wave_mask(wave, u32::MAX, |_| true); + let folded = ((exists << 1) ^ (exists & 0x0f0f_0f0f)) << 1; + output.extend(wave.iter().map(|&x| folded ^ x)); + } + output + } const COMPARE_VALUES: [u32; 10] = [ 0, 1, @@ -1412,6 +1427,30 @@ mod review { input } + #[test] + fn compare_ft_fixture_matches_exact_definitions() { + // A full wave and a final partial wave of 7 lanes. + let mut input = compare_fixture_input()[..32].to_vec(); + input.extend([0, 1, u32::MAX, 0x8000_0000, 0x7fff_ffff, 64, 0x1234_5678]); + let expected = compare_ft_expected(&input); + verify(COMPARE_FT_FIXTURE, &input, Some(&expected)); + // The partial wave's T masks have only its 7 lanes. + assert_eq!(expected[32], ((0x7f << 1) ^ 0x0f) << 1); + let compiled = compile(Architecture::Gfx1030, COMPARE_FT_FIXTURE).unwrap(); + assert_eq!( + compiled.ir.matches("wave.mask").count(), + 7, + "{}", + compiled.ir + ); + assert_eq!( + compiled.ir.matches("join.vccz").count(), + 2, + "{}", + compiled.ir + ); + } + #[test] fn compare_fixture_matches_exact_definitions() { let input = compare_fixture_input(); @@ -1892,6 +1931,10 @@ mod review { assert_eq!(run(&join, &[1, 0, 5, 0]), [0b1010; 4]); assert_eq!(run(&join, &[0, 0, 0, 0]), [0; 4]); programs += 2; + let mut input = compare_fixture_input()[..32].to_vec(); + input.extend([0, 1, u32::MAX, 0x8000_0000, 0x7fff_ffff, 64, 0x1234_5678]); + assert_eq!(run(COMPARE_FT_FIXTURE, &input), compare_ft_expected(&input)); + programs += 1; eprintln!("{programs} VOPC programs matched on native Metal"); } } From 8909b99ece218dcf37628f2ce1e50ff924d45fc5 Mon Sep 17 00:00:00 2001 From: elforeign <324243036+elforeign@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:39:24 -0600 Subject: [PATCH 04/15] test(vopc): cover EXEC preservation, known-0 branch, pending loads (#215) Review found four ways F/T could be wrong and still pass: clearing EXEC under partial EXEC, treating the empty-EXEC result as lane-derived, ignoring an outstanding load on a source, and decoding opcode 200. Add a case or rejection for each; each was shown failing with that break. Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com> --- tests/validation/tests/vopc_f_t.rs | 65 +++++++++++++++++++++++++++--- 1 file changed, 60 insertions(+), 5 deletions(-) diff --git a/tests/validation/tests/vopc_f_t.rs b/tests/validation/tests/vopc_f_t.rs index 53b74b1..522ec48 100644 --- a/tests/validation/tests/vopc_f_t.rs +++ b/tests/validation/tests/vopc_f_t.rs @@ -135,8 +135,10 @@ const EXEC_MASKS: [u32; 7] = [ /// VCC_LO before the compare in the EXEC cases: bits inside and outside every /// mask above, so a partial VCC update would show. const STALE_VCC: u32 = 0xa5a5_c33c; +/// XORed with v1 to give every lane its own old v2 before a masked move. +const OLD: u32 = 0x0bad_f00d; -const COUNTS: [(&str, usize); 11] = [ +const COUNTS: [(&str, usize); 12] = [ ("vopc domain", 4 * 8 * 2), ("vopc aliasing", 4 * 2), ("vopc inline integer", 4 * 81), @@ -147,13 +149,14 @@ const COUNTS: [(&str, usize); 11] = [ ("vopc exec", 4 * (7 + 2)), ("vopc empty exec reads nothing", 4 * 3), ("vopc partial wave", 4 * 3), - ("vopc vccz branch", 4 * 3), + ("vopc vccz branch", 4 * 4), + ("vopc exec unchanged", 4 * 2), ]; -/// Per form: 4 uninitialized sources, a missing literal, 9 float inline +/// Per form: 4 uninitialized sources, 2 sources with a load outstanding, a missing literal, 9 float inline /// constants, 9 other special SRC0 selectors, a float constant under empty /// EXEC, SDWA, DPP16 and two DPP8 forms, the VOP3 `_e64` form, the matching /// `v_cmpx`, and a lane-derived F result branching over a scalar instruction. -const REJECTIONS: usize = 4 * (4 + 1 + 9 + 9 + 1 + 4 + 1 + 1 + 1); +const REJECTIONS: usize = 4 * (4 + 2 + 1 + 9 + 9 + 1 + 4 + 1 + 1 + 1); const LITERAL: u32 = 255; const VCC_LO: u32 = 106; @@ -429,6 +432,41 @@ fn cases() -> Vec { if mask == 0 { 0 } else { mask ^ x } })); } + // Under EXEC_LO = 0 the result is a known 0 (contract section 5), so + // the branch is resolved statically and may skip a scalar + // instruction (`s_mov_b32 s8, 0`); it is taken, v2 = 0. + let tail = [VCCZ_OVER_ONE, 0xbe88_0380]; + let (code, _) = program(&vmov(3, 5), Some(0), &[vopc(op, vgpr(1), 3)], &tail); + let label = "exec 0, then s_cbranch_vccz over s_mov".into(); + cases.push(case(entry, family, label, code, lanes(), |_, _, _| 0)); + // EXEC_LO is unchanged by the compare (contract section 3): v2 = + // vcc_lo runs under the compare's partial EXEC, so active lanes take + // VCC_LO and inactive lanes keep their own old v2 = v1 ^ OLD. + let family = "vopc exec unchanged"; + for exec in [0x5555_5555, 0x8000_0001] { + let mut code = PREFIX.to_vec(); + code.extend(vmov(3, 5)); + code.extend(vmov(5, OLD)); + code.push(29 << 25 | 2 << 17 | 1 << 9 | vgpr(5)); // v_xor_b32 v2, v5, v1 + code.extend(smov(EXEC_LO, exec)); + code.extend([vopc(op, vgpr(1), 3), READ_VCC, FULL_EXEC]); + code.extend(STORE_V2); + let label = format!("exec {exec:#x}, v2 = vcc_lo before EXEC is restored"); + cases.push(case( + entry, + family, + label, + words(&code), + lanes(), + |n, x, p| { + if exec >> (n % 32) & 1 == 1 { + vcc(form, exec, p, |k| (v1(k), 5)) + } else { + x ^ OLD + } + }, + )); + } } cases } @@ -454,6 +492,19 @@ fn rejections() -> Vec<(String, Vec, usize)> { program(&setup, None, &[vopc(op, src0, vsrc1)], &[]), ); } + // A source whose VGPR has a load outstanding (no wait after + // `buffer_load_dword v3`): refused at the compare. + for (src0, vsrc1, label) in [(vgpr(1), 3, "VSRC1"), (vgpr(3), 1, "SRC0")] { + let mut code = PREFIX.to_vec(); + code.extend(setup); + code.extend([0xe030_2000, 0x8000_0300]); + let offset = 4 * code.len(); + code.push(vopc(op, src0, vsrc1)); + code.extend([READ_VCC, 0xbf8c_3f70]); + code.extend(STORE_V2); + let label = format!("v3 load outstanding as {label}"); + reject(label, (words(&code), offset)); + } // A literal SRC0 with no literal dword: the program ends at the word. let mut code = PREFIX.to_vec(); code.extend(setup); @@ -620,7 +671,11 @@ fn other_constant_compares_stay_unsupported() { // V_CMP_F_I64 160, V_CMP_T_I64 167, V_CMPX_F_I64 176, V_CMPX_T_I64 183, // V_CMP_F_U64 224, V_CMP_T_U64 231, V_CMPX_F_U64 240, V_CMPX_T_U64 247. let setup = vmov(3, 7); - for op in [0, 15, 16, 31, 160, 167, 176, 183, 224, 231, 240, 247] { + // Also the neighbours of the two 32-bit integer groups: 127 and 191 (not + // in Table 61), 136 V_CMP_CLASS_F32 and 200 V_CMP_F_F16. + for op in [ + 0, 15, 16, 31, 127, 136, 160, 167, 176, 183, 191, 200, 224, 231, 240, 247, + ] { let (code, offset) = program(&setup, None, &[vopc(op, vgpr(1), 3)], &[]); assert_rejected_at(&format!("opcode {op}"), &code, offset, &lanes()); } From ef90105a265c4cebbd0692b4db69e74add42f850 Mon Sep 17 00:00:00 2001 From: elforeign <324243036+elforeign@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:43:08 -0600 Subject: [PATCH 05/15] isa: check VOPC relations against the Table 59 opcode layout and the VCC write direction (#215) Review fixes. A VOPC compare's opcode must equal its group base (128 signed, 192 unsigned) plus its relation's Table 59 offset, so a row such as V_CMP_T_I32 with relation f is rejected instead of lowering to false. A lane_mask form now needs exactly one fieldless XML VCC operand that is written and not read. The generator tests render the real F/T rows, and the vector-compare doc names the file each count comes from. Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com> --- crates/isa/generate_semantics.py | 19 ++++++- docs/shaders/semantic-registry.md | 4 ++ docs/shaders/vector-compare.md | 9 ++-- .../test_generate_semantics.py | 49 ++++++++++++++++--- 4 files changed, 70 insertions(+), 11 deletions(-) diff --git a/crates/isa/generate_semantics.py b/crates/isa/generate_semantics.py index 337b897..0328eb5 100755 --- a/crates/isa/generate_semantics.py +++ b/crates/isa/generate_semantics.py @@ -64,6 +64,11 @@ RELATIONS = { } # F and T exist only as VOPC compares (guide Table 59 offsets 0 and 7). VECTOR_ONLY_RELATIONS = {"f", "t"} +# Guide 12.9 Table 59 and Table 61: a 32-bit integer VOPC compare's opcode is +# its group base (128 for _I32, 192 for _U32) plus its relation's offset. This +# is the guide's opcode layout, not a reading of the mnemonic. +VOPC_INTEGER_BASES = {"signed": 128, "unsigned": 192} +VOPC_RELATION_OFFSETS = {"f": 0, "lt": 1, "eq": 2, "le": 3, "gt": 4, "lg": 5, "ge": 6, "t": 7} # (relation, signedness) -> primitive. Equality does not depend on signedness, # so both declared signednesses of EQ and LG share one primitive. COMPARE_PRIMITIVES = { @@ -384,6 +389,7 @@ def _check_xml(form, rule, snapshot, errors): operands = {} scc_in = scc_out = False implicit = set() + vcc_writes = [] 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 @@ -392,10 +398,13 @@ def _check_xml(form, rule, snapshot, errors): operands[field] = (data_format, size, is_input, is_output) else: implicit.add(kind) + if kind == "OPR_VCC": + vcc_writes.append((is_input, is_output)) # The vocabulary states SCC effects and a lane-mask VCC write; any other # implicit XML operand (such as an EXEC write) is undeclared. if form["vcc"] == "lane_mask": - if "OPR_VCC" not in implicit: + # Exactly one fieldless VCC operand, written and not read. + if vcc_writes != [(False, True)]: errors.append(f"{label}: vcc lane_mask but the XML has no implicit VCC output") implicit.discard("OPR_VCC") if implicit: @@ -570,6 +579,14 @@ def validate(registry, snapshot): errors.append(f"{label}: no primitive implements {relation}/{form['signedness']}") elif relation in VECTOR_ONLY_RELATIONS and _rule_kind(form) != "vector_compare": errors.append(f"{label}: relation {relation} exists only for VOPC compares") + elif _rule_kind(form) == "vector_compare": + base = VOPC_INTEGER_BASES.get(form["signedness"]) + expected = None if base is None else base + VOPC_RELATION_OFFSETS[relation] + if form["opcode"] != expected: + errors.append( + f"{label}: relation {relation}/{form['signedness']} has VOPC opcode " + f"{expected} (guide Table 59), not {form['opcode']}" + ) # SOPC compares write SCC; VOPC compares write VCC and leave SCC. scc = "unchanged" if _rule_kind(form) == "vector_compare" else "relation" if form["scc"] != scc: diff --git a/docs/shaders/semantic-registry.md b/docs/shaders/semantic-registry.md index f31f5a5..dd706b1 100644 --- a/docs/shaders/semantic-registry.md +++ b/docs/shaders/semantic-registry.md @@ -127,6 +127,10 @@ 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; +- VOPC compares whose opcode is not the group base (128 for `signed`, 192 + for `unsigned`) plus the relation's offset in guide Table 59 (F 0, LT 1, + EQ 2, LE 3, GT 4, LG/NE 5, GE 6, T 7), and a `lane_mask` form whose XML + does not have exactly one implicit VCC operand that is written and not read; - duplicates: the same `name`, the same `(family, opcode)`, or the same `variant` twice in one generated enum; - XML disagreements: a family with no XML encoding, a form with no default XML diff --git a/docs/shaders/vector-compare.md b/docs/shaders/vector-compare.md index a9b1dec..56dd577 100644 --- a/docs/shaders/vector-compare.md +++ b/docs/shaders/vector-compare.md @@ -213,7 +213,7 @@ forms: an F that clears a stale VCC, T and F under partial EXEC, a T reading result (always taken). The independent oracle for F and T is `tests/validation/tests/vopc_f_t.rs`. -The same file runs each form against 10 boundary values (0, 1, 0x7ffffffe, +`tests/validation/known_answers.rs` runs each relational form against 10 boundary values (0, 1, 0x7ffffffe, 0x7fffffff, 0x80000000, 0x80000001, 0xfffffff0, 0xfffffffe, 0xffffffff, 0x0f0f0f0f), in both operand orders. That is 240 programs, checked against exact i128 differences. It also covers partial and empty EXEC with seeded @@ -221,9 +221,10 @@ destinations, both runtime branch edges in one dispatch, and 32 rejections pinned to their byte offset. The translator, the reference (lockstep waves, compares on widened i64 values) and the second interpreter (sign-bit flip, then an unsigned compare) must all agree. The 9 ordered compare slots in the -fixture each change the result when their signedness is flipped. The same -programs, plus 2 mask-chain programs (252 in all), match on native Metal with API and shader validation -(`vector_compare_native_metal_known_answers`, run by `scripts/test-gpu.sh`). +relational fixture each change the result when their signedness is flipped. The same +programs, plus 2 mask-chain programs (252 in all), and the F/T fixture (253) match on native Metal with API and shader validation +(`vector_compare_native_metal_known_answers`, run by `scripts/test-gpu.sh`). The F/T oracle's own native Metal cases +run in `vopc_f_t_match_the_guide_on_native_metal`. A deliberately broken copy of each implementation fails these tests: the reference with unsigned-only compares or with the EXEC test removed; the diff --git a/tests/semantics_generator/test_generate_semantics.py b/tests/semantics_generator/test_generate_semantics.py index 90eb6fd..e7c1b5c 100644 --- a/tests/semantics_generator/test_generate_semantics.py +++ b/tests/semantics_generator/test_generate_semantics.py @@ -151,9 +151,12 @@ def snapshot(): ["SRC0", [[0, 9]]], ["VSRC1", [[9, 8]]], ["OP", [[17, 8]]], ["ENCODING", [[25, 7]]], ], "identifier_mask": 0xFFFE0000, - "identifiers": [0x7C000000 | (op << 17) for op in (129, 197)], + "identifiers": [0x7C000000 | (op << 17) for op in (129, 135, 192, 197)], } - for name, opcode, data_format in (("V_CMP_LT_I32", 129, I32), ("V_CMP_NE_U32", 197, U32)): + for name, opcode, data_format in ( + ("V_CMP_LT_I32", 129, I32), ("V_CMP_T_I32", 135, I32), ("V_CMP_F_U32", 192, U32), + ("V_CMP_NE_U32", 197, U32), + ): variants[(name, "ENC_VOPC")] = { "instruction": name, "encoding": "ENC_VOPC", "opcode": opcode, # Values copied from the AMD XML snapshot: an implicit 64-bit VCC output. @@ -255,6 +258,8 @@ def vector_compares(): reg["form"] += [ # The same variant name as a SOPC form: variants are per enum. compare("V_CMP_LT_I32", 129, "CmpLtI32", "lt", "signed"), + compare("V_CMP_T_I32", 135, "CmpTI32", "t", "signed"), + compare("V_CMP_F_U32", 192, "CmpFU32", "f", "unsigned"), compare("V_CMP_NE_U32", 197, "CmpNeU32", "lg", "unsigned"), ] return reg @@ -840,12 +845,44 @@ class Validate(unittest.TestCase): def test_renders_f_and_t_primitives(self): reg = vector_compares() - form(reg, "V_CMP_LT_I32")["relation"] = "t" - form(reg, "V_CMP_NE_U32")["relation"] = "f" self.assertEqual(self.errors(reg), []) text = gen.render(reg, snapshot()) - self.assertIn("Self::CmpLtI32 => primitive::true_b32(src0, src1),", text) - self.assertIn("Self::CmpNeU32 => CompareRelation::False,", text) + self.assertIn("Self::CmpTI32 => primitive::true_b32(src0, src1),", text) + self.assertIn("Self::CmpFU32 => CompareRelation::False,", text) + + def test_rejects_a_vopc_relation_that_contradicts_the_opcode(self): + for name, relation, expected in ( + ("V_CMP_T_I32", "f", 128), ("V_CMP_LT_I32", "gt", 132), ("V_CMP_F_U32", "t", 199), + ): + with self.subTest(name=name): + reg = vector_compares() + form(reg, name)["relation"] = relation + signedness = form(reg, name)["signedness"] + self.rejects( + reg, + f"{name}: relation {relation}/{signedness} has VOPC opcode {expected} " + f"(guide Table 59), not {form(reg, name)['opcode']}", + ) + + def test_rejects_an_implicit_vcc_read_as_a_lane_mask_write(self): + for direction in ([True, False], [True, True]): + with self.subTest(direction=direction): + snap = snapshot() + operands = snap["variants"][("V_CMP_T_I32", "ENC_VOPC")]["operands"] + operands[0][4:6] = direction + self.rejects( + vector_compares(), + "V_CMP_T_I32: vcc lane_mask but the XML has no implicit VCC output", + snap, + ) + + def test_rejects_a_second_implicit_vcc_operand(self): + snap = snapshot() + operands = snap["variants"][("V_CMP_T_I32", "ENC_VOPC")]["operands"] + operands.append(["", "FMT_NUM_M64", "OPR_VCC", 64, True, False, False, False]) + self.rejects( + vector_compares(), "V_CMP_T_I32: vcc lane_mask but the XML has no implicit VCC output", snap + ) def test_renders_vector_compare_dispatch(self): text = gen.render(vector_compares(), snapshot()) From 2384bed8b47e9cf8c5ab7018f238838eec06c807 Mon Sep 17 00:00:00 2001 From: elforeign <324243036+elforeign@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:49:07 -0600 Subject: [PATCH 06/15] isa: split the semantic registry into one file per encoding family (#215) crates/isa/semantics/rdna2.toml keeps the schema, architecture, snapshot hash, cited documents and field meanings, and lists the family files under `include`: rdna2/{sop2,sopc,sop1,vop2,vopc}.toml, each holding only the operand rules and forms of the family it is named after. The generator merges them in include order, and rejects a form or rule of another family, a rule declared twice, root keys in a family file and a missing or repeated include. The merged registry equals the former single file, and semantics_gen.rs is byte-identical (generate_semantics.py --check passes unchanged). The coverage report and the RDNA2 planner read the merged registry; their output is unchanged. Parallel work on different families no longer edits the same file. Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com> --- crates/isa/generate_semantics.py | 58 +- crates/isa/semantics/rdna2.toml | 1740 +---------------- crates/isa/semantics/rdna2/sop1.toml | 238 +++ crates/isa/semantics/rdna2/sop2.toml | 647 ++++++ crates/isa/semantics/rdna2/sopc.toml | 269 +++ crates/isa/semantics/rdna2/vop2.toml | 225 +++ crates/isa/semantics/rdna2/vopc.toml | 360 ++++ docs/shaders/semantic-registry.md | 19 +- docs/shaders/vector-compare.md | 2 +- scripts/audit/semantic_coverage.py | 19 +- scripts/qa/rdna2_plan.py | 4 +- .../test_generate_semantics.py | 75 + 12 files changed, 1918 insertions(+), 1738 deletions(-) create mode 100644 crates/isa/semantics/rdna2/sop1.toml create mode 100644 crates/isa/semantics/rdna2/sop2.toml create mode 100644 crates/isa/semantics/rdna2/sopc.toml create mode 100644 crates/isa/semantics/rdna2/vop2.toml create mode 100644 crates/isa/semantics/rdna2/vopc.toml diff --git a/crates/isa/generate_semantics.py b/crates/isa/generate_semantics.py index 0328eb5..7997782 100755 --- a/crates/isa/generate_semantics.py +++ b/crates/isa/generate_semantics.py @@ -1,7 +1,8 @@ #!/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 + validate check crates/isa/semantics/rdna2.toml (and the family files it + includes) 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 @@ -315,10 +316,55 @@ NAME = re.compile(r"^[A-Z][A-Z0-9_]*$") SECTION = re.compile(r"^[0-9]+(\.[0-9]+)*$") +class RegistryError(ValueError): + """A registry file set that cannot be merged into one registry.""" + + +# Keys a family file may hold; everything else lives in the root file. +FAMILY_FILE_KEYS = {"operand_rules", "form"} + + def load_registry(path=REGISTRY): - """Parse the TOML registry into a dict.""" + """Parse the root registry file and merge its family files into one dict. + + The root lists its family files under `include`, in order. Each family file + holds only operand rules and forms of the one encoding family it is named + after (`rdna2/vop2.toml` holds VOP2), so parallel work on different + families never edits the same file. Forms keep the include order, so the + merged registry is the same as one file with the parts concatenated. + """ + path = Path(path) with open(path, "rb") as handle: - return tomllib.load(handle) + registry = tomllib.load(handle) + 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") + if len(set(includes)) != len(includes): + raise RegistryError(f"{path.name}: a family file is included twice") + rules = registry.setdefault("operand_rules", {}) + forms = registry.setdefault("form", []) + for include in includes: + part_path = path.parent / include + family = Path(include).stem.upper() + if not part_path.is_file(): + raise RegistryError(f"{path.name}: included family file {include} does not exist") + with open(part_path, "rb") as handle: + part = tomllib.load(handle) + unknown = sorted(set(part) - FAMILY_FILE_KEYS) + if unknown: + raise RegistryError(f"{include}: keys {unknown} belong in the root file") + for name, rule in part.get("operand_rules", {}).items(): + if name in rules: + raise RegistryError(f"{include}: operand rule {name} is declared twice") + if not isinstance(rule, dict) or rule.get("family") != family: + raise RegistryError(f"{include}: operand rule {name} is not a {family} rule") + rules[name] = rule + for index, form in enumerate(part.get("form", [])): + if not isinstance(form, dict) or form.get("family") != family: + label = form.get("name", f"form #{index}") if isinstance(form, dict) else index + raise RegistryError(f"{include}: form {label} is not a {family} form") + forms.append(form) + return registry def load_snapshot(path=SNAPSHOT): @@ -1018,7 +1064,11 @@ def main(): 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) + try: + registry = load_registry(arguments.registry) + except RegistryError as error: + print(f"error: {error}", file=sys.stderr) + return 1 snapshot = load_snapshot(arguments.snapshot) errors = validate(registry, snapshot) if errors: diff --git a/crates/isa/semantics/rdna2.toml b/crates/isa/semantics/rdna2.toml index 29f678a..bfe7a4f 100644 --- a/crates/isa/semantics/rdna2.toml +++ b/crates/isa/semantics/rdna2.toml @@ -8,12 +8,21 @@ # 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. +# interpreter (tests/validation/independent_ref.rs) never read these files. schema = 1 architecture = "gfx1030" # Must equal the "sha256" of the source line in crates/isa/data/rdna2.jsonl. source_sha256 = "d671ecbc36543674ab59e9b2feffd56718fd2137e7ad913c314f2e2508b9f4f7" +# Family files, in this order (forms keep the order they are listed in; each +# file holds the operand rules and forms of one encoding family, named after it). +include = [ + "rdna2/sop2.toml", + "rdna2/sopc.toml", + "rdna2/sop1.toml", + "rdna2/vop2.toml", + "rdna2/vopc.toml", +] # Named public documents that spec references point at. [documents.guide] @@ -25,26 +34,7 @@ pages = 291 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: +# Form field meanings (every family file): # name XML instruction name (stable identity) # family encoding family; must match the XML base encoding # opcode XML opcode; must match @@ -59,1711 +49,3 @@ unsupported = [ # 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"] - -# ---- Stage C: further SOP2 logical and shift forms (#215) ---- -# Shifts use the low shift_count_bits of S1 as the count (guide 12.1 pseudocode). - -[[form]] -name = "S_ANDN2_B32" -family = "SOP2" -opcode = 20 -variant = "Andn2B32" -operation = "andn2" -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 = 103 }] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_ORN2_B32" -family = "SOP2" -opcode = 22 -variant = "Orn2B32" -operation = "orn2" -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 = 103 }] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_NAND_B32" -family = "SOP2" -opcode = 24 -variant = "NandB32" -operation = "nand" -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 = 104 }] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_NOR_B32" -family = "SOP2" -opcode = 26 -variant = "NorB32" -operation = "nor" -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 = 104 }] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_XNOR_B32" -family = "SOP2" -opcode = 28 -variant = "XnorB32" -operation = "xnor" -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 = 104 }] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_LSHL_B32" -family = "SOP2" -opcode = 30 -variant = "LshlB32" -operation = "lshl" -signedness = "bitwise" -carry_in = "none" -width = 32 -shift_count_bits = 5 -scc = "nonzero" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop2_sgpr" -spec = [{ document = "guide", section = "12.1", page = 104 }] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_LSHR_B32" -family = "SOP2" -opcode = 32 -variant = "LshrB32" -operation = "lshr" -signedness = "unsigned" -carry_in = "none" -width = 32 -shift_count_bits = 5 -scc = "nonzero" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop2_sgpr" -spec = [{ document = "guide", section = "12.1", page = 104 }] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_ASHR_I32" -family = "SOP2" -opcode = 34 -variant = "AshrI32" -operation = "ashr" -signedness = "signed" -carry_in = "none" -width = 32 -shift_count_bits = 5 -scc = "nonzero" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop2_sgpr" -spec = [{ document = "guide", section = "12.1", page = 104 }] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -# ---- SOP2 32-bit integer arithmetic, select and bit-field forms (#215) ---- -# min/max: SCC = S0 chosen by the strict compare (a tie gives S1, SCC 0). cselect -# reads SCC and writes none. bfm, mul, mul_hi write no SCC (Tables 11, 12, 14). -# bfe: offset S1[4:0], width S1[22:16]. lshl_add: SCC = carry of (S0 << N) + S1. - -[[form]] -name = "S_MIN_I32" -family = "SOP2" -opcode = 6 -variant = "MinI32" -operation = "min" -signedness = "signed" -carry_in = "none" -width = 32 -scc = "selected_src0" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop2_sgpr" -spec = [ - { document = "guide", section = "12.1", page = 102 }, - { document = "guide", section = "5.4", page = 34 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_MIN_U32" -family = "SOP2" -opcode = 7 -variant = "MinU32" -operation = "min" -signedness = "unsigned" -carry_in = "none" -width = 32 -scc = "selected_src0" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop2_sgpr" -spec = [ - { document = "guide", section = "12.1", page = 102 }, - { document = "guide", section = "5.4", page = 34 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_MAX_I32" -family = "SOP2" -opcode = 8 -variant = "MaxI32" -operation = "max" -signedness = "signed" -carry_in = "none" -width = 32 -scc = "selected_src0" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop2_sgpr" -spec = [ - { document = "guide", section = "12.1", page = 102 }, - { document = "guide", section = "5.4", page = 34 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_MAX_U32" -family = "SOP2" -opcode = 9 -variant = "MaxU32" -operation = "max" -signedness = "unsigned" -carry_in = "none" -width = 32 -scc = "selected_src0" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop2_sgpr" -spec = [ - { document = "guide", section = "12.1", page = 103 }, - { document = "guide", section = "5.4", page = 34 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_CSELECT_B32" -family = "SOP2" -opcode = 10 -variant = "CselectB32" -operation = "cselect" -signedness = "bitwise" -carry_in = "scc" -width = 32 -scc = "unchanged" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop2_sgpr" -spec = [ - { document = "guide", section = "12.1", page = 103 }, - { document = "guide", section = "5.5", page = 34 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_BFM_B32" -family = "SOP2" -opcode = 36 -variant = "BfmB32" -operation = "bfm" -signedness = "bitwise" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop2_sgpr" -spec = [ - { document = "guide", section = "12.1", page = 104 }, - { document = "guide", section = "5.7", page = 36 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_MUL_I32" -family = "SOP2" -opcode = 38 -variant = "MulI32" -operation = "mul" -signedness = "signed" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop2_sgpr" -spec = [ - { document = "guide", section = "12.1", page = 105 }, - { document = "guide", section = "5.4", page = 34 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_BFE_U32" -family = "SOP2" -opcode = 39 -variant = "BfeU32" -operation = "bfe" -signedness = "unsigned" -carry_in = "none" -width = 32 -scc = "nonzero" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop2_sgpr" -spec = [ - { document = "guide", section = "12.1", page = 105 }, - { document = "guide", section = "5.7", page = 36 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_BFE_I32" -family = "SOP2" -opcode = 40 -variant = "BfeI32" -operation = "bfe" -signedness = "signed" -carry_in = "none" -width = 32 -scc = "nonzero" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop2_sgpr" -spec = [ - { document = "guide", section = "12.1", page = 105 }, - { document = "guide", section = "5.7", page = 36 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_ABSDIFF_I32" -family = "SOP2" -opcode = 44 -variant = "AbsdiffI32" -operation = "absdiff" -signedness = "signed" -carry_in = "none" -width = 32 -scc = "nonzero" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop2_sgpr" -spec = [ - { document = "guide", section = "12.1", page = 105 }, - { document = "guide", section = "5.4", page = 34 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_LSHL1_ADD_U32" -family = "SOP2" -opcode = 46 -variant = "Lshl1AddU32" -operation = "lshl_add" -signedness = "unsigned" -carry_in = "none" -width = 32 -shift_amount = 1 -scc = "carry_out" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop2_sgpr" -spec = [{ document = "guide", section = "12.1", page = 105 }] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_LSHL2_ADD_U32" -family = "SOP2" -opcode = 47 -variant = "Lshl2AddU32" -operation = "lshl_add" -signedness = "unsigned" -carry_in = "none" -width = 32 -shift_amount = 2 -scc = "carry_out" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop2_sgpr" -spec = [{ document = "guide", section = "12.1", page = 105 }] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_LSHL3_ADD_U32" -family = "SOP2" -opcode = 48 -variant = "Lshl3AddU32" -operation = "lshl_add" -signedness = "unsigned" -carry_in = "none" -width = 32 -shift_amount = 3 -scc = "carry_out" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop2_sgpr" -spec = [{ document = "guide", section = "12.1", page = 106 }] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_LSHL4_ADD_U32" -family = "SOP2" -opcode = 49 -variant = "Lshl4AddU32" -operation = "lshl_add" -signedness = "unsigned" -carry_in = "none" -width = 32 -shift_amount = 4 -scc = "carry_out" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop2_sgpr" -spec = [{ document = "guide", section = "12.1", page = 106 }] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_MUL_HI_U32" -family = "SOP2" -opcode = 53 -variant = "MulHiU32" -operation = "mul_hi" -signedness = "unsigned" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop2_sgpr" -spec = [{ document = "guide", section = "12.1", page = 106 }] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_MUL_HI_I32" -family = "SOP2" -opcode = 54 -variant = "MulHiI32" -operation = "mul_hi" -signedness = "signed" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop2_sgpr" -spec = [{ document = "guide", section = "12.1", page = 106 }] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -# ---- Stage D: SOPC 32-bit integer compares (#215) ---- -# Only SCC is written: SCC = relation(S0, S1), S0 = SSRC0 on the left (guide 12.4). - -[operand_rules.sopc_scalar] -family = "SOPC" -src = [ - { field = "SSRC0", class = "scalar_source" }, - { field = "SSRC1", class = "scalar_source" }, -] -max_literals = 1 -unsupported = [ - "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_float_inline", - "src_special", "two_literals", -] - -[[form]] -name = "S_CMP_EQ_I32" -family = "SOPC" -opcode = 0 -variant = "CmpEqI32" -operation = "compare" -relation = "eq" -signedness = "signed" -carry_in = "none" -width = 32 -scc = "relation" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sopc_scalar" -spec = [ - { document = "guide", section = "12.4", page = 0 }, - { document = "guide", section = "5.3", page = 33 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_CMP_LG_I32" -family = "SOPC" -opcode = 1 -variant = "CmpLgI32" -operation = "compare" -relation = "lg" -signedness = "signed" -carry_in = "none" -width = 32 -scc = "relation" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sopc_scalar" -spec = [ - { document = "guide", section = "12.4", page = 0 }, - { document = "guide", section = "5.3", page = 33 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_CMP_GT_I32" -family = "SOPC" -opcode = 2 -variant = "CmpGtI32" -operation = "compare" -relation = "gt" -signedness = "signed" -carry_in = "none" -width = 32 -scc = "relation" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sopc_scalar" -spec = [ - { document = "guide", section = "12.4", page = 0 }, - { document = "guide", section = "5.3", page = 33 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_CMP_GE_I32" -family = "SOPC" -opcode = 3 -variant = "CmpGeI32" -operation = "compare" -relation = "ge" -signedness = "signed" -carry_in = "none" -width = 32 -scc = "relation" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sopc_scalar" -spec = [ - { document = "guide", section = "12.4", page = 0 }, - { document = "guide", section = "5.3", page = 33 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_CMP_LT_I32" -family = "SOPC" -opcode = 4 -variant = "CmpLtI32" -operation = "compare" -relation = "lt" -signedness = "signed" -carry_in = "none" -width = 32 -scc = "relation" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sopc_scalar" -spec = [ - { document = "guide", section = "12.4", page = 0 }, - { document = "guide", section = "5.3", page = 33 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_CMP_LE_I32" -family = "SOPC" -opcode = 5 -variant = "CmpLeI32" -operation = "compare" -relation = "le" -signedness = "signed" -carry_in = "none" -width = 32 -scc = "relation" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sopc_scalar" -spec = [ - { document = "guide", section = "12.4", page = 0 }, - { document = "guide", section = "5.3", page = 33 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_CMP_EQ_U32" -family = "SOPC" -opcode = 6 -variant = "CmpEqU32" -operation = "compare" -relation = "eq" -signedness = "unsigned" -carry_in = "none" -width = 32 -scc = "relation" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sopc_scalar" -spec = [ - { document = "guide", section = "12.4", page = 0 }, - { document = "guide", section = "5.3", page = 33 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_CMP_LG_U32" -family = "SOPC" -opcode = 7 -variant = "CmpLgU32" -operation = "compare" -relation = "lg" -signedness = "unsigned" -carry_in = "none" -width = 32 -scc = "relation" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sopc_scalar" -spec = [ - { document = "guide", section = "12.4", page = 0 }, - { document = "guide", section = "5.3", page = 33 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_CMP_GT_U32" -family = "SOPC" -opcode = 8 -variant = "CmpGtU32" -operation = "compare" -relation = "gt" -signedness = "unsigned" -carry_in = "none" -width = 32 -scc = "relation" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sopc_scalar" -spec = [ - { document = "guide", section = "12.4", page = 0 }, - { document = "guide", section = "5.3", page = 33 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_CMP_GE_U32" -family = "SOPC" -opcode = 9 -variant = "CmpGeU32" -operation = "compare" -relation = "ge" -signedness = "unsigned" -carry_in = "none" -width = 32 -scc = "relation" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sopc_scalar" -spec = [ - { document = "guide", section = "12.4", page = 0 }, - { document = "guide", section = "5.3", page = 33 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_CMP_LT_U32" -family = "SOPC" -opcode = 10 -variant = "CmpLtU32" -operation = "compare" -relation = "lt" -signedness = "unsigned" -carry_in = "none" -width = 32 -scc = "relation" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sopc_scalar" -spec = [ - { document = "guide", section = "12.4", page = 0 }, - { document = "guide", section = "5.3", page = 33 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_CMP_LE_U32" -family = "SOPC" -opcode = 11 -variant = "CmpLeU32" -operation = "compare" -relation = "le" -signedness = "unsigned" -carry_in = "none" -width = 32 -scc = "relation" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sopc_scalar" -spec = [ - { document = "guide", section = "12.4", page = 0 }, - { document = "guide", section = "5.3", page = 33 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -# ---- SOP1 32-bit unary integer forms (#215) ---- -# NOT, BCNT0, BCNT1 and ABS set SCC = (D != 0); the others leave SCC unchanged. -# Searches that find nothing return -1 (guide 12.3). - -[operand_rules.sop1_sgpr] -family = "SOP1" -dst = { field = "SDST", class = "sgpr", min = 0, max = 105 } -src = [{ field = "SSRC0", class = "scalar_source" }] -max_literals = 1 -unsupported = [ - "dst_vcc", "dst_exec", "dst_ttmp", "dst_m0", "dst_null", - "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_float_inline", "src_special", -] - -[[form]] -name = "S_NOT_B32" -family = "SOP1" -opcode = 7 -variant = "NotB32" -operation = "not" -signedness = "bitwise" -carry_in = "none" -width = 32 -scc = "nonzero" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop1_sgpr" -spec = [ - { document = "guide", section = "12.3", page = 0 }, - { document = "guide", section = "5.3", page = 33 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_BREV_B32" -family = "SOP1" -opcode = 11 -variant = "BrevB32" -operation = "brev" -signedness = "bitwise" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop1_sgpr" -spec = [ - { document = "guide", section = "12.3", page = 0 }, - { document = "guide", section = "5.3", page = 33 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_BCNT0_I32_B32" -family = "SOP1" -opcode = 13 -variant = "Bcnt0I32B32" -operation = "bcnt0" -signedness = "bitwise" -carry_in = "none" -width = 32 -scc = "nonzero" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop1_sgpr" -spec = [ - { document = "guide", section = "12.3", page = 0 }, - { document = "guide", section = "5.3", page = 33 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_BCNT1_I32_B32" -family = "SOP1" -opcode = 15 -variant = "Bcnt1I32B32" -operation = "bcnt1" -signedness = "bitwise" -carry_in = "none" -width = 32 -scc = "nonzero" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop1_sgpr" -spec = [ - { document = "guide", section = "12.3", page = 0 }, - { document = "guide", section = "5.3", page = 33 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_FF0_I32_B32" -family = "SOP1" -opcode = 17 -variant = "Ff0I32B32" -operation = "ff0" -signedness = "bitwise" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop1_sgpr" -spec = [ - { document = "guide", section = "12.3", page = 0 }, - { document = "guide", section = "5.3", page = 33 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_FF1_I32_B32" -family = "SOP1" -opcode = 19 -variant = "Ff1I32B32" -operation = "ff1" -signedness = "bitwise" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop1_sgpr" -spec = [ - { document = "guide", section = "12.3", page = 0 }, - { document = "guide", section = "5.3", page = 33 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_FLBIT_I32_B32" -family = "SOP1" -opcode = 21 -variant = "FlbitI32B32" -operation = "flbit" -signedness = "bitwise" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop1_sgpr" -spec = [ - { document = "guide", section = "12.3", page = 0 }, - { document = "guide", section = "5.3", page = 33 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_FLBIT_I32" -family = "SOP1" -opcode = 23 -variant = "FlbitI32" -operation = "flbit" -signedness = "signed" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop1_sgpr" -spec = [ - { document = "guide", section = "12.3", page = 0 }, - { document = "guide", section = "5.3", page = 33 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_SEXT_I32_I8" -family = "SOP1" -opcode = 25 -variant = "SextI32I8" -operation = "sext" -signedness = "signed" -carry_in = "none" -width = 32 -source_bits = 8 -scc = "unchanged" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop1_sgpr" -spec = [ - { document = "guide", section = "12.3", page = 0 }, - { document = "guide", section = "5.3", page = 33 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_SEXT_I32_I16" -family = "SOP1" -opcode = 26 -variant = "SextI32I16" -operation = "sext" -signedness = "signed" -carry_in = "none" -width = 32 -source_bits = 16 -scc = "unchanged" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop1_sgpr" -spec = [ - { document = "guide", section = "12.3", page = 0 }, - { document = "guide", section = "5.3", page = 33 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "S_ABS_I32" -family = "SOP1" -opcode = 52 -variant = "AbsI32" -operation = "abs" -signedness = "signed" -carry_in = "none" -width = 32 -scc = "nonzero" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "sop1_sgpr" -spec = [ - { document = "guide", section = "12.3", page = 0 }, - { document = "guide", section = "5.3", page = 33 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -# ---- VOP2 32-bit vector integer forms (#215) ---- -# Per lane under EXEC; no SCC, VCC or EXEC write (guide 12.7). The 24-bit -# multiplies read S0[23:0] and S1[23:0], sign-extended when signed; the high -# forms keep bits 63:32 of the product. SUBREV declares its reversed sources. - -[operand_rules.vop2_vgpr] -family = "VOP2" -dst = { field = "VDST", class = "vgpr", min = 0, max = 255 } -src = [ - { field = "SRC0", class = "vector_source" }, - { field = "VSRC1", class = "vgpr" }, -] -# vector_source = VGPR, normal SGPR s0-s105, vcc_lo, inline integer -16..64, or a literal word. -max_literals = 1 -unsupported = [ - "src_vcc_hi", "src_exec", "src_m0", "src_ttmp", "src_null", "src_float_inline", "src_special", -] - -[[form]] -name = "V_MUL_I32_I24" -family = "VOP2" -opcode = 9 -variant = "MulI32I24" -operation = "mul24" -signedness = "signed" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "vop2_vgpr" -spec = [{ document = "guide", section = "12.7", page = 131 }] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "V_MUL_HI_I32_I24" -family = "VOP2" -opcode = 10 -variant = "MulHiI32I24" -operation = "mul_hi24" -signedness = "signed" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "vop2_vgpr" -spec = [{ document = "guide", section = "12.7", page = 132 }] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "V_MUL_U32_U24" -family = "VOP2" -opcode = 11 -variant = "MulU32U24" -operation = "mul24" -signedness = "unsigned" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "vop2_vgpr" -spec = [{ document = "guide", section = "12.7", page = 132 }] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "V_MUL_HI_U32_U24" -family = "VOP2" -opcode = 12 -variant = "MulHiU32U24" -operation = "mul_hi24" -signedness = "unsigned" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "vop2_vgpr" -spec = [{ document = "guide", section = "12.7", page = 132 }] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "V_MIN_I32" -family = "VOP2" -opcode = 17 -variant = "MinI32" -operation = "min" -signedness = "signed" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "vop2_vgpr" -spec = [{ document = "guide", section = "12.7", page = 133 }] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "V_MAX_I32" -family = "VOP2" -opcode = 18 -variant = "MaxI32" -operation = "max" -signedness = "signed" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "vop2_vgpr" -spec = [{ document = "guide", section = "12.7", page = 133 }] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "V_MIN_U32" -family = "VOP2" -opcode = 19 -variant = "MinU32" -operation = "min" -signedness = "unsigned" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "vop2_vgpr" -spec = [{ document = "guide", section = "12.7", page = 133 }] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "V_MAX_U32" -family = "VOP2" -opcode = 20 -variant = "MaxU32" -operation = "max" -signedness = "unsigned" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "vop2_vgpr" -spec = [{ document = "guide", section = "12.7", page = 133 }] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "V_XNOR_B32" -family = "VOP2" -opcode = 30 -variant = "XnorB32" -operation = "xnor" -signedness = "bitwise" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "vop2_vgpr" -spec = [{ document = "guide", section = "12.7", page = 134 }] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "V_ADD_NC_U32" -family = "VOP2" -opcode = 37 -variant = "AddNcU32" -operation = "add" -signedness = "unsigned" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "vop2_vgpr" -spec = [{ document = "guide", section = "12.7", page = 134 }] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "V_SUB_NC_U32" -family = "VOP2" -opcode = 38 -variant = "SubNcU32" -operation = "sub" -signedness = "unsigned" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "vop2_vgpr" -spec = [{ document = "guide", section = "12.7", page = 134 }] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "V_SUBREV_NC_U32" -family = "VOP2" -opcode = 39 -variant = "SubrevNcU32" -operation = "sub" -signedness = "unsigned" -carry_in = "none" -width = 32 -source_order = "reversed" -scc = "unchanged" -vcc = "unchanged" -exec = "unchanged" -wave = "any" -operands = "vop2_vgpr" -spec = [{ document = "guide", section = "12.7", page = 134 }] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -# ---- VOPC Wave32 32-bit integer compares (migrated from #239) ---- -# VCC_LO := lanes where EXEC and the relation (S0 = SRC0 on the left) hold; -# the contract is docs/shaders/vector-compare.md. relation "lg" is the guide's -# LG/NE offset 5 (Table 59), named V_CMP_NE_* in the XML. v_cmpx (EXEC writes), -# the VOP3 encoding and Wave64 stay unsupported. -[operand_rules.vopc_vcc] -family = "VOPC" -src = [ - { field = "SRC0", class = "vector_source" }, - { field = "VSRC1", class = "vgpr" }, -] -# The destination is implicitly vcc_lo; SRC0 is a vector_source as for VOP2. -max_literals = 1 -unsupported = [ - "src_vcc_hi", "src_exec", "src_m0", "src_ttmp", "src_null", "src_float_inline", "src_special", -] - -[[form]] -name = "V_CMP_LT_I32" -family = "VOPC" -opcode = 129 -variant = "CmpLtI32" -operation = "compare" -relation = "lt" -signedness = "signed" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "lane_mask" -exec = "unchanged" -wave = "wave32" -operands = "vopc_vcc" -spec = [ - { document = "guide", section = "12.9", page = 150 }, - { document = "guide", section = "3.9", page = 19 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "V_CMP_EQ_I32" -family = "VOPC" -opcode = 130 -variant = "CmpEqI32" -operation = "compare" -relation = "eq" -signedness = "signed" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "lane_mask" -exec = "unchanged" -wave = "wave32" -operands = "vopc_vcc" -spec = [ - { document = "guide", section = "12.9", page = 150 }, - { document = "guide", section = "3.9", page = 19 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "V_CMP_LE_I32" -family = "VOPC" -opcode = 131 -variant = "CmpLeI32" -operation = "compare" -relation = "le" -signedness = "signed" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "lane_mask" -exec = "unchanged" -wave = "wave32" -operands = "vopc_vcc" -spec = [ - { document = "guide", section = "12.9", page = 150 }, - { document = "guide", section = "3.9", page = 19 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "V_CMP_GT_I32" -family = "VOPC" -opcode = 132 -variant = "CmpGtI32" -operation = "compare" -relation = "gt" -signedness = "signed" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "lane_mask" -exec = "unchanged" -wave = "wave32" -operands = "vopc_vcc" -spec = [ - { document = "guide", section = "12.9", page = 150 }, - { document = "guide", section = "3.9", page = 19 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "V_CMP_NE_I32" -family = "VOPC" -opcode = 133 -variant = "CmpNeI32" -operation = "compare" -relation = "lg" -signedness = "signed" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "lane_mask" -exec = "unchanged" -wave = "wave32" -operands = "vopc_vcc" -spec = [ - { document = "guide", section = "12.9", page = 150 }, - { document = "guide", section = "3.9", page = 19 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "V_CMP_GE_I32" -family = "VOPC" -opcode = 134 -variant = "CmpGeI32" -operation = "compare" -relation = "ge" -signedness = "signed" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "lane_mask" -exec = "unchanged" -wave = "wave32" -operands = "vopc_vcc" -spec = [ - { document = "guide", section = "12.9", page = 150 }, - { document = "guide", section = "3.9", page = 19 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "V_CMP_LT_U32" -family = "VOPC" -opcode = 193 -variant = "CmpLtU32" -operation = "compare" -relation = "lt" -signedness = "unsigned" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "lane_mask" -exec = "unchanged" -wave = "wave32" -operands = "vopc_vcc" -spec = [ - { document = "guide", section = "12.9", page = 150 }, - { document = "guide", section = "3.9", page = 19 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "V_CMP_EQ_U32" -family = "VOPC" -opcode = 194 -variant = "CmpEqU32" -operation = "compare" -relation = "eq" -signedness = "unsigned" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "lane_mask" -exec = "unchanged" -wave = "wave32" -operands = "vopc_vcc" -spec = [ - { document = "guide", section = "12.9", page = 150 }, - { document = "guide", section = "3.9", page = 19 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "V_CMP_LE_U32" -family = "VOPC" -opcode = 195 -variant = "CmpLeU32" -operation = "compare" -relation = "le" -signedness = "unsigned" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "lane_mask" -exec = "unchanged" -wave = "wave32" -operands = "vopc_vcc" -spec = [ - { document = "guide", section = "12.9", page = 150 }, - { document = "guide", section = "3.9", page = 19 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "V_CMP_GT_U32" -family = "VOPC" -opcode = 196 -variant = "CmpGtU32" -operation = "compare" -relation = "gt" -signedness = "unsigned" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "lane_mask" -exec = "unchanged" -wave = "wave32" -operands = "vopc_vcc" -spec = [ - { document = "guide", section = "12.9", page = 150 }, - { document = "guide", section = "3.9", page = 19 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "V_CMP_NE_U32" -family = "VOPC" -opcode = 197 -variant = "CmpNeU32" -operation = "compare" -relation = "lg" -signedness = "unsigned" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "lane_mask" -exec = "unchanged" -wave = "wave32" -operands = "vopc_vcc" -spec = [ - { document = "guide", section = "12.9", page = 150 }, - { document = "guide", section = "3.9", page = 19 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "V_CMP_GE_U32" -family = "VOPC" -opcode = 198 -variant = "CmpGeU32" -operation = "compare" -relation = "ge" -signedness = "unsigned" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "lane_mask" -exec = "unchanged" -wave = "wave32" -operands = "vopc_vcc" -spec = [ - { document = "guide", section = "12.9", page = 150 }, - { document = "guide", section = "3.9", page = 19 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -# ---- VOPC F and T compares (guide Table 59 offsets 0 and 7) ---- -# The test is false or true for every lane, so VCC_LO := 0 or the EXEC lanes -# that exist. Sources are still decoded and checked as for the other compares -# (docs/shaders/vector-compare.md section 5). - -[[form]] -name = "V_CMP_F_I32" -family = "VOPC" -opcode = 128 -variant = "CmpFI32" -operation = "compare" -relation = "f" -signedness = "signed" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "lane_mask" -exec = "unchanged" -wave = "wave32" -operands = "vopc_vcc" -spec = [ - { document = "guide", section = "12.9", page = 150 }, - { document = "guide", section = "3.9", page = 19 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "V_CMP_T_I32" -family = "VOPC" -opcode = 135 -variant = "CmpTI32" -operation = "compare" -relation = "t" -signedness = "signed" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "lane_mask" -exec = "unchanged" -wave = "wave32" -operands = "vopc_vcc" -spec = [ - { document = "guide", section = "12.9", page = 150 }, - { document = "guide", section = "3.9", page = 19 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "V_CMP_F_U32" -family = "VOPC" -opcode = 192 -variant = "CmpFU32" -operation = "compare" -relation = "f" -signedness = "unsigned" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "lane_mask" -exec = "unchanged" -wave = "wave32" -operands = "vopc_vcc" -spec = [ - { document = "guide", section = "12.9", page = 150 }, - { document = "guide", section = "3.9", page = 19 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] - -[[form]] -name = "V_CMP_T_U32" -family = "VOPC" -opcode = 199 -variant = "CmpTU32" -operation = "compare" -relation = "t" -signedness = "unsigned" -carry_in = "none" -width = 32 -scc = "unchanged" -vcc = "lane_mask" -exec = "unchanged" -wave = "wave32" -operands = "vopc_vcc" -spec = [ - { document = "guide", section = "12.9", page = 150 }, - { document = "guide", section = "3.9", page = 19 }, -] -verify = ["reference", "independent", "metal", "llvm_encoding"] diff --git a/crates/isa/semantics/rdna2/sop1.toml b/crates/isa/semantics/rdna2/sop1.toml new file mode 100644 index 0000000..ec7b75a --- /dev/null +++ b/crates/isa/semantics/rdna2/sop1.toml @@ -0,0 +1,238 @@ +# SOP1 forms of the gfx1030 semantic registry; included by ../rdna2.toml. +# Data only; see the root file for the field meanings. + +# ---- SOP1 32-bit unary integer forms (#215) ---- +# NOT, BCNT0, BCNT1 and ABS set SCC = (D != 0); the others leave SCC unchanged. +# Searches that find nothing return -1 (guide 12.3). + +[operand_rules.sop1_sgpr] +family = "SOP1" +dst = { field = "SDST", class = "sgpr", min = 0, max = 105 } +src = [{ field = "SSRC0", class = "scalar_source" }] +max_literals = 1 +unsupported = [ + "dst_vcc", "dst_exec", "dst_ttmp", "dst_m0", "dst_null", + "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_float_inline", "src_special", +] + +[[form]] +name = "S_NOT_B32" +family = "SOP1" +opcode = 7 +variant = "NotB32" +operation = "not" +signedness = "bitwise" +carry_in = "none" +width = 32 +scc = "nonzero" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop1_sgpr" +spec = [ + { document = "guide", section = "12.3", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_BREV_B32" +family = "SOP1" +opcode = 11 +variant = "BrevB32" +operation = "brev" +signedness = "bitwise" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop1_sgpr" +spec = [ + { document = "guide", section = "12.3", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_BCNT0_I32_B32" +family = "SOP1" +opcode = 13 +variant = "Bcnt0I32B32" +operation = "bcnt0" +signedness = "bitwise" +carry_in = "none" +width = 32 +scc = "nonzero" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop1_sgpr" +spec = [ + { document = "guide", section = "12.3", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_BCNT1_I32_B32" +family = "SOP1" +opcode = 15 +variant = "Bcnt1I32B32" +operation = "bcnt1" +signedness = "bitwise" +carry_in = "none" +width = 32 +scc = "nonzero" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop1_sgpr" +spec = [ + { document = "guide", section = "12.3", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_FF0_I32_B32" +family = "SOP1" +opcode = 17 +variant = "Ff0I32B32" +operation = "ff0" +signedness = "bitwise" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop1_sgpr" +spec = [ + { document = "guide", section = "12.3", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_FF1_I32_B32" +family = "SOP1" +opcode = 19 +variant = "Ff1I32B32" +operation = "ff1" +signedness = "bitwise" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop1_sgpr" +spec = [ + { document = "guide", section = "12.3", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_FLBIT_I32_B32" +family = "SOP1" +opcode = 21 +variant = "FlbitI32B32" +operation = "flbit" +signedness = "bitwise" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop1_sgpr" +spec = [ + { document = "guide", section = "12.3", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_FLBIT_I32" +family = "SOP1" +opcode = 23 +variant = "FlbitI32" +operation = "flbit" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop1_sgpr" +spec = [ + { document = "guide", section = "12.3", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_SEXT_I32_I8" +family = "SOP1" +opcode = 25 +variant = "SextI32I8" +operation = "sext" +signedness = "signed" +carry_in = "none" +width = 32 +source_bits = 8 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop1_sgpr" +spec = [ + { document = "guide", section = "12.3", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_SEXT_I32_I16" +family = "SOP1" +opcode = 26 +variant = "SextI32I16" +operation = "sext" +signedness = "signed" +carry_in = "none" +width = 32 +source_bits = 16 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop1_sgpr" +spec = [ + { document = "guide", section = "12.3", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_ABS_I32" +family = "SOP1" +opcode = 52 +variant = "AbsI32" +operation = "abs" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "nonzero" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop1_sgpr" +spec = [ + { document = "guide", section = "12.3", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] diff --git a/crates/isa/semantics/rdna2/sop2.toml b/crates/isa/semantics/rdna2/sop2.toml new file mode 100644 index 0000000..8452abf --- /dev/null +++ b/crates/isa/semantics/rdna2/sop2.toml @@ -0,0 +1,647 @@ +# SOP2 forms of the gfx1030 semantic registry; included by ../rdna2.toml. +# Data only; see the root file for the field meanings. + +# ---- SOP2 32-bit integer and logical forms (migrated from #229/#230) ---- + +# 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", +] + + +[[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"] + +# ---- Stage C: further SOP2 logical and shift forms (#215) ---- +# Shifts use the low shift_count_bits of S1 as the count (guide 12.1 pseudocode). + +[[form]] +name = "S_ANDN2_B32" +family = "SOP2" +opcode = 20 +variant = "Andn2B32" +operation = "andn2" +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 = 103 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_ORN2_B32" +family = "SOP2" +opcode = 22 +variant = "Orn2B32" +operation = "orn2" +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 = 103 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_NAND_B32" +family = "SOP2" +opcode = 24 +variant = "NandB32" +operation = "nand" +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 = 104 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_NOR_B32" +family = "SOP2" +opcode = 26 +variant = "NorB32" +operation = "nor" +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 = 104 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_XNOR_B32" +family = "SOP2" +opcode = 28 +variant = "XnorB32" +operation = "xnor" +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 = 104 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_LSHL_B32" +family = "SOP2" +opcode = 30 +variant = "LshlB32" +operation = "lshl" +signedness = "bitwise" +carry_in = "none" +width = 32 +shift_count_bits = 5 +scc = "nonzero" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop2_sgpr" +spec = [{ document = "guide", section = "12.1", page = 104 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_LSHR_B32" +family = "SOP2" +opcode = 32 +variant = "LshrB32" +operation = "lshr" +signedness = "unsigned" +carry_in = "none" +width = 32 +shift_count_bits = 5 +scc = "nonzero" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop2_sgpr" +spec = [{ document = "guide", section = "12.1", page = 104 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_ASHR_I32" +family = "SOP2" +opcode = 34 +variant = "AshrI32" +operation = "ashr" +signedness = "signed" +carry_in = "none" +width = 32 +shift_count_bits = 5 +scc = "nonzero" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop2_sgpr" +spec = [{ document = "guide", section = "12.1", page = 104 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +# ---- SOP2 32-bit integer arithmetic, select and bit-field forms (#215) ---- +# min/max: SCC = S0 chosen by the strict compare (a tie gives S1, SCC 0). cselect +# reads SCC and writes none. bfm, mul, mul_hi write no SCC (Tables 11, 12, 14). +# bfe: offset S1[4:0], width S1[22:16]. lshl_add: SCC = carry of (S0 << N) + S1. + +[[form]] +name = "S_MIN_I32" +family = "SOP2" +opcode = 6 +variant = "MinI32" +operation = "min" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "selected_src0" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop2_sgpr" +spec = [ + { document = "guide", section = "12.1", page = 102 }, + { document = "guide", section = "5.4", page = 34 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_MIN_U32" +family = "SOP2" +opcode = 7 +variant = "MinU32" +operation = "min" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "selected_src0" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop2_sgpr" +spec = [ + { document = "guide", section = "12.1", page = 102 }, + { document = "guide", section = "5.4", page = 34 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_MAX_I32" +family = "SOP2" +opcode = 8 +variant = "MaxI32" +operation = "max" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "selected_src0" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop2_sgpr" +spec = [ + { document = "guide", section = "12.1", page = 102 }, + { document = "guide", section = "5.4", page = 34 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_MAX_U32" +family = "SOP2" +opcode = 9 +variant = "MaxU32" +operation = "max" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "selected_src0" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop2_sgpr" +spec = [ + { document = "guide", section = "12.1", page = 103 }, + { document = "guide", section = "5.4", page = 34 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_CSELECT_B32" +family = "SOP2" +opcode = 10 +variant = "CselectB32" +operation = "cselect" +signedness = "bitwise" +carry_in = "scc" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop2_sgpr" +spec = [ + { document = "guide", section = "12.1", page = 103 }, + { document = "guide", section = "5.5", page = 34 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_BFM_B32" +family = "SOP2" +opcode = 36 +variant = "BfmB32" +operation = "bfm" +signedness = "bitwise" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop2_sgpr" +spec = [ + { document = "guide", section = "12.1", page = 104 }, + { document = "guide", section = "5.7", page = 36 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_MUL_I32" +family = "SOP2" +opcode = 38 +variant = "MulI32" +operation = "mul" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop2_sgpr" +spec = [ + { document = "guide", section = "12.1", page = 105 }, + { document = "guide", section = "5.4", page = 34 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_BFE_U32" +family = "SOP2" +opcode = 39 +variant = "BfeU32" +operation = "bfe" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "nonzero" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop2_sgpr" +spec = [ + { document = "guide", section = "12.1", page = 105 }, + { document = "guide", section = "5.7", page = 36 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_BFE_I32" +family = "SOP2" +opcode = 40 +variant = "BfeI32" +operation = "bfe" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "nonzero" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop2_sgpr" +spec = [ + { document = "guide", section = "12.1", page = 105 }, + { document = "guide", section = "5.7", page = 36 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_ABSDIFF_I32" +family = "SOP2" +opcode = 44 +variant = "AbsdiffI32" +operation = "absdiff" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "nonzero" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop2_sgpr" +spec = [ + { document = "guide", section = "12.1", page = 105 }, + { document = "guide", section = "5.4", page = 34 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_LSHL1_ADD_U32" +family = "SOP2" +opcode = 46 +variant = "Lshl1AddU32" +operation = "lshl_add" +signedness = "unsigned" +carry_in = "none" +width = 32 +shift_amount = 1 +scc = "carry_out" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop2_sgpr" +spec = [{ document = "guide", section = "12.1", page = 105 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_LSHL2_ADD_U32" +family = "SOP2" +opcode = 47 +variant = "Lshl2AddU32" +operation = "lshl_add" +signedness = "unsigned" +carry_in = "none" +width = 32 +shift_amount = 2 +scc = "carry_out" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop2_sgpr" +spec = [{ document = "guide", section = "12.1", page = 105 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_LSHL3_ADD_U32" +family = "SOP2" +opcode = 48 +variant = "Lshl3AddU32" +operation = "lshl_add" +signedness = "unsigned" +carry_in = "none" +width = 32 +shift_amount = 3 +scc = "carry_out" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop2_sgpr" +spec = [{ document = "guide", section = "12.1", page = 106 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_LSHL4_ADD_U32" +family = "SOP2" +opcode = 49 +variant = "Lshl4AddU32" +operation = "lshl_add" +signedness = "unsigned" +carry_in = "none" +width = 32 +shift_amount = 4 +scc = "carry_out" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop2_sgpr" +spec = [{ document = "guide", section = "12.1", page = 106 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_MUL_HI_U32" +family = "SOP2" +opcode = 53 +variant = "MulHiU32" +operation = "mul_hi" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop2_sgpr" +spec = [{ document = "guide", section = "12.1", page = 106 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_MUL_HI_I32" +family = "SOP2" +opcode = 54 +variant = "MulHiI32" +operation = "mul_hi" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sop2_sgpr" +spec = [{ document = "guide", section = "12.1", page = 106 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] diff --git a/crates/isa/semantics/rdna2/sopc.toml b/crates/isa/semantics/rdna2/sopc.toml new file mode 100644 index 0000000..94d7e3b --- /dev/null +++ b/crates/isa/semantics/rdna2/sopc.toml @@ -0,0 +1,269 @@ +# SOPC forms of the gfx1030 semantic registry; included by ../rdna2.toml. +# Data only; see the root file for the field meanings. + +# ---- Stage D: SOPC 32-bit integer compares (#215) ---- +# Only SCC is written: SCC = relation(S0, S1), S0 = SSRC0 on the left (guide 12.4). + +[operand_rules.sopc_scalar] +family = "SOPC" +src = [ + { field = "SSRC0", class = "scalar_source" }, + { field = "SSRC1", class = "scalar_source" }, +] +max_literals = 1 +unsupported = [ + "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_float_inline", + "src_special", "two_literals", +] + +[[form]] +name = "S_CMP_EQ_I32" +family = "SOPC" +opcode = 0 +variant = "CmpEqI32" +operation = "compare" +relation = "eq" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "relation" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sopc_scalar" +spec = [ + { document = "guide", section = "12.4", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_CMP_LG_I32" +family = "SOPC" +opcode = 1 +variant = "CmpLgI32" +operation = "compare" +relation = "lg" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "relation" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sopc_scalar" +spec = [ + { document = "guide", section = "12.4", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_CMP_GT_I32" +family = "SOPC" +opcode = 2 +variant = "CmpGtI32" +operation = "compare" +relation = "gt" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "relation" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sopc_scalar" +spec = [ + { document = "guide", section = "12.4", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_CMP_GE_I32" +family = "SOPC" +opcode = 3 +variant = "CmpGeI32" +operation = "compare" +relation = "ge" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "relation" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sopc_scalar" +spec = [ + { document = "guide", section = "12.4", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_CMP_LT_I32" +family = "SOPC" +opcode = 4 +variant = "CmpLtI32" +operation = "compare" +relation = "lt" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "relation" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sopc_scalar" +spec = [ + { document = "guide", section = "12.4", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_CMP_LE_I32" +family = "SOPC" +opcode = 5 +variant = "CmpLeI32" +operation = "compare" +relation = "le" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "relation" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sopc_scalar" +spec = [ + { document = "guide", section = "12.4", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_CMP_EQ_U32" +family = "SOPC" +opcode = 6 +variant = "CmpEqU32" +operation = "compare" +relation = "eq" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "relation" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sopc_scalar" +spec = [ + { document = "guide", section = "12.4", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_CMP_LG_U32" +family = "SOPC" +opcode = 7 +variant = "CmpLgU32" +operation = "compare" +relation = "lg" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "relation" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sopc_scalar" +spec = [ + { document = "guide", section = "12.4", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_CMP_GT_U32" +family = "SOPC" +opcode = 8 +variant = "CmpGtU32" +operation = "compare" +relation = "gt" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "relation" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sopc_scalar" +spec = [ + { document = "guide", section = "12.4", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_CMP_GE_U32" +family = "SOPC" +opcode = 9 +variant = "CmpGeU32" +operation = "compare" +relation = "ge" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "relation" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sopc_scalar" +spec = [ + { document = "guide", section = "12.4", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_CMP_LT_U32" +family = "SOPC" +opcode = 10 +variant = "CmpLtU32" +operation = "compare" +relation = "lt" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "relation" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sopc_scalar" +spec = [ + { document = "guide", section = "12.4", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "S_CMP_LE_U32" +family = "SOPC" +opcode = 11 +variant = "CmpLeU32" +operation = "compare" +relation = "le" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "relation" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "sopc_scalar" +spec = [ + { document = "guide", section = "12.4", page = 0 }, + { document = "guide", section = "5.3", page = 33 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] diff --git a/crates/isa/semantics/rdna2/vop2.toml b/crates/isa/semantics/rdna2/vop2.toml new file mode 100644 index 0000000..1ccce38 --- /dev/null +++ b/crates/isa/semantics/rdna2/vop2.toml @@ -0,0 +1,225 @@ +# VOP2 forms of the gfx1030 semantic registry; included by ../rdna2.toml. +# Data only; see the root file for the field meanings. + +# ---- VOP2 32-bit vector integer forms (#215) ---- +# Per lane under EXEC; no SCC, VCC or EXEC write (guide 12.7). The 24-bit +# multiplies read S0[23:0] and S1[23:0], sign-extended when signed; the high +# forms keep bits 63:32 of the product. SUBREV declares its reversed sources. + +[operand_rules.vop2_vgpr] +family = "VOP2" +dst = { field = "VDST", class = "vgpr", min = 0, max = 255 } +src = [ + { field = "SRC0", class = "vector_source" }, + { field = "VSRC1", class = "vgpr" }, +] +# vector_source = VGPR, normal SGPR s0-s105, vcc_lo, inline integer -16..64, or a literal word. +max_literals = 1 +unsupported = [ + "src_vcc_hi", "src_exec", "src_m0", "src_ttmp", "src_null", "src_float_inline", "src_special", +] + +[[form]] +name = "V_MUL_I32_I24" +family = "VOP2" +opcode = 9 +variant = "MulI32I24" +operation = "mul24" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "vop2_vgpr" +spec = [{ document = "guide", section = "12.7", page = 131 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_MUL_HI_I32_I24" +family = "VOP2" +opcode = 10 +variant = "MulHiI32I24" +operation = "mul_hi24" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "vop2_vgpr" +spec = [{ document = "guide", section = "12.7", page = 132 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_MUL_U32_U24" +family = "VOP2" +opcode = 11 +variant = "MulU32U24" +operation = "mul24" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "vop2_vgpr" +spec = [{ document = "guide", section = "12.7", page = 132 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_MUL_HI_U32_U24" +family = "VOP2" +opcode = 12 +variant = "MulHiU32U24" +operation = "mul_hi24" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "vop2_vgpr" +spec = [{ document = "guide", section = "12.7", page = 132 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_MIN_I32" +family = "VOP2" +opcode = 17 +variant = "MinI32" +operation = "min" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "vop2_vgpr" +spec = [{ document = "guide", section = "12.7", page = 133 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_MAX_I32" +family = "VOP2" +opcode = 18 +variant = "MaxI32" +operation = "max" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "vop2_vgpr" +spec = [{ document = "guide", section = "12.7", page = 133 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_MIN_U32" +family = "VOP2" +opcode = 19 +variant = "MinU32" +operation = "min" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "vop2_vgpr" +spec = [{ document = "guide", section = "12.7", page = 133 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_MAX_U32" +family = "VOP2" +opcode = 20 +variant = "MaxU32" +operation = "max" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "vop2_vgpr" +spec = [{ document = "guide", section = "12.7", page = 133 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_XNOR_B32" +family = "VOP2" +opcode = 30 +variant = "XnorB32" +operation = "xnor" +signedness = "bitwise" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "vop2_vgpr" +spec = [{ document = "guide", section = "12.7", page = 134 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_ADD_NC_U32" +family = "VOP2" +opcode = 37 +variant = "AddNcU32" +operation = "add" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "vop2_vgpr" +spec = [{ document = "guide", section = "12.7", page = 134 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_SUB_NC_U32" +family = "VOP2" +opcode = 38 +variant = "SubNcU32" +operation = "sub" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "vop2_vgpr" +spec = [{ document = "guide", section = "12.7", page = 134 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_SUBREV_NC_U32" +family = "VOP2" +opcode = 39 +variant = "SubrevNcU32" +operation = "sub" +signedness = "unsigned" +carry_in = "none" +width = 32 +source_order = "reversed" +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "vop2_vgpr" +spec = [{ document = "guide", section = "12.7", page = 134 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] diff --git a/crates/isa/semantics/rdna2/vopc.toml b/crates/isa/semantics/rdna2/vopc.toml new file mode 100644 index 0000000..d3bfe8a --- /dev/null +++ b/crates/isa/semantics/rdna2/vopc.toml @@ -0,0 +1,360 @@ +# VOPC forms of the gfx1030 semantic registry; included by ../rdna2.toml. +# Data only; see the root file for the field meanings. + +# ---- VOPC Wave32 32-bit integer compares (migrated from #239) ---- +# VCC_LO := lanes where EXEC and the relation (S0 = SRC0 on the left) hold; +# the contract is docs/shaders/vector-compare.md. relation "lg" is the guide's +# LG/NE offset 5 (Table 59), named V_CMP_NE_* in the XML. v_cmpx (EXEC writes), +# the VOP3 encoding and Wave64 stay unsupported. +[operand_rules.vopc_vcc] +family = "VOPC" +src = [ + { field = "SRC0", class = "vector_source" }, + { field = "VSRC1", class = "vgpr" }, +] +# The destination is implicitly vcc_lo; SRC0 is a vector_source as for VOP2. +max_literals = 1 +unsupported = [ + "src_vcc_hi", "src_exec", "src_m0", "src_ttmp", "src_null", "src_float_inline", "src_special", +] + +[[form]] +name = "V_CMP_LT_I32" +family = "VOPC" +opcode = 129 +variant = "CmpLtI32" +operation = "compare" +relation = "lt" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_CMP_EQ_I32" +family = "VOPC" +opcode = 130 +variant = "CmpEqI32" +operation = "compare" +relation = "eq" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_CMP_LE_I32" +family = "VOPC" +opcode = 131 +variant = "CmpLeI32" +operation = "compare" +relation = "le" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_CMP_GT_I32" +family = "VOPC" +opcode = 132 +variant = "CmpGtI32" +operation = "compare" +relation = "gt" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_CMP_NE_I32" +family = "VOPC" +opcode = 133 +variant = "CmpNeI32" +operation = "compare" +relation = "lg" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_CMP_GE_I32" +family = "VOPC" +opcode = 134 +variant = "CmpGeI32" +operation = "compare" +relation = "ge" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_CMP_LT_U32" +family = "VOPC" +opcode = 193 +variant = "CmpLtU32" +operation = "compare" +relation = "lt" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_CMP_EQ_U32" +family = "VOPC" +opcode = 194 +variant = "CmpEqU32" +operation = "compare" +relation = "eq" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_CMP_LE_U32" +family = "VOPC" +opcode = 195 +variant = "CmpLeU32" +operation = "compare" +relation = "le" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_CMP_GT_U32" +family = "VOPC" +opcode = 196 +variant = "CmpGtU32" +operation = "compare" +relation = "gt" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_CMP_NE_U32" +family = "VOPC" +opcode = 197 +variant = "CmpNeU32" +operation = "compare" +relation = "lg" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_CMP_GE_U32" +family = "VOPC" +opcode = 198 +variant = "CmpGeU32" +operation = "compare" +relation = "ge" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +# ---- VOPC F and T compares (guide Table 59 offsets 0 and 7) ---- +# The test is false or true for every lane, so VCC_LO := 0 or the EXEC lanes +# that exist. Sources are still decoded and checked as for the other compares +# (docs/shaders/vector-compare.md section 5). + +[[form]] +name = "V_CMP_F_I32" +family = "VOPC" +opcode = 128 +variant = "CmpFI32" +operation = "compare" +relation = "f" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_CMP_T_I32" +family = "VOPC" +opcode = 135 +variant = "CmpTI32" +operation = "compare" +relation = "t" +signedness = "signed" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_CMP_F_U32" +family = "VOPC" +opcode = 192 +variant = "CmpFU32" +operation = "compare" +relation = "f" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_CMP_T_U32" +family = "VOPC" +opcode = 199 +variant = "CmpTU32" +operation = "compare" +relation = "t" +signedness = "unsigned" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "lane_mask" +exec = "unchanged" +wave = "wave32" +operands = "vopc_vcc" +spec = [ + { document = "guide", section = "12.9", page = 150 }, + { document = "guide", section = "3.9", page = 19 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] diff --git a/docs/shaders/semantic-registry.md b/docs/shaders/semantic-registry.md index dd706b1..9cb63d4 100644 --- a/docs/shaders/semantic-registry.md +++ b/docs/shaders/semantic-registry.md @@ -12,7 +12,8 @@ The registry covers the nine SOP2 forms listed in [SOP2 scalar ALU](scalar-alu.m | File | Role | | --- | --- | -| `crates/isa/semantics/rdna2.toml` | The registry. Data only: every value comes from a closed vocabulary. | +| `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/.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/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. | @@ -20,9 +21,23 @@ The registry covers the nine SOP2 forms listed in [SOP2 scalar ALU](scalar-alu.m | `crates/isa/src/primitive.rs` | The shared integer primitives that the generated `evaluate` calls. | | `tests/semantics_generator/` | Unit tests for the generator. | +## Family files + +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 +families therefore never edits the same registry file. To add a family, create +`rdna2/.toml` and append it to `include`; the generated order (and so +the generated file) changes only where the new file is placed. + ## Fields -The top of the file holds: +The root file holds: - `schema`: must be `1`. - `architecture`: must be `"gfx1030"`. diff --git a/docs/shaders/vector-compare.md b/docs/shaders/vector-compare.md index 56dd577..0244694 100644 --- a/docs/shaders/vector-compare.md +++ b/docs/shaders/vector-compare.md @@ -58,7 +58,7 @@ The 32-bit VOPC encoding (bits 31:25 = 0b0111110), no SDWA or DPP: `_i32` compares the 32-bit two's-complement values, `_u32` the unsigned values. The forms are declared in the semantic registry -(`crates/isa/semantics/rdna2.toml`, operand rule `vopc_vcc`); the decoder +(`crates/isa/semantics/rdna2/vopc.toml`, operand rule `vopc_vcc`); the decoder dispatches them from the generated `VectorCompareOp`. Operand order matters (S0 is SRC0): lt with swapped operands is gt. diff --git a/scripts/audit/semantic_coverage.py b/scripts/audit/semantic_coverage.py index 6a6a614..f9712f3 100644 --- a/scripts/audit/semantic_coverage.py +++ b/scripts/audit/semantic_coverage.py @@ -142,6 +142,23 @@ def parse_generated(source): raise ValueError(f"{GENERATED}: unterminated FORM_IDS") +def load_registry(path): + """The root registry with its `include`d family files merged in order. + + Only the merge is done here; crates/isa/generate_semantics.py validates + which family each file may hold. + """ + 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", [])) + return registry + + def read_declarations(registry, identified): if type(registry.get("schema")) is not int or registry["schema"] != 1: raise ValueError(f"{REGISTRY}: expected schema 1") @@ -294,7 +311,7 @@ def main(): args = parser.parse_args() try: identified = load_snapshot(ROOT) - registry = tomllib.loads((ROOT / REGISTRY).read_text(encoding="utf-8")) + registry = load_registry(ROOT / REGISTRY) 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")) diff --git a/scripts/qa/rdna2_plan.py b/scripts/qa/rdna2_plan.py index 0e75ed1..f648882 100644 --- a/scripts/qa/rdna2_plan.py +++ b/scripts/qa/rdna2_plan.py @@ -67,6 +67,7 @@ class Inventory: # Planning does not claim or edit these paths. DEFAULT_PERMITTED_FILES = ( "crates/isa/semantics/rdna2.toml", + "crates/isa/semantics/rdna2/", "crates/isa/src/semantics_gen.rs", "crates/decoder/src/lib.rs", "crates/shader/", @@ -87,7 +88,8 @@ DEFAULT_ACCEPTANCE = ( def load_inventories(root: Path) -> dict[str, Any]: sc = _load_coverage_module(root) identified = sc["load_snapshot"](root) - registry = tomllib.loads((root / sc["REGISTRY"]).read_text(encoding="utf-8")) + # The root registry includes per-family files; merge them as the coverage report does. + registry = sc["load_registry"](root / sc["REGISTRY"]) decoder = sc["parse_decoder"]((root / sc["DECODER"]).read_text(encoding="utf-8")) generated = sc["parse_generated"]((root / sc["GENERATED"]).read_text(encoding="utf-8")) decoder_forms = set(decoder) | set(generated) diff --git a/tests/semantics_generator/test_generate_semantics.py b/tests/semantics_generator/test_generate_semantics.py index e7c1b5c..58be8d2 100644 --- a/tests/semantics_generator/test_generate_semantics.py +++ b/tests/semantics_generator/test_generate_semantics.py @@ -10,6 +10,7 @@ snapshot are only read, never edited. Run from the repository root: import copy import importlib.util +import shutil import subprocess import sys import tempfile @@ -1037,6 +1038,79 @@ class Render(unittest.TestCase): self.assertEqual(text, gen.RUST.read_text(encoding="utf-8")) +class LoadRegistry(unittest.TestCase): + """The root file plus its per-family files merge into one registry.""" + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.dir = Path(self.tmp.name) + (self.dir / "rdna2").mkdir() + + def write(self, root_extra, files): + (self.dir / "rdna2.toml").write_text( + "schema = 1\n" + root_extra, encoding="utf-8" + ) + for name, text in files.items(): + (self.dir / "rdna2" / name).write_text(text, encoding="utf-8") + return self.dir / "rdna2.toml" + + RULE = '[operand_rules.{name}]\nfamily = "{family}"\n' + FORM = '[[form]]\nname = "{name}"\nfamily = "{family}"\n' + + def fails(self, root, fragment): + with self.assertRaises(gen.RegistryError) as raised: + gen.load_registry(root) + self.assertIn(fragment, str(raised.exception)) + + def test_the_real_split_registry_equals_one_concatenated_file(self): + registry = gen.load_registry() + self.assertNotIn("include", registry) + families = [form["family"] for form in registry["form"]] + # Each family is one contiguous run, in include order. + runs = [family for index, family in enumerate(families) if index == 0 or families[index - 1] != family] + self.assertEqual(len(runs), len(set(runs))) + for name, rule in registry["operand_rules"].items(): + self.assertIn(rule["family"], runs, name) + + def test_merges_family_files_in_include_order(self): + root = self.write('include = ["rdna2/vop2.toml", "rdna2/sop2.toml"]\n', { + "vop2.toml": self.RULE.format(name="v", family="VOP2") + self.FORM.format(name="B", family="VOP2"), + "sop2.toml": self.FORM.format(name="A", family="SOP2") + self.FORM.format(name="C", family="SOP2"), + }) + registry = gen.load_registry(root) + self.assertEqual([form["name"] for form in registry["form"]], ["B", "A", "C"]) + self.assertEqual(list(registry["operand_rules"]), ["v"]) + + def test_rejects_a_form_of_another_family(self): + root = self.write('include = ["rdna2/sop2.toml"]\n', { + "sop2.toml": self.FORM.format(name="V_X", family="VOP2"), + }) + self.fails(root, "rdna2/sop2.toml: form V_X is not a SOP2 form") + + def test_rejects_a_rule_of_another_family(self): + root = self.write('include = ["rdna2/sop2.toml"]\n', { + "sop2.toml": self.RULE.format(name="r", family="SOPC"), + }) + self.fails(root, "rdna2/sop2.toml: operand rule r is not a SOP2 rule") + + def test_rejects_a_rule_declared_in_two_files(self): + root = self.write('include = ["rdna2/sop2.toml", "rdna2/sop1.toml"]\n', { + "sop2.toml": self.RULE.format(name="r", family="SOP2"), + "sop1.toml": self.RULE.format(name="r", family="SOP1"), + }) + self.fails(root, "rdna2/sop1.toml: operand rule r is declared twice") + + def test_rejects_root_keys_in_a_family_file(self): + 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_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": ""}) + self.fails(root, "a family file is included twice") + + class CommandLine(unittest.TestCase): def run_cli(self, *arguments): return subprocess.run( @@ -1072,6 +1146,7 @@ class CommandLine(unittest.TestCase): def test_invalid_registry_fails_every_mode_without_writing(self): bad = self.dir / "rdna2.toml" + shutil.copytree(gen.REGISTRY.parent / "rdna2", self.dir / "rdna2") 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" From 516976fb9f599177ce1ec55f66aae65fb23000ba Mon Sep 17 00:00:00 2001 From: elforeign <324243036+elforeign@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:53:50 -0600 Subject: [PATCH 07/15] isa, decoder, shader: registry encoding variants; v_add_nc_u32_e64 as the first (#215) An [[encoding_variant]] re-encodes a declared form in another family: it names the form, the family, its opcode there and that encoding's operand rule, and inherits the rest. The XML check runs on the inherited declaration, and the generator rejects variants of undeclared forms, in the form's own family, duplicates, rules that cannot encode the form and forms that use a variant-only rule. It emits from__word and _assembly_name on the base enum and one FORMS row per variant. rdna2/vop3.toml declares the vop3_vgpr2 rule (the subset the hand-written decoder accepted: VGPR sources, no modifiers, unused SRC2) and the VOP3 encoding of V_ADD_NC_U32. The decoder dispatches it through VectorAluOp::from_vop3_word into Instruction::VectorAluVop3, which replaces AddNoCarryU32; the shader lowers it through the VOP2 form's template and still admits only v_add_nc_u32_e64 inside a runtime s_cbranch_vccz region. Goldens, known answers and the LLVM oracle are unchanged. Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com> --- CHANGELOG.md | 1 + crates/decoder/src/lib.rs | 28 +-- crates/decoder/tests/gfx1030.rs | 15 +- crates/isa/generate_semantics.py | 159 +++++++++++++++++- crates/isa/semantics/rdna2.toml | 1 + crates/isa/semantics/rdna2/vop3.toml | 35 ++++ crates/isa/src/lib.rs | 18 +- crates/isa/src/semantics.rs | 4 + crates/isa/src/semantics_gen.rs | 52 +++++- crates/isa/tests/semantics.rs | 33 ++++ crates/shader/src/lib.rs | 35 +++- docs/shaders/semantic-coverage.md | 5 +- docs/shaders/semantic-registry.md | 33 ++++ scripts/audit/semantic_coverage.py | 9 +- .../test_generate_semantics.py | 109 +++++++++++- 15 files changed, 496 insertions(+), 41 deletions(-) create mode 100644 crates/isa/semantics/rdna2/vop3.toml diff --git a/CHANGELOG.md b/CHANGELOG.md index 4efdfe2..bf4468f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,6 +31,7 @@ remains unsupported. - Recorded agent-queue live smoke evidence for issue #180 against the disposable private repository `ranveersoni98/xenora-agent-queue-smoke`, including claim grant, overlap refusal, release, not-ready denial, progress renew and a successful audit dispatch after fixing comment-only `apply_actions` and audit permissions/argparse issues. - Added twelve gfx1030 VOP2 vector integer forms through the semantic registry: `v_mul_i32_i24`, `v_mul_hi_i32_i24`, `v_mul_u32_u24`, `v_mul_hi_u32_u24`, `v_min_i32`, `v_max_i32`, `v_min_u32`, `v_max_u32`, `v_xnor_b32`, `v_add_nc_u32`, `v_sub_nc_u32` and `v_subrev_nc_u32` (AMD guide section 12.7), with SRC0 a VGPR, an SGPR, `vcc_lo`, an inline integer or a literal. The registry gained a `vop2_vgpr` operand rule, the vector operations `mul24` and `mul_hi24`, a declared `source_order` for SUBREV, and a per-lane `VectorBinary` that selects one reusable MSL template per operation. Both reference interpreters, written separately from the guide, run the same twelve forms and are checked against 2,040 guide-derived cases, each asserting every lane of a 7-, 32- or 45-lane dispatch (partial, empty and full EXEC), on both CPU interpreters and on native Metal; 575 rejected programs are refused by both interpreters and by the compiler at the same word. A new LLVM-assembled fixture computes every lane from its own input. Part of #215. - Moved the twelve Wave32 VOPC integer compares from #239 into the semantic registry (operand rule `vopc_vcc`, `vcc = "lane_mask"`, `wave = "wave32"`) with no behaviour change, and added `v_cmp_f_i32`, `v_cmp_t_i32`, `v_cmp_f_u32` and `v_cmp_t_u32` as registry forms under the same Wave32 VCC/EXEC contract, verified by an independent guide-derived oracle (`tests/validation/tests/vopc_f_t.rs`), a new LLVM-assembled fixture and native Metal (part of #215). `v_cmpx_*`, the VOP3 encoding and Wave64 stay unsupported. +- Split the gfx1030 semantic registry into one file per encoding family (`crates/isa/semantics/rdna2/{sop2,sopc,sop1,vop2,vopc,vop3}.toml`, included in order by `rdna2.toml`; the split left the generated tables byte-identical), and added registry encoding variants: another encoding of a declared form is pure data. `v_add_nc_u32_e64` is now the first VOP3 variant of `v_add_nc_u32` (operand rule `vop3_vgpr2`), replacing its hand-written decoder and instruction with no behaviour change (part of #215). - Added sixteen gfx1030 SOP2 integer forms through the semantic registry: `s_min_i32`, `s_min_u32`, `s_max_i32`, `s_max_u32`, `s_cselect_b32`, `s_bfm_b32`, `s_mul_i32`, `s_bfe_u32`, `s_bfe_i32`, `s_absdiff_i32`, `s_lshl1_add_u32` to `s_lshl4_add_u32`, `s_mul_hi_u32` and `s_mul_hi_i32` (AMD guide section 12.1). Min and max set SCC from the strict compare (a tie gives S1 and SCC 0), `s_cselect_b32` reads SCC and is refused when SCC is unset, and BFM, MUL, MUL_HI and CSELECT leave SCC unchanged. The registry gained these primitives, a `selected_src0` SCC effect, the select's SCC input and a declared `shift_amount` for the shift-and-add forms; `ScalarAluOp::evaluate` now returns an optional SCC. Both reference interpreters, written separately from the guide, run the same sixteen forms and are checked against 21,070 guide-derived cases on both CPU interpreters and on native Metal; 597 rejected programs are refused by both interpreters and by the compiler. A new LLVM-assembled fixture covers all sixteen. Part of #215. - Added audio PCM streaming and sandboxed virtual filesystem (VFS) integration to the native application runtime (Gate 6, #284). The C interface gains audio management functions (`xenora_session_audio_init`, `xenora_session_audio_submit`, `xenora_session_audio_read`, `xenora_session_audio_status`, `xenora_session_audio_set_volume`) and virtual filesystem functions (`xenora_session_vfs_set_root`, `xenora_session_vfs_open`, `xenora_session_vfs_read`, `xenora_session_vfs_seek`, `xenora_session_vfs_close`, `xenora_session_run_audio_vfs_fixture`). The audio subsystem implements a bounded ring buffer supporting configurable sample rates, channel configurations, PCM formats (S16LE, F32LE), volume attenuation, mute, and buffer underrun tracking. The virtual filesystem operates within an explicitly configured, sandboxed directory root (`fixtures/assets`), strictly rejecting path traversal attempts (`..`, absolute paths, null bytes) and invalid or stale handles, while supporting sequential and seekable file reads (`XENORA_SEEK_SET`, `XENORA_SEEK_CUR`, `XENORA_SEEK_END`). An original PE fixture (`fixtures/pe/audio_vfs.exe`, generated by `fixtures/pe/audio_vfs.py` using only the supported ARM64 DBT instruction subset) opens `asset.bin` (generated by `fixtures/assets/generate.py`), loads a 2x2 RGBA texture and 256 PCM audio samples via VFS, initializes audio, submits the PCM audio queue, and renders the loaded texture on Metal. Verified with unit tests, four Metal acceptance tests in `crates/ffi/tests/audio_vfs.rs`, UI controls and a `--smoke-audio-vfs` CLI in `Xenora.app`. - Added persistent GPU resources, dynamic texture updates, and resource retirement to the native application (Gate 5, #279). The C interface gains `xenora_resource`, resource types (`XENORA_RESOURCE_TYPE_*`), `xenora_session_create_texture`, `xenora_session_update_texture`, `xenora_session_destroy_resource`, `xenora_session_resource_info`, `xenora_session_render_textured`, and `xenora_session_run_textured_fixture`. Persistent GPU resources (textures) are explicitly allocated and owned by the execution session, surviving across execution slices without re-allocation. Dynamic texture subregion updates modify GPU texture contents in-place on native Metal. Resource retirement is completion-aware: destroying a resource held by in-flight GPU execution marks it retired and safely defers destruction until in-flight work completes, while rejecting subsequent caller queries with typed error codes. An original PE fixture (`fixtures/pe/textured.exe`, generated by `fixtures/pe/textured.py` using only the supported ARM64 DBT instruction subset) creates a persistent 2x2 texture via `xenora.dll!texture_create`, renders frame 0, updates pixels via `xenora.dll!texture_update`, renders frame 1, and retires the resource via `xenora.dll!texture_destroy`. Xenora.app gains "Run textured fixture" controls and `--smoke-resources`. Six GPU acceptance tests with Metal validation verify persistent texture lifecycle across multiple frames, dynamic 1x1 and 2x1 subregion updates on native Metal, completion-aware deferred retirement, rejection of invalid/stale/double-destroyed handles, slot reuse across 200 cycles without leaking, and full guest fixture execution. Wired acceptance tests into `scripts/test-gpu.sh`. diff --git a/crates/decoder/src/lib.rs b/crates/decoder/src/lib.rs index d259189..f5e1014 100644 --- a/crates/decoder/src/lib.rs +++ b/crates/decoder/src/lib.rs @@ -9,8 +9,8 @@ pub use xenora_isa::{ use xenora_isa::{ BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_BRANCH, S_CBRANCH_EXECZ, S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_ENDPGM, S_MOV_B32, S_WAITCNT, S_WAITCNT_VSCNT, V_ADD_F32, - V_ADD_NC_U32, V_AND_B32, V_ASHRREV_I32, 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, VCC_LO, + V_AND_B32, V_ASHRREV_I32, 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, VCC_LO, }; use xenora_isa::meta::EncodingFamily; @@ -40,7 +40,7 @@ const fn concat_forms() -> [(&'static str, EncodingFamily); N] { } /// Decoded forms not yet described by the semantic registry. -const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 24] = [ +const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 23] = [ ("BUFFER_LOAD_DWORD", EncodingFamily::Mubuf), ("BUFFER_STORE_DWORD", EncodingFamily::Mubuf), ("EXP", EncodingFamily::Exp), @@ -54,7 +54,6 @@ const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 24] = [ ("S_WAITCNT", EncodingFamily::Sopp), ("S_WAITCNT_VSCNT", EncodingFamily::Sopk), ("V_ADD_F32", EncodingFamily::Vop2), - ("V_ADD_NC_U32", EncodingFamily::Vop3), ("V_AND_B32", EncodingFamily::Vop2), ("V_ASHRREV_I32", EncodingFamily::Vop2), ("V_INTERP_P1_F32", EncodingFamily::Vintrp), @@ -327,10 +326,9 @@ 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 V_ADD_NC_U32.matches(first) { - let len = V_ADD_NC_U32.byte_len(); - let second = word(bytes, len)?; - return Ok((add_u32(first, second)?, len)); + if let Some(op) = VectorAluOp::from_vop3_word(first) { + let second = word(bytes, 8)?; + return Ok((vop3_vgpr2(op, first, second)?, 8)); } if S_MOV_B32.matches(first) { let dst = ((first >> 16) & 0x7f) as u8; @@ -747,18 +745,22 @@ fn move_b32(first: u32, bytes: &[u8]) -> Result<(Instruction, u8), DecodeErrorKi Ok((Instruction::MoveB32 { dst, src }, len)) } -fn add_u32(first: u32, second: u32) -> Result { +/// Operand rule `vop3_vgpr2`: VDST in bits 0-7 of the first word, SRC0 and SRC1 +/// 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 { let src0 = second & 0x1ff; let src1 = (second >> 9) & 0x1ff; - // All output and input modifiers are clear. The unused third source uses - // the gfx1030 assembler's inline-zero operand encoding. if first & 0xff00 != 0 || second >> 18 != 128 || src0 < 256 || src1 < 256 { return Err(unsupported( - "v_add_nc_u32_e64", + op.vop3_assembly_name() + .expect("VOP3 dispatch selects only declared variants"), "expected two VGPR sources and no modifiers", )); } - Ok(Instruction::AddNoCarryU32 { + Ok(Instruction::VectorAluVop3 { + op, dst: first as u8, src0: src0 as u8, src1: src1 as u8, diff --git a/crates/decoder/tests/gfx1030.rs b/crates/decoder/tests/gfx1030.rs index d9c3f97..de9ea49 100644 --- a/crates/decoder/tests/gfx1030.rs +++ b/crates/decoder/tests/gfx1030.rs @@ -43,7 +43,8 @@ fn decodes_each_fixture_instruction_with_offset_and_length() { ( 20, 8, - Instruction::AddNoCarryU32 { + Instruction::VectorAluVop3 { + op: VectorAluOp::AddNcU32, dst: 1, src0: 1, src1: 2, @@ -373,7 +374,14 @@ fn reference_op(instruction: Instruction) -> Op { reference_scalar(src0), reference_scalar(src1), ), - Instruction::AddNoCarryU32 { dst, src0, src1 } => Op::Add(dst, src0, src1), + // The reference's VOP3 add; it is the only VOP3 variant so far. + Instruction::VectorAluVop3 { + op: VectorAluOp::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 { @@ -998,7 +1006,8 @@ fn accepts_scalar_destination_105_and_vgpr_zero_add_sources() { let bytes: Vec<_> = words.iter().flat_map(|word| word.to_le_bytes()).collect(); assert_eq!( decode(Architecture::Gfx1030, &bytes).unwrap()[0].instruction, - Instruction::AddNoCarryU32 { + Instruction::VectorAluVop3 { + op: VectorAluOp::AddNcU32, dst: 1, src0: 0, src1: 0 diff --git a/crates/isa/generate_semantics.py b/crates/isa/generate_semantics.py index 7997782..d9604db 100755 --- a/crates/isa/generate_semantics.py +++ b/crates/isa/generate_semantics.py @@ -37,7 +37,17 @@ 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"} +TOP_KEYS = { + "schema", "architecture", "source_sha256", "documents", "operand_rules", "form", + "encoding_variant", +} +# An encoding variant is another encoding of a form already in the registry (for +# example the VOP3 `_e64` encoding of a VOP2 form): pure data that names the base +# form, the encoding family, its opcode there and the operand rule of that +# encoding. It inherits the base form's operation, signedness and effects. +VARIANT_KEYS = {"of", "family", "opcode", "operands", "spec", "verify"} +# The assembler suffix LLVM prints for a variant's encoding family. +ASSEMBLY_SUFFIX = {"VOP3": "_e64"} OPERATIONS = { "add": "Add", "sub": "Sub", "and": "And", "or": "Or", "xor": "Xor", @@ -222,7 +232,9 @@ UNSUPPORTED_COMBOS = { } # Every combo name a rule may list (VOP2 also names vcc_hi and NULL sources, # which SOP2 groups under src_vcc and src_special). -ALL_COMBOS = UNSUPPORTED_COMBOS | {"src_vcc_hi", "src_null"} +# VOP3 rules also name source classes and encoding fields they refuse. +VOP3_COMBOS = {"src_sgpr", "src_inline", "src_literal", "modifiers", "src2"} +ALL_COMBOS = UNSUPPORTED_COMBOS | {"src_vcc_hi", "src_null"} | VOP3_COMBOS OPERAND_RULES = { "sop2_sgpr": { "rust": "Sop2Sgpr", @@ -287,6 +299,28 @@ OPERAND_RULES = { }, "kind": "vector_compare", }, + "vop3_vgpr2": { + "rust": "Vop3Vgpr2", + "enum": "VectorAluOp", + "shape": { + "family": "VOP3", + "dst": {"field": "VDST", "class": "vgpr", "min": 0, "max": 255}, + "src": [ + {"field": "SRC0", "class": "vgpr"}, + {"field": "SRC1", "class": "vgpr"}, + ], + "max_literals": 0, + }, + # Two VGPR sources only, with ABS, OP_SEL, CLAMP, OMOD and NEG clear and + # SRC2 the assembler's unused inline zero; the decoder rejects the rest. + "unsupported": { + "src_sgpr", "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_null", "src_inline", + "src_float_inline", "src_special", "src_literal", "modifiers", "src2", + }, + "kind": "vector_vop3", + # Only encoding variants of forms whose rule has this kind may use it. + "variant_of": "vector", + }, "vop2_vgpr": { "rust": "Vop2Vgpr", "enum": "VectorAluOp", @@ -321,7 +355,7 @@ class RegistryError(ValueError): # Keys a family file may hold; everything else lives in the root file. -FAMILY_FILE_KEYS = {"operand_rules", "form"} +FAMILY_FILE_KEYS = {"operand_rules", "form", "encoding_variant"} def load_registry(path=REGISTRY): @@ -364,6 +398,11 @@ def load_registry(path=REGISTRY): label = form.get("name", f"form #{index}") if isinstance(form, dict) else index raise RegistryError(f"{include}: form {label} is not a {family} form") forms.append(form) + for index, variant in enumerate(part.get("encoding_variant", [])): + if not isinstance(variant, dict) or variant.get("family") != family: + label = variant.get("of", f"#{index}") if isinstance(variant, dict) else index + raise RegistryError(f"{include}: encoding variant {label} is not a {family} encoding") + registry.setdefault("encoding_variant", []).append(variant) return registry @@ -661,6 +700,8 @@ def validate(registry, snapshot): 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 _implemented_rule(form) and "variant_of" in _implemented_rule(form): + errors.append(f"{label}: operand rule {form['operands']} is only for encoding variants") if rule is None: errors.append(f"{label}: unknown operand rule {form['operands']!r}") elif rule.get("family") != form["family"]: @@ -682,9 +723,68 @@ def validate(registry, snapshot): if len(set(verify)) != len(verify): errors.append(f"{label}: duplicate verification requirement") _check_xml(form, rule, snapshot, errors) + _check_variants(registry, rules, documents, snapshot, seen, errors) return errors +def variant_row(registry, variant): + """The base form re-encoded: its declaration with the variant's identity.""" + base = next(form for form in registry["form"] if form.get("name") == variant["of"]) + return dict( + base, family=variant["family"], opcode=variant["opcode"], operands=variant["operands"], + spec=variant["spec"], verify=variant["verify"], + ) + + +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')})" + missing = sorted(VARIANT_KEYS - set(variant)) + extra = sorted(set(variant) - VARIANT_KEYS) + if missing: + errors.append(f"{label}: incomplete encoding variant, missing {missing}") + if extra: + errors.append(f"{label}: unknown keys {extra}") + if missing: + continue + base = forms.get(variant["of"]) + if base is None: + errors.append(f"{label}: encoding variant of an undeclared form") + continue + if type(variant["opcode"]) is not int or not 0 <= variant["opcode"] <= U16_MAX: + errors.append(f"{label}: invalid opcode") + continue + if variant["family"] == base.get("family"): + errors.append(f"{label}: an encoding variant must use another family than its form") + identity = (variant["of"], variant["family"]) + if identity in identities: + errors.append(f"{label}: duplicate encoding of {variant['of']}") + identities.add(identity) + if (variant["family"], variant["opcode"]) in seen["opcode"]: + errors.append(f"{label}: duplicate opcode {(variant['family'], variant['opcode'])}") + seen["opcode"].add((variant["family"], variant["opcode"])) + implemented = OPERAND_RULES.get(variant["operands"]) if isinstance(variant["operands"], str) else None + rule = rules.get(variant["operands"]) + if rule is None or implemented is None: + errors.append(f"{label}: unknown operand rule {variant['operands']!r}") + continue + if rule.get("family") != variant["family"]: + errors.append(f"{label}: operand rule {variant['operands']} is for {rule.get('family')}") + if implemented.get("variant_of") != _rule_kind(base) or implemented["enum"] != _rule_enum(base): + errors.append( + f"{label}: operand rule {variant['operands']} cannot encode a {_rule_kind(base)} form" + ) + _check_spec(label, variant["spec"], documents, errors) + verify = variant["verify"] + if not verify or any(item not in EVIDENCE for item in verify) or len(set(verify)) != len(verify): + errors.append(f"{label}: invalid verification requirements {verify}") + # 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) + + def _implemented_rule(form): operands = form.get("operands") return OPERAND_RULES.get(operands) if isinstance(operands, str) else None @@ -743,9 +843,15 @@ def render(registry, snapshot): 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) + variants = registry.get("encoding_variant", []) + 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) + # Encoding variants follow the forms, as rows of their own. + forms = forms + [variant_row(registry, variant) for variant in variants] out += [ "", - "/// Identity of every registry form, in registry order.", + "/// Identity of every registry form and encoding variant, in registry order.", f"pub const FORM_IDS: [(&str, EncodingFamily); {len(forms)}] = [", ] for form in forms: @@ -791,6 +897,51 @@ 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"] + family = variants[0]["family"] + encoding = snapshot["encodings"][_family_encoding(family)] + (offset, size), = dict((name, ranges) for name, ranges in encoding["fields"])["OP"] + op_mask = ((1 << size) - 1) << offset + fixed_mask = encoding["identifier_mask"] & ~op_mask + 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"]) + 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 {{", + f" if word & 0x{fixed_mask:09_x} != 0x{fixed_bits:09_x} {{", + " return None;", + " }", + f" match (word >> {offset}) & 0x{(1 << size) - 1:x} {{", + ] + out += [f" {row['opcode']} => Some(Self::{variant_of[row['of']]})," for row in rows] + out += [ + " _ => None,", + " }", + " }", + "", + f" /// Assembler name of the {family} encoding, as LLVM prints it, if declared.", + f" pub const fn {lower}_assembly_name(self) -> Option<&'static str> {{", + " match self {", + ] + out += [ + f" Self::{variant_of[row['of']]} => " + f"Some(\"{row['of'].lower()}{ASSEMBLY_SUFFIX[family]}\")," + for row in variants + ] + out += [" #[allow(unreachable_patterns)]", " _ => None,", " }", " }", "}"] + return out + + def _render_enum(rule_name, forms, snapshot, positions): enum = OPERAND_RULES[rule_name]["enum"] kind = OPERAND_RULES[rule_name]["kind"] diff --git a/crates/isa/semantics/rdna2.toml b/crates/isa/semantics/rdna2.toml index bfe7a4f..cf21825 100644 --- a/crates/isa/semantics/rdna2.toml +++ b/crates/isa/semantics/rdna2.toml @@ -22,6 +22,7 @@ include = [ "rdna2/sop1.toml", "rdna2/vop2.toml", "rdna2/vopc.toml", + "rdna2/vop3.toml", ] # Named public documents that spec references point at. diff --git a/crates/isa/semantics/rdna2/vop3.toml b/crates/isa/semantics/rdna2/vop3.toml new file mode 100644 index 0000000..ecd1a6f --- /dev/null +++ b/crates/isa/semantics/rdna2/vop3.toml @@ -0,0 +1,35 @@ +# VOP3 encodings of the gfx1030 semantic registry; included by ../rdna2.toml. +# Data only; see the root file for the field meanings. + +# ---- VOP3 encoding variants of registry forms (#215) ---- +# An [[encoding_variant]] re-encodes a form declared in another family file: it +# names the form (`of`), this family, the XML opcode here and the operand rule +# of this encoding, and inherits everything else (operation, signedness, +# effects) from the form. The XML must agree with the inherited declaration. + +# Two VGPR sources, VGPR destination, no modifiers (ABS, OP_SEL, CLAMP, OMOD +# and NEG clear) and SRC2 the assembler's unused inline zero. This is the +# subset the decoder accepted for v_add_nc_u32_e64 before the registry. +[operand_rules.vop3_vgpr2] +family = "VOP3" +dst = { field = "VDST", class = "vgpr", min = 0, max = 255 } +src = [ + { field = "SRC0", class = "vgpr" }, + { field = "SRC1", class = "vgpr" }, +] +max_literals = 0 +unsupported = [ + "src_sgpr", "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_null", "src_inline", + "src_float_inline", "src_special", "src_literal", "modifiers", "src2", +] + +[[encoding_variant]] +of = "V_ADD_NC_U32" +family = "VOP3" +opcode = 293 +operands = "vop3_vgpr2" +spec = [ + { document = "guide", section = "12.12", page = 167 }, + { document = "guide", section = "12.7", page = 134 }, +] +verify = ["reference", "independent", "metal", "llvm_encoding"] diff --git a/crates/isa/src/lib.rs b/crates/isa/src/lib.rs index b5edab6..e55aa8f 100644 --- a/crates/isa/src/lib.rs +++ b/crates/isa/src/lib.rs @@ -154,8 +154,14 @@ pub enum Instruction { WaitStore, /// VOP1 unmodified 32-bit vector move. MoveB32 { dst: u8, src: VectorSource }, - /// VOP3 unsigned 32-bit addition with no carry or input/output modifiers. - AddNoCarryU32 { dst: u8, src0: u8, src1: u8 }, + /// VOP3 encoding of a registry VOP2 integer operation (operand rule + /// `vop3_vgpr2`): two VGPR sources and no input or output modifiers. + VectorAluVop3 { + op: VectorAluOp, + dst: u8, + src0: u8, + src1: u8, + }, /// SOP1 32-bit move to a normal SGPR or an EXEC/VCC half. ScalarMoveB32 { dst: u8, src: ScalarSource }, /// SOP1 32-bit unary integer operation writing a normal SGPR (s0-s105) and, @@ -271,7 +277,9 @@ impl Instruction { Self::WaitLoad => "s_waitcnt", Self::WaitStore => "s_waitcnt_vscnt", Self::MoveB32 { .. } => "v_mov_b32_e32", - Self::AddNoCarryU32 { .. } => "v_add_nc_u32_e64", + Self::VectorAluVop3 { op, .. } => op + .vop3_assembly_name() + .expect("decoded VOP3 variants have a VOP3 name"), Self::ScalarMoveB32 { .. } => "s_mov_b32", Self::ScalarUnary { op, .. } => op.mnemonic(), Self::ScalarAlu { op, .. } => op.mnemonic(), @@ -328,7 +336,9 @@ impl fmt::Display for Instruction { Self::WaitLoad => formatter.write_str(" vmcnt(0)"), Self::WaitStore => formatter.write_str(" null, 0"), Self::MoveB32 { dst, src } => write!(formatter, " v{dst}, {src}"), - Self::AddNoCarryU32 { dst, src0, src1 } + Self::VectorAluVop3 { + dst, src0, src1, .. + } | Self::VectorLshlrevB32 { dst, src0, src1 } | Self::VectorLshrrevB32 { dst, src0, src1 } | Self::VectorAshrrevI32 { dst, src0, src1 } diff --git a/crates/isa/src/semantics.rs b/crates/isa/src/semantics.rs index ff67cb6..3ef28a0 100644 --- a/crates/isa/src/semantics.rs +++ b/crates/isa/src/semantics.rs @@ -196,6 +196,10 @@ pub enum OperandRule { /// s0-s105, `vcc_lo`, an inline integer -16..64 or a literal word; VSRC1 is a /// VGPR. Everything else is rejected as unsupported. VopcVcc, + /// VOP3 encoding of a VOP2 vector form: VDST is v0-v255, SRC0 and SRC1 are + /// VGPRs, no input or output modifiers, SRC2 unused. Everything else is + /// rejected as unsupported. + Vop3Vgpr2, /// VOP2 vector: VDST is v0-v255; SRC0 is a VGPR, s0-s105, `vcc_lo`, an inline /// integer -16..64 or a literal word; VSRC1 is a VGPR. Everything else is /// rejected as unsupported. diff --git a/crates/isa/src/semantics_gen.rs b/crates/isa/src/semantics_gen.rs index 8e889fb..94e720b 100644 --- a/crates/isa/src/semantics_gen.rs +++ b/crates/isa/src/semantics_gen.rs @@ -1872,8 +1872,32 @@ impl VectorCompareOp { } } -/// Identity of every registry form, in registry order. -pub const FORM_IDS: [(&str, EncodingFamily); 84] = [ +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 { + if word & 0xfc00_0000 != 0xd400_0000 { + return None; + } + match (word >> 16) & 0x3ff { + 293 => Some(Self::AddNcU32), + _ => None, + } + } + + /// Assembler name of the VOP3 encoding, as LLVM prints it, if declared. + pub const fn vop3_assembly_name(self) -> Option<&'static str> { + match self { + Self::AddNcU32 => Some("v_add_nc_u32_e64"), + #[allow(unreachable_patterns)] + _ => None, + } + } +} + +/// Identity of every registry form and encoding variant, in registry order. +pub const FORM_IDS: [(&str, EncodingFamily); 85] = [ ("S_ADD_U32", EncodingFamily::Sop2), ("S_SUB_U32", EncodingFamily::Sop2), ("S_ADD_I32", EncodingFamily::Sop2), @@ -1958,10 +1982,11 @@ pub const FORM_IDS: [(&str, EncodingFamily); 84] = [ ("V_CMP_T_I32", EncodingFamily::Vopc), ("V_CMP_F_U32", EncodingFamily::Vopc), ("V_CMP_T_U32", EncodingFamily::Vopc), + ("V_ADD_NC_U32", EncodingFamily::Vop3), ]; /// One validated row per registry form, in registry order. -pub static FORMS: [FormSemantics; 84] = [ +pub static FORMS: [FormSemantics; 85] = [ FormSemantics { name: "S_ADD_U32", family: EncodingFamily::Sop2, @@ -3726,4 +3751,25 @@ pub static FORMS: [FormSemantics; 84] = [ spec: &[SpecRef { document: Document::Guide, section: "12.9", page: 150 }, SpecRef { document: Document::Guide, section: "3.9", page: 19 }], verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], }, + FormSemantics { + name: "V_ADD_NC_U32", + family: EncodingFamily::Vop3, + opcode: 293, + operation: Operation::Add, + signedness: Signedness::Unsigned, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: None, + scc: SccEffect::Unchanged, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::Vop3Vgpr2, + spec: &[SpecRef { document: Document::Guide, section: "12.12", page: 167 }, SpecRef { document: Document::Guide, section: "12.7", page: 134 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, ]; diff --git a/crates/isa/tests/semantics.rs b/crates/isa/tests/semantics.rs index 895b7ff..c1aa420 100644 --- a/crates/isa/tests/semantics.rs +++ b/crates/isa/tests/semantics.rs @@ -160,3 +160,36 @@ fn vector_compare_dispatch_selects_exactly_the_registry_vopc_forms() { VectorCompareOp::from_word(word).map(|op| op.semantics().name) }); } + +#[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(); + // The variant inherits the base declaration; only identity and the + // operand rule differ. + assert_eq!( + ( + base.operation, + base.signedness, + base.scc, + base.vcc, + base.exec + ), + (row.operation, row.signedness, row.scc, row.vcc, row.exec) + ); + assert_eq!( + op.vop3_assembly_name(), + Some(format!("{}_e64", op.mnemonic()).as_str()) + ); + } + dispatch_selects_exactly(EncodingFamily::Vop3, |word| { + VectorAluOp::from_vop3_word(word).map(|op| op.semantics().name) + }); +} diff --git a/crates/shader/src/lib.rs b/crates/shader/src/lib.rs index 3eae65c..c7ee8a8 100644 --- a/crates/shader/src/lib.rs +++ b/crates/shader/src/lib.rs @@ -9,8 +9,8 @@ pub use graphics::{PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics}; pub use xenora_decoder::Architecture; use xenora_decoder::{ - DecodeError, DecodedInstruction, Instruction, ScalarSource, VectorBinary, VectorCompareOp, - VectorSource, + DecodeError, DecodedInstruction, Instruction, ScalarSource, VectorAluOp, VectorBinary, + VectorCompareOp, VectorSource, }; /// SGPR index of `vcc_lo`. @@ -215,7 +215,6 @@ fn compare_expression(op: VectorCompareOp, left: &str, right: &str) -> String { #[derive(Clone, Copy)] enum Binary { - Add, ShiftLeft, ShiftRight, ArithmeticShiftRight, @@ -224,14 +223,14 @@ enum Binary { Xor, FloatAdd, FloatMul, - /// A registry VOP2 integer operation, lowered by its typed template. + /// A registry VOP2 integer operation (or its VOP3 encoding), lowered by its + /// typed template. Vector(VectorBinary), } impl Binary { fn operator(self) -> (&'static str, &'static str) { match self { - Self::Add => ("add.u32", "+"), Self::ShiftLeft => ("lshl.b32", "<<"), Self::ShiftRight => ("lshr.b32", ">>"), Self::ArithmeticShiftRight => ("ashr.i32", ">>"), @@ -684,7 +683,12 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result Result Result { - (Some(dst), Op::Binary(Binary::Add, read(src0)?, read(src1)?)) + Instruction::VectorAluVop3 { + op, + dst, + src0, + src1, + } => { + let (left, right) = if op.swaps_sources() { + (read(src1)?, read(src0)?) + } else { + (read(src0)?, read(src1)?) + }; + ( + Some(dst), + Op::Binary(Binary::Vector(op.lowering()), left, right), + ) } Instruction::VectorLshlrevB32 { dst, src0, src1 } => ( Some(dst), diff --git a/docs/shaders/semantic-coverage.md b/docs/shaders/semantic-coverage.md index 04f437a..d759c40 100644 --- a/docs/shaders/semantic-coverage.md +++ b/docs/shaders/semantic-coverage.md @@ -32,11 +32,11 @@ acceptance remain outside the verified count. All results concern synthetic fixt | VINTRP | 3 | 0 | 0 | 2 | 0 | 0 | 0 | 0 | 0 | | VOP1 | 81 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 | | VOP2 | 47 | 20 | 12 | 20 | 20 | 20 | 7 | 7 | 7 | -| VOP3 | 416 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 | +| VOP3 | 416 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 12 | | VOP3P | 29 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | | VOP3SDST | 10 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | | VOPC | 190 | 16 | 16 | 16 | 16 | 16 | 0 | 0 | 7 | -| **Total** | 1465 | 104 | 84 | 108 | 104 | 104 | 18 | 18 | 44 | +| **Total** | 1465 | 104 | 85 | 108 | 104 | 104 | 18 | 18 | 56 | ## Unsupported operand variants @@ -48,4 +48,5 @@ The table counts distinct variant names per family across registry operand rules | 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` | | SOPC | `sopc_scalar` | `src_exec`, `src_float_inline`, `src_m0`, `src_special`, `src_ttmp`, `src_vcc`, `two_literals` | | VOP2 | `vop2_vgpr` | `src_exec`, `src_float_inline`, `src_m0`, `src_null`, `src_special`, `src_ttmp`, `src_vcc_hi` | +| VOP3 | `vop3_vgpr2` | `modifiers`, `src2`, `src_exec`, `src_float_inline`, `src_inline`, `src_literal`, `src_m0`, `src_null`, `src_sgpr`, `src_special`, `src_ttmp`, `src_vcc` | | VOPC | `vopc_vcc` | `src_exec`, `src_float_inline`, `src_m0`, `src_null`, `src_special`, `src_ttmp`, `src_vcc_hi` | diff --git a/docs/shaders/semantic-registry.md b/docs/shaders/semantic-registry.md index 9cb63d4..2fb8821 100644 --- a/docs/shaders/semantic-registry.md +++ b/docs/shaders/semantic-registry.md @@ -35,6 +35,39 @@ families therefore never edits the same registry file. To add a family, create `rdna2/.toml` and append it to `include`; the generated order (and so the generated file) changes only where the new file is placed. +## Encoding variants + +An `[[encoding_variant]]` is another encoding of a form that is already declared, +such as the VOP3 (`_e64`) encoding of a VOP2 form. It is pure data in the family +file of its encoding (`rdna2/vop3.toml`) and has exactly these fields: + +| Field | Meaning | +| --- | --- | +| `of` | The `name` of the declared base form | +| `family` | The encoding family of this variant; must differ from the form's | +| `opcode` | The XML opcode in that family | +| `operands` | An operand rule of that family whose kind can encode the base form (today `vop3_vgpr2` for VOP2 vector forms) | +| `spec`, `verify` | As for a form | + +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__word` (encoding bits, then an explicit match on the OP field) and +`_assembly_name`, and one `FORMS` row per variant after the forms. 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 +rule that cannot encode the form, missing or unknown fields, and any XML +disagreement. + +`vop3_vgpr2` is the subset the decoder accepted for `v_add_nc_u32_e64` before +the registry: VGPR destination, two VGPR sources, ABS, OP_SEL, CLAMP, OMOD and +NEG clear, and SRC2 the assembler's unused inline zero. `v_add_nc_u32_e64` is its +first variant; adding the VOP3 encoding of another VOP2 form under this rule is +one `[[encoding_variant]]` entry. Wider VOP3 operand rules (scalar and inline +sources, legal modifiers) come with the VOP3 batch. + ## Fields The root file holds: diff --git a/scripts/audit/semantic_coverage.py b/scripts/audit/semantic_coverage.py index f9712f3..c59d444 100644 --- a/scripts/audit/semantic_coverage.py +++ b/scripts/audit/semantic_coverage.py @@ -156,6 +156,7 @@ def load_registry(path): 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 @@ -178,7 +179,13 @@ def read_declarations(registry, identified): rules[name] = (family, set(unsupported)) declared = set() - for form in registry["form"]: + # An encoding variant declares its base form in another encoding family. + variants = [ + {"family": variant["family"], "name": variant["of"], "opcode": variant["opcode"], + "operands": variant["operands"]} + for variant in registry.get("encoding_variant", []) + ] + for form in registry["form"] + variants: key = (form["family"], form["name"]) if key not in identified: raise ValueError(f"{REGISTRY}: unknown form {key}") diff --git a/tests/semantics_generator/test_generate_semantics.py b/tests/semantics_generator/test_generate_semantics.py index 58be8d2..9b3b505 100644 --- a/tests/semantics_generator/test_generate_semantics.py +++ b/tests/semantics_generator/test_generate_semantics.py @@ -167,11 +167,34 @@ def snapshot(): ["VSRC1", data_format, "OPR_VGPR", 32, True, False, False, True], ], } + vop3 = { + "name": "ENC_VOP3", + "bits": 64, + "fields": [ + ["VDST", [[0, 8]]], ["ABS", [[8, 3]]], ["OP_SEL", [[11, 4]]], ["CLAMP", [[15, 1]]], + ["OP", [[16, 10]]], ["ENCODING", [[26, 6]]], ["SRC0", [[32, 9]]], ["SRC1", [[41, 9]]], + ["SRC2", [[50, 9]]], ["OMOD", [[59, 2]]], ["NEG", [[61, 3]]], + ], + "identifier_mask": 0xFFFF0000, + "identifiers": [0xD4000000 | (op << 16) for op in (265, 273, 295)], + } + # Values copied from the AMD XML snapshot: VOP3 encodings of VOP2 forms. + for name, opcode, data_format in ( + ("V_MUL_I32_I24", 265, I32), ("V_MIN_I32", 273, I32), ("V_SUBREV_NC_U32", 295, U32), + ): + variants[(name, "ENC_VOP3")] = { + "instruction": name, "encoding": "ENC_VOP3", "opcode": opcode, + "operands": [ + ["VDST", data_format, "OPR_VGPR", 32, False, True, False, True], + ["SRC0", data_format, "OPR_SRC", 32, True, False, False, True], + ["SRC1", data_format, "OPR_SRC_NOLDS", 32, True, False, False, True], + ], + } return { "source": {"sha256": SHA}, "encodings": { "ENC_SOP2": encoding, "ENC_SOPC": sopc, "ENC_SOP1": sop1, "ENC_VOP2": vop2, - "ENC_VOPC": vopc, + "ENC_VOPC": vopc, "ENC_VOP3": vop3, }, "variants": variants, } @@ -266,6 +289,25 @@ def vector_compares(): return reg +def variants(): + reg = vectors() + rule = copy.deepcopy(gen.OPERAND_RULES["vop3_vgpr2"]["shape"]) + rule["unsupported"] = sorted(gen.OPERAND_RULES["vop3_vgpr2"]["unsupported"]) + reg["operand_rules"]["vop3_vgpr2"] = rule + reg["encoding_variant"] = [ + _variant("V_MIN_I32", 273), _variant("V_SUBREV_NC_U32", 295), + ] + return reg + + +def _variant(of, opcode): + return { + "of": of, "family": "VOP3", "opcode": opcode, "operands": "vop3_vgpr2", + "spec": [{"document": "guide", "section": "12.12", "page": 167}], + "verify": ["reference", "independent"], + } + + def compares(): reg = registry() reg["form"] += [ @@ -784,6 +826,68 @@ class Validate(unittest.TestCase): reg["documents"]["guide"]["file"] = "missing.pdf" self.rejects(reg, "document guide: differs from the pinned public document") + # ---- encoding variants ---- + + def test_accepts_encoding_variants(self): + self.assertEqual(self.errors(variants()), []) + + def test_rejects_a_variant_of_an_undeclared_form(self): + reg = variants() + reg["encoding_variant"].append(_variant("V_MUL_HI_I32_I24", 266)) + self.rejects(reg, "V_MUL_HI_I32_I24 (VOP3): encoding variant of an undeclared form") + + def test_rejects_an_incomplete_or_unknown_variant_field(self): + reg = variants() + del reg["encoding_variant"][0]["spec"] + reg["encoding_variant"][1]["operation"] = "sub" + self.rejects(reg, "V_MIN_I32 (VOP3): incomplete encoding variant, missing ['spec']") + self.rejects(reg, "V_SUBREV_NC_U32 (VOP3): unknown keys ['operation']") + + def test_rejects_a_variant_opcode_that_disagrees_with_the_xml(self): + reg = variants() + reg["encoding_variant"][0]["opcode"] = 265 + self.rejects(reg, "V_MIN_I32: opcode 265 disagrees with the XML opcode 273") + + def test_rejects_a_duplicate_variant_or_opcode(self): + reg = variants() + reg["encoding_variant"].append(_variant("V_MIN_I32", 273)) + self.rejects(reg, "V_MIN_I32 (VOP3): duplicate encoding of V_MIN_I32") + self.rejects(reg, "V_MIN_I32 (VOP3): duplicate opcode ('VOP3', 273)") + + def test_rejects_a_variant_in_its_forms_own_family(self): + reg = variants() + reg["encoding_variant"][0].update(family="VOP2", opcode=17, operands="vop2_vgpr") + self.rejects(reg, "V_MIN_I32 (VOP2): an encoding variant must use another family than its form") + + def test_rejects_a_variant_rule_that_cannot_encode_the_form(self): + reg = variants() + reg["encoding_variant"][0]["operands"] = "sop2_sgpr" + self.rejects(reg, "V_MIN_I32 (VOP3): operand rule sop2_sgpr is for SOP2") + self.rejects(reg, "V_MIN_I32 (VOP3): operand rule sop2_sgpr cannot encode a vector form") + + def test_rejects_a_form_that_uses_a_variant_only_rule(self): + reg = variants() + form(reg, "V_MIN_I32")["operands"] = "vop3_vgpr2" + self.rejects(reg, "V_MIN_I32: operand rule vop3_vgpr2 is only for encoding variants") + + def test_checks_the_variant_xml_against_the_inherited_declaration(self): + snap = snapshot() + for row in snap["variants"][("V_MIN_I32", "ENC_VOP3")]["operands"]: + row[1] = U32 + self.rejects(variants(), "V_MIN_I32: signedness signed contradicts XML format FMT_NUM_U32", snap) + + def test_renders_variant_dispatch_and_rows(self): + text = gen.render(variants(), snapshot()) + self.assertIn("pub const fn from_vop3_word(word: u32) -> Option {", text) + 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('("V_MIN_I32", EncodingFamily::Vop3),', text) + self.assertIn("operands: OperandRule::Vop3Vgpr2,", text) + # The VOP3 row inherits SUBREV's reversed sources. + row = text.split('name: "V_SUBREV_NC_U32",\n family: EncodingFamily::Vop3,', 1)[1] + self.assertIn("swap_sources: true,", row.split("}", 1)[0]) + def test_rejects_an_unenforced_wave_restriction(self): reg = registry() reg["form"][0]["wave"] = "wave32" @@ -1070,8 +1174,9 @@ class LoadRegistry(unittest.TestCase): # Each family is one contiguous run, in include order. runs = [family for index, family in enumerate(families) if index == 0 or families[index - 1] != family] self.assertEqual(len(runs), len(set(runs))) + declared = set(runs) | {variant["family"] for variant in registry.get("encoding_variant", [])} for name, rule in registry["operand_rules"].items(): - self.assertIn(rule["family"], runs, name) + self.assertIn(rule["family"], declared, name) def test_merges_family_files_in_include_order(self): root = self.write('include = ["rdna2/vop2.toml", "rdna2/sop2.toml"]\n', { From 6bc88d6c5161b15f9e6a0e979eb21e6adffd3591 Mon Sep 17 00:00:00 2001 From: elforeign <324243036+elforeign@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:01:18 -0600 Subject: [PATCH 08/15] isa, scripts: review fixes for the registry split and encoding variants (#215) - Includes must be `/.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> --- crates/decoder/src/lib.rs | 14 ++- crates/decoder/tests/gfx1030.rs | 10 +- crates/isa/generate_semantics.py | 105 +++++++++++++++--- crates/isa/src/lib.rs | 8 +- crates/isa/src/semantics_gen.rs | 44 ++++++-- crates/isa/tests/semantics.rs | 36 +++--- crates/shader/src/lib.rs | 5 +- docs/shaders/scalar-alu.md | 2 +- docs/shaders/semantic-registry.md | 22 ++-- scripts/audit/semantic_coverage.py | 26 ++--- scripts/qa/rdna2_plan.py | 10 +- tests/qa/test_rdna2_plan.py | 14 +++ .../test_semantic_coverage.py | 20 ++++ .../test_generate_semantics.py | 30 ++++- 14 files changed, 263 insertions(+), 83 deletions(-) diff --git a/crates/decoder/src/lib.rs b/crates/decoder/src/lib.rs index f5e1014..398a88a 100644 --- a/crates/decoder/src/lib.rs +++ b/crates/decoder/src/lib.rs @@ -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 { +fn vop3_vgpr2( + op: VectorAluVop3Op, + first: u32, + second: u32, +) -> Result { 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", )); } diff --git a/crates/decoder/tests/gfx1030.rs b/crates/decoder/tests/gfx1030.rs index de9ea49..ae9f8b9 100644 --- a/crates/decoder/tests/gfx1030.rs +++ b/crates/decoder/tests/gfx1030.rs @@ -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 diff --git a/crates/isa/generate_semantics.py b/crates/isa/generate_semantics.py index d9604db..7735cbf 100755 --- a/crates/isa/generate_semantics.py +++ b/crates/isa/generate_semantics.py @@ -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 `/.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 `/.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}/.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 {{", + " /// 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 {", 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 diff --git a/crates/isa/src/lib.rs b/crates/isa/src/lib.rs index e55aa8f..aad5376 100644 --- a/crates/isa/src/lib.rs +++ b/crates/isa/src/lib.rs @@ -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(), diff --git a/crates/isa/src/semantics_gen.rs b/crates/isa/src/semantics_gen.rs index 94e720b..7f25966 100644 --- a/crates/isa/src/semantics_gen.rs +++ b/crates/isa/src/semantics_gen.rs @@ -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 { +/// 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 { 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. diff --git a/crates/isa/tests/semantics.rs b/crates/isa/tests/semantics.rs index c1aa420..14826d0 100644 --- a/crates/isa/tests/semantics.rs +++ b/crates/isa/tests/semantics.rs @@ -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 + ); + } } diff --git a/crates/shader/src/lib.rs b/crates/shader/src/lib.rs index c7ee8a8..c61a905 100644 --- a/crates/shader/src/lib.rs +++ b/crates/shader/src/lib.rs @@ -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 Result { + let op = op.base(); let (left, right) = if op.swaps_sources() { (read(src1)?, read(src0)?) } else { diff --git a/docs/shaders/scalar-alu.md b/docs/shaders/scalar-alu.md index 213e896..7a74b12 100644 --- a/docs/shaders/scalar-alu.md +++ b/docs/shaders/scalar-alu.md @@ -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 diff --git a/docs/shaders/semantic-registry.md b/docs/shaders/semantic-registry.md index 2fb8821..468de39 100644 --- a/docs/shaders/semantic-registry.md +++ b/docs/shaders/semantic-registry.md @@ -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/.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/.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/.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/.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__word` (encoding bits, then an explicit match on the OP field) and -`_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 diff --git a/scripts/audit/semantic_coverage.py b/scripts/audit/semantic_coverage.py index c59d444..3fca878 100644 --- a/scripts/audit/semantic_coverage.py +++ b/scripts/audit/semantic_coverage.py @@ -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): diff --git a/scripts/qa/rdna2_plan.py b/scripts/qa/rdna2_plan.py index f648882..fd29f36 100644 --- a/scripts/qa/rdna2_plan.py +++ b/scripts/qa/rdna2_plan.py @@ -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}") diff --git a/tests/qa/test_rdna2_plan.py b/tests/qa/test_rdna2_plan.py index 1737183..103151d 100644 --- a/tests/qa/test_rdna2_plan.py +++ b/tests/qa/test_rdna2_plan.py @@ -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: diff --git a/tests/semantic_coverage/test_semantic_coverage.py b/tests/semantic_coverage/test_semantic_coverage.py index b8aa5b8..0147cac 100644 --- a/tests/semantic_coverage/test_semantic_coverage.py +++ b/tests/semantic_coverage/test_semantic_coverage.py @@ -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() diff --git a/tests/semantics_generator/test_generate_semantics.py b/tests/semantics_generator/test_generate_semantics.py index 9b3b505..de461df 100644 --- a/tests/semantics_generator/test_generate_semantics.py +++ b/tests/semantics_generator/test_generate_semantics.py @@ -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 {", text) + self.assertIn("pub enum VectorAluVop3Op {", text) + self.assertIn("pub const fn from_word(word: u32) -> Option {", 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/.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": ""}) From 846589abce8fb00c593f81a23e1d516985363506 Mon Sep 17 00:00:00 2001 From: elforeign <324243036+elforeign@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:06:26 -0600 Subject: [PATCH 09/15] isa, scripts: second round of registry review fixes (#215) - A family file must be a regular file directly in the registry directory: links (and so second names for one file) are rejected. - Variant operand formats are compared by role (destination, then the sources in rule order), not by XML row order. - Malformed spec and verify values are diagnosed instead of raising. - vop3_vgpr2 declares variant_only = true in the data; the planner reads that flag instead of inferring it from which entries use the rule. Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com> --- crates/isa/generate_semantics.py | 50 +++++++++++++++---- crates/isa/semantics/rdna2/vop3.toml | 2 + docs/shaders/semantic-registry.md | 7 ++- scripts/qa/rdna2_plan.py | 10 ++-- tests/qa/test_rdna2_plan.py | 10 +++- .../test_generate_semantics.py | 41 ++++++++++++++- 6 files changed, 99 insertions(+), 21 deletions(-) diff --git a/crates/isa/generate_semantics.py b/crates/isa/generate_semantics.py index 7735cbf..b09c460 100755 --- a/crates/isa/generate_semantics.py +++ b/crates/isa/generate_semantics.py @@ -310,6 +310,9 @@ OPERAND_RULES = { {"field": "SRC1", "class": "vgpr"}, ], "max_literals": 0, + # Declared in the data, so every reader (the planner too) knows this + # rule only re-encodes declared forms. + "variant_only": True, }, # Two VGPR sources only, with ABS, OP_SEL, CLAMP, OMOD and NEG clear and # SRC2 the assembler's unused inline zero; the decoder rejects the rest. @@ -388,11 +391,16 @@ def load_registry(path=REGISTRY): raise RegistryError(f"{path.name}: a family file is included twice") rules = registry.setdefault("operand_rules", {}) forms = registry.setdefault("form", []) + directory = (path.parent / path.stem).resolve() for include in includes: part_path = path.parent / include family = Path(include).stem.upper() if not part_path.is_file(): raise RegistryError(f"{path.name}: included family file {include} does not exist") + # A family file is a regular file directly in the registry directory, + # not a link to data elsewhere (nor a second name for another include). + if part_path.is_symlink() or part_path.resolve().parent != directory: + raise RegistryError(f"{path.name}: included family file {include} is a link or outside {path.stem}/") with open(part_path, "rb") as handle: part = tomllib.load(handle) unknown = sorted(set(part) - FAMILY_FILE_KEYS) @@ -727,6 +735,9 @@ def validate(registry, snapshot): errors.append(f"{label}: operation {form['operation']} does not fit rule {form['operands']}") _check_spec(label, form["spec"], documents, errors) verify = form["verify"] + if not isinstance(verify, list) or not all(isinstance(item, str) for item in verify): + errors.append(f"{label}: verify must be a list of evidence names") + verify = [] if not verify: errors.append(f"{label}: no verification requirement") if any(item not in EVIDENCE for item in verify): @@ -793,7 +804,11 @@ def _check_variants(registry, rules, documents, snapshot, seen, errors): ) _check_spec(label, variant["spec"], documents, errors) verify = variant["verify"] - if not verify or any(item not in EVIDENCE for item in verify) or len(set(verify)) != len(verify): + if ( + not isinstance(verify, list) or not all(isinstance(item, str) for item in verify) + or not verify or any(item not in EVIDENCE for item in verify) + or len(set(verify)) != len(verify) + ): errors.append(f"{label}: invalid verification requirements {verify}") # 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. @@ -802,14 +817,23 @@ def _check_variants(registry, rules, documents, snapshot, seen, errors): # 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]}" - ) + base_rule = rules.get(base.get("operands")) + if base_xml and own_xml and isinstance(base_rule, dict): + # Operands correspond by role, in rule order: the destination, then + # each source (VSRC1 of VOP2 is SRC1 of VOP3). + def roles(rule, record): + by_field = {row[0]: row[1] for row in record["operands"] if row[0]} + fields = ([rule["dst"]["field"]] if "dst" in rule else []) + fields += [src["field"] for src in rule.get("src", [])] + return [(field, by_field.get(field)) for field in fields] + + pairs = list(zip(roles(base_rule, base_xml), roles(rule, own_xml))) + for (base_field, base_format), (field, data_format) in pairs: + if base_format != data_format: + errors.append( + f"{label}: XML {field} format {data_format} differs from the form's " + f"{base_field} format {base_format}" + ) def _implemented_rule(form): @@ -831,10 +855,16 @@ def _rule_enum(form): def _check_spec(label, spec, documents, errors): has_guide = False + if not isinstance(spec, list): + errors.append(f"{label}: spec must be a list of references") + return for ref in spec: - if set(ref) != {"document", "section", "page"}: + if not isinstance(ref, dict) or set(ref) != {"document", "section", "page"}: errors.append(f"{label}: spec reference needs exactly document, section, page") continue + if not isinstance(ref["document"], str): + errors.append(f"{label}: spec document must be a name") + 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"])): diff --git a/crates/isa/semantics/rdna2/vop3.toml b/crates/isa/semantics/rdna2/vop3.toml index ecd1a6f..960e627 100644 --- a/crates/isa/semantics/rdna2/vop3.toml +++ b/crates/isa/semantics/rdna2/vop3.toml @@ -18,6 +18,8 @@ src = [ { field = "SRC1", class = "vgpr" }, ] max_literals = 0 +# Only [[encoding_variant]] entries may use this rule; it hosts no new forms. +variant_only = true unsupported = [ "src_sgpr", "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_null", "src_inline", "src_float_inline", "src_special", "src_literal", "modifiers", "src2", diff --git a/docs/shaders/semantic-registry.md b/docs/shaders/semantic-registry.md index 468de39..26f94dc 100644 --- a/docs/shaders/semantic-registry.md +++ b/docs/shaders/semantic-registry.md @@ -29,7 +29,7 @@ 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.*]`, `[[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/.toml`. The loader rejects a form, +Each include must be `rdna2/.toml`, a regular file in that directory (not a link). 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 @@ -60,7 +60,10 @@ 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 +destination included, must have the data format of the base operand in the same +role (destination, then the sources in rule order). A variant-only rule says so +in the data (`variant_only = true`), so the RDNA2 planner does not count it as a +rule that can host new forms. 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 diff --git a/scripts/qa/rdna2_plan.py b/scripts/qa/rdna2_plan.py index fd29f36..d878f68 100644 --- a/scripts/qa/rdna2_plan.py +++ b/scripts/qa/rdna2_plan.py @@ -200,10 +200,12 @@ def classify_unsupported( registry = data["registry"] rules = data["rules"] ops = _declared_ops(registry) - form_rules = {form.get("operands") for form in registry.get("form", [])} + # A rule declared `variant_only` re-encodes declared forms (for example the + # VOP3 encoding of a VOP2 form) and cannot host a new form of its family. variant_only_rules = { - variant.get("operands") for variant in registry.get("encoding_variant", []) - } - form_rules + name for name, rule in registry.get("operand_rules", {}).items() + if isinstance(rule, dict) and rule.get("variant_only") is True + } family_widths: dict[str, set[int]] = defaultdict(set) family_types: dict[str, set[str]] = defaultdict(set) for form in registry.get("form", []): @@ -225,8 +227,6 @@ def classify_unsupported( continue opcode = identified[(family, name)] reusable = sorted(op for op in ops if op) - # 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 ] diff --git a/tests/qa/test_rdna2_plan.py b/tests/qa/test_rdna2_plan.py index 103151d..2412771 100644 --- a/tests/qa/test_rdna2_plan.py +++ b/tests/qa/test_rdna2_plan.py @@ -70,15 +70,21 @@ class Rdna2Plan(unittest.TestCase): # 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", []) + name for name, rule in self.data["registry"]["operand_rules"].items() + if rule.get("variant_only") is True } if not variant_rules: - self.skipTest("no encoding variants declared") + self.skipTest("no variant-only operand rules 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) + # The flag, not current usage, decides: without any variant using the + # rule, the family still has no rule for new forms. + data = dict(self.data, registry=dict(self.data["registry"], encoding_variant=[])) + for cand in classify_unsupported(data, families=["VOP3"]): + 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) diff --git a/tests/semantics_generator/test_generate_semantics.py b/tests/semantics_generator/test_generate_semantics.py index de461df..bae5e7e 100644 --- a/tests/semantics_generator/test_generate_semantics.py +++ b/tests/semantics_generator/test_generate_semantics.py @@ -881,11 +881,41 @@ class Validate(unittest.TestCase): 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']", + "V_MIN_I32 (VOP3): XML VDST format FMT_NUM_F32 differs from the form's VDST format FMT_NUM_I32", snap, ) + def test_compares_variant_formats_by_role_not_row_order(self): + snap = snapshot() + rows = snap["variants"][("V_MIN_I32", "ENC_VOP3")]["operands"] + rows[0], rows[1] = rows[1], rows[0] + self.assertEqual(self.errors(variants(), snap), []) + # A genuine mismatch on the second source is still reported by role. + rows[2][1] = U32 + self.rejects( + variants(), "V_MIN_I32 (VOP3): XML SRC1 format FMT_NUM_U32 differs from the form's VSRC1", snap + ) + + def test_rejects_malformed_spec_and_verify_without_a_traceback(self): + cases = ( + ("spec", 1, "spec must be a list of references"), + ("spec", [[]], "spec reference needs exactly document, section, page"), + ("spec", [{"document": [], "section": "1", "page": 1}], "spec document must be a name"), + ("verify", 1, "invalid verification requirements"), + ("verify", [[]], "invalid verification requirements"), + ) + for key, value, fragment in cases: + with self.subTest(key=key, value=value): + reg = variants() + reg["encoding_variant"][0][key] = value + self.rejects(reg, fragment) + for key, value, fragment in cases: + with self.subTest(form=True, key=key, value=value): + reg = variants() + form(reg, "V_MIN_I32")[key] = value + expected = "verify must be a list of evidence names" if key == "verify" else fragment + self.rejects(reg, expected) + def test_rejects_malformed_variant_fields_without_a_traceback(self): for key in ("of", "operands", "family"): with self.subTest(key=key): @@ -1236,6 +1266,13 @@ class LoadRegistry(unittest.TestCase): root = self.write(f'include = ["{include}"]\n', {"sop2.toml": ""}) self.fails(root, f"include {include!r} is not rdna2/.toml") + def test_rejects_a_family_file_that_is_a_link(self): + outside = self.dir / "outside.toml" + outside.write_text("", encoding="utf-8") + (self.dir / "rdna2" / "sop2.toml").symlink_to(outside) + root = self.write('include = ["rdna2/sop2.toml"]\n', {}) + self.fails(root, "included family file rdna2/sop2.toml is a link or outside rdna2/") + 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": ""}) From 06614f2219c4317a6e96a39589f38a405469599f Mon Sep 17 00:00:00 2001 From: elforeign <324243036+elforeign@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:09:16 -0600 Subject: [PATCH 10/15] isa: third round of registry review fixes (#215) - The family directory must not be a link, and two includes must not be hard links to one file. - The role-based format comparison skips malformed rules (they keep their rule diagnostic instead of raising), and its test now reproduces the row-order case the old comparison got wrong. Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com> --- crates/isa/generate_semantics.py | 19 ++++++++++++++- .../test_generate_semantics.py | 23 ++++++++++++++++++- 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/crates/isa/generate_semantics.py b/crates/isa/generate_semantics.py index b09c460..ec4c7f9 100755 --- a/crates/isa/generate_semantics.py +++ b/crates/isa/generate_semantics.py @@ -392,6 +392,9 @@ def load_registry(path=REGISTRY): rules = registry.setdefault("operand_rules", {}) forms = registry.setdefault("form", []) directory = (path.parent / path.stem).resolve() + if (path.parent / path.stem).is_symlink(): + raise RegistryError(f"{path.name}: the family directory {path.stem}/ is a link") + identities = set() for include in includes: part_path = path.parent / include family = Path(include).stem.upper() @@ -401,6 +404,10 @@ def load_registry(path=REGISTRY): # not a link to data elsewhere (nor a second name for another include). if part_path.is_symlink() or part_path.resolve().parent != directory: raise RegistryError(f"{path.name}: included family file {include} is a link or outside {path.stem}/") + status = part_path.stat() + if (status.st_dev, status.st_ino) in identities: + raise RegistryError(f"{path.name}: included family file {include} is another name for an included file") + identities.add((status.st_dev, status.st_ino)) with open(part_path, "rb") as handle: part = tomllib.load(handle) unknown = sorted(set(part) - FAMILY_FILE_KEYS) @@ -749,6 +756,16 @@ def validate(registry, snapshot): return errors +def _well_formed(rule): + """Whether a rule has the dst/src shape the operand checks read.""" + return ( + isinstance(rule, dict) + and isinstance(rule.get("src"), list) + and all(isinstance(src, dict) and isinstance(src.get("field"), str) for src in rule["src"]) + and ("dst" not in rule or (isinstance(rule["dst"], dict) and isinstance(rule["dst"].get("field"), str))) + ) + + def variant_row(registry, variant): """The base form re-encoded: its declaration with the variant's identity.""" base = next(form for form in registry["form"] if form.get("name") == variant["of"]) @@ -818,7 +835,7 @@ def _check_variants(registry, rules, documents, snapshot, seen, errors): base_xml = snapshot["variants"].get((base["name"], _family_encoding(base["family"]))) own_xml = snapshot["variants"].get((variant["of"], _family_encoding(variant["family"]))) base_rule = rules.get(base.get("operands")) - if base_xml and own_xml and isinstance(base_rule, dict): + if base_xml and own_xml and _well_formed(base_rule) and _well_formed(rule): # Operands correspond by role, in rule order: the destination, then # each source (VSRC1 of VOP2 is SRC1 of VOP3). def roles(rule, record): diff --git a/tests/semantics_generator/test_generate_semantics.py b/tests/semantics_generator/test_generate_semantics.py index bae5e7e..13ec5d4 100644 --- a/tests/semantics_generator/test_generate_semantics.py +++ b/tests/semantics_generator/test_generate_semantics.py @@ -10,6 +10,7 @@ snapshot are only read, never edited. Run from the repository root: import copy import importlib.util +import os import shutil import subprocess import sys @@ -887,15 +888,26 @@ class Validate(unittest.TestCase): def test_compares_variant_formats_by_role_not_row_order(self): snap = snapshot() + # Give both encodings an unsigned destination and signed sources, then + # list the VOP3 rows in another order: by role they still match. + snap["variants"][("V_MIN_I32", "ENC_VOP2")]["operands"][0][1] = U32 rows = snap["variants"][("V_MIN_I32", "ENC_VOP3")]["operands"] + rows[0][1] = U32 rows[0], rows[1] = rows[1], rows[0] - self.assertEqual(self.errors(variants(), snap), []) + reg = variants() + errors = [error for error in self.errors(reg, snap) if "differs from the form" in error] + self.assertEqual(errors, []) # A genuine mismatch on the second source is still reported by role. rows[2][1] = U32 self.rejects( variants(), "V_MIN_I32 (VOP3): XML SRC1 format FMT_NUM_U32 differs from the form's VSRC1", snap ) + def test_a_malformed_variant_rule_is_a_diagnostic(self): + reg = variants() + reg["operand_rules"]["vop3_vgpr2"]["src"] = 1 + self.rejects(reg, "operand rule vop3_vgpr2: declaration differs from the decoder's implemented rule") + def test_rejects_malformed_spec_and_verify_without_a_traceback(self): cases = ( ("spec", 1, "spec must be a list of references"), @@ -1273,6 +1285,15 @@ class LoadRegistry(unittest.TestCase): root = self.write('include = ["rdna2/sop2.toml"]\n', {}) self.fails(root, "included family file rdna2/sop2.toml is a link or outside rdna2/") + def test_rejects_a_linked_directory_or_a_hard_link_alias(self): + root = self.write('include = ["rdna2/sop2.toml", "rdna2/vop2.toml"]\n', {"sop2.toml": ""}) + os.link(self.dir / "rdna2" / "sop2.toml", self.dir / "rdna2" / "vop2.toml") + self.fails(root, "included family file rdna2/vop2.toml is another name for an included file") + outside = self.dir / "outside" + (self.dir / "rdna2").rename(outside) + (self.dir / "rdna2").symlink_to(outside, target_is_directory=True) + self.fails(root, "the family directory rdna2/ is a link") + 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": ""}) From 625e26affc5c0b09c3892377e7759c337515f4f1 Mon Sep 17 00:00:00 2001 From: elforeign <324243036+elforeign@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:10:51 -0600 Subject: [PATCH 11/15] isa: fourth round of registry review fixes (#215) A self-referential family-directory link is reported instead of raising, a malformed rule destination field is a rule diagnostic in the XML check too, and the row-order test asserts a fully valid registry so it catches the old row-order comparison. Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com> --- crates/isa/generate_semantics.py | 9 +++++---- .../test_generate_semantics.py | 17 +++++++++++------ 2 files changed, 16 insertions(+), 10 deletions(-) diff --git a/crates/isa/generate_semantics.py b/crates/isa/generate_semantics.py index ec4c7f9..ed680c8 100755 --- a/crates/isa/generate_semantics.py +++ b/crates/isa/generate_semantics.py @@ -391,9 +391,12 @@ def load_registry(path=REGISTRY): raise RegistryError(f"{path.name}: a family file is included twice") rules = registry.setdefault("operand_rules", {}) forms = registry.setdefault("form", []) - directory = (path.parent / path.stem).resolve() if (path.parent / path.stem).is_symlink(): raise RegistryError(f"{path.name}: the family directory {path.stem}/ is a link") + try: + directory = (path.parent / path.stem).resolve(strict=True) + except (OSError, RuntimeError) as error: + raise RegistryError(f"{path.name}: the family directory {path.stem}/ cannot be read: {error}") identities = set() for include in includes: part_path = path.parent / include @@ -526,9 +529,7 @@ def _check_xml(form, rule, snapshot, errors): errors.append(f"{label}: scc {form['scc']} contradicts the XML SCC output") if rule is None: return - if not isinstance(rule.get("src"), list) or not all( - isinstance(src, dict) and isinstance(src.get("field"), str) for src in rule["src"] - ) or ("dst" in rule and not (isinstance(rule["dst"], dict) and "field" in rule["dst"])): + if not _well_formed(rule): return # the rule check already reported the malformed shape fields = [(rule["dst"]["field"], False)] if "dst" in rule else [] fields += [(src["field"], True) for src in rule["src"]] diff --git a/tests/semantics_generator/test_generate_semantics.py b/tests/semantics_generator/test_generate_semantics.py index 13ec5d4..d2be136 100644 --- a/tests/semantics_generator/test_generate_semantics.py +++ b/tests/semantics_generator/test_generate_semantics.py @@ -894,9 +894,7 @@ class Validate(unittest.TestCase): rows = snap["variants"][("V_MIN_I32", "ENC_VOP3")]["operands"] rows[0][1] = U32 rows[0], rows[1] = rows[1], rows[0] - reg = variants() - errors = [error for error in self.errors(reg, snap) if "differs from the form" in error] - self.assertEqual(errors, []) + self.assertEqual(self.errors(variants(), snap), []) # A genuine mismatch on the second source is still reported by role. rows[2][1] = U32 self.rejects( @@ -904,9 +902,13 @@ class Validate(unittest.TestCase): ) def test_a_malformed_variant_rule_is_a_diagnostic(self): - reg = variants() - reg["operand_rules"]["vop3_vgpr2"]["src"] = 1 - self.rejects(reg, "operand rule vop3_vgpr2: declaration differs from the decoder's implemented rule") + for key, value in (("src", 1), ("dst", {"field": [], "class": "vgpr", "min": 0, "max": 255})): + with self.subTest(key=key): + reg = variants() + reg["operand_rules"]["vop3_vgpr2"][key] = value + self.rejects( + reg, "operand rule vop3_vgpr2: declaration differs from the decoder's implemented rule" + ) def test_rejects_malformed_spec_and_verify_without_a_traceback(self): cases = ( @@ -1293,6 +1295,9 @@ class LoadRegistry(unittest.TestCase): (self.dir / "rdna2").rename(outside) (self.dir / "rdna2").symlink_to(outside, target_is_directory=True) self.fails(root, "the family directory rdna2/ is a link") + (self.dir / "rdna2").unlink() + (self.dir / "rdna2").symlink_to(self.dir / "rdna2", target_is_directory=True) + self.fails(root, "the family directory rdna2/ is a link") 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") From 06ded40d549e8639ad2d13f21ed99e60d20ab4f2 Mon Sep 17 00:00:00 2001 From: elforeign <324243036+elforeign@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:26:23 -0600 Subject: [PATCH 12/15] isa, scripts: registry loader and variant validation give diagnostics, not tracebacks (#215) - A standalone registry (no include) no longer needs a family directory. - A variant of an incomplete form reports the form instead of a KeyError. - A non-array encoding_variant, or a non-table entry, is a diagnostic in the loader, the validator and the coverage report. Each case has a test that fails on the previous code. The split-registry test now compares the whole merged result with a hand concatenation, and vop3.toml cites guide 12.7.1 for the VOP3 opcode offset. Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com> --- crates/isa/generate_semantics.py | 38 +++++++++++++--- crates/isa/semantics/rdna2/vop3.toml | 2 + scripts/audit/semantic_coverage.py | 10 ++++- .../test_semantic_coverage.py | 5 +++ .../test_generate_semantics.py | 45 +++++++++++++++++++ 5 files changed, 92 insertions(+), 8 deletions(-) diff --git a/crates/isa/generate_semantics.py b/crates/isa/generate_semantics.py index ed680c8..00db2d0 100755 --- a/crates/isa/generate_semantics.py +++ b/crates/isa/generate_semantics.py @@ -389,14 +389,22 @@ def load_registry(path=REGISTRY): ) if len(set(includes)) != len(includes): raise RegistryError(f"{path.name}: a family file is included twice") + for key, kind, name in (("operand_rules", dict, "a table"), ("form", list, "an array"), + ("encoding_variant", list, "an array")): + if not isinstance(registry.get(key, kind()), kind): + raise RegistryError(f"{path.name}: {key} must be {name}") rules = registry.setdefault("operand_rules", {}) forms = registry.setdefault("form", []) - if (path.parent / path.stem).is_symlink(): - raise RegistryError(f"{path.name}: the family directory {path.stem}/ is a link") - try: - directory = (path.parent / path.stem).resolve(strict=True) - except (OSError, RuntimeError) as error: - raise RegistryError(f"{path.name}: the family directory {path.stem}/ cannot be read: {error}") + # A standalone registry (no includes) needs no family directory. + if includes: + if (path.parent / path.stem).is_symlink(): + raise RegistryError(f"{path.name}: the family directory {path.stem}/ is a link") + try: + directory = (path.parent / path.stem).resolve(strict=True) + except (OSError, RuntimeError) as error: + raise RegistryError( + f"{path.name}: the family directory {path.stem}/ cannot be read: {error}" + ) identities = set() for include in includes: part_path = path.parent / include @@ -416,6 +424,10 @@ def load_registry(path=REGISTRY): unknown = sorted(set(part) - FAMILY_FILE_KEYS) if unknown: raise RegistryError(f"{include}: keys {unknown} belong in the root file") + for key, kind, name in (("operand_rules", dict, "a table"), ("form", list, "an array"), + ("encoding_variant", list, "an array")): + if not isinstance(part.get(key, kind()), kind): + raise RegistryError(f"{include}: {key} must be {name}") for name, rule in part.get("operand_rules", {}).items(): if name in rules: raise RegistryError(f"{include}: operand rule {name} is declared twice") @@ -779,7 +791,14 @@ def variant_row(registry, variant): 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", [])): + variants = registry.get("encoding_variant", []) + if not isinstance(variants, list): + errors.append("encoding_variant must be an array of tables") + return + for index, variant in enumerate(variants): + if not isinstance(variant, dict): + errors.append(f"encoding variant #{index}: must be a table, got {variant!r}") + continue 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) @@ -830,6 +849,11 @@ def _check_variants(registry, rules, documents, snapshot, seen, errors): errors.append(f"{label}: invalid verification requirements {verify}") # 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. + # An incomplete base form has its own diagnostic; checking its re-encoding + # would only fail on the missing fields. + if FORM_KEYS - set(base): + errors.append(f"{label}: not checked, its form {variant['of']} is incomplete") + continue _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). diff --git a/crates/isa/semantics/rdna2/vop3.toml b/crates/isa/semantics/rdna2/vop3.toml index 960e627..cffcc80 100644 --- a/crates/isa/semantics/rdna2/vop3.toml +++ b/crates/isa/semantics/rdna2/vop3.toml @@ -25,6 +25,8 @@ unsupported = [ "src_float_inline", "src_special", "src_literal", "modifiers", "src2", ] +# VOP3 opcode of a VOP2 form = VOP2 opcode + 0x100 (guide 12.7.1), e.g. 37 + 256 +# = 293; each opcode below is still checked against the pinned XML. [[encoding_variant]] of = "V_ADD_NC_U32" family = "VOP3" diff --git a/scripts/audit/semantic_coverage.py b/scripts/audit/semantic_coverage.py index 3fca878..498a0e9 100644 --- a/scripts/audit/semantic_coverage.py +++ b/scripts/audit/semantic_coverage.py @@ -180,10 +180,18 @@ def read_declarations(registry, identified): declared = set() # An encoding variant declares its base form in another encoding family. + raw_variants = registry.get("encoding_variant", []) + if not isinstance(raw_variants, list) or not all( + isinstance(variant, dict) and {"family", "of", "opcode", "operands"} <= set(variant) + for variant in raw_variants + ): + raise ValueError( + f"{REGISTRY}: every encoding_variant needs family, of, opcode and operands" + ) variants = [ {"family": variant["family"], "name": variant["of"], "opcode": variant["opcode"], "operands": variant["operands"]} - for variant in registry.get("encoding_variant", []) + for variant in raw_variants ] for form in registry["form"] + variants: key = (form["family"], form["name"]) diff --git a/tests/semantic_coverage/test_semantic_coverage.py b/tests/semantic_coverage/test_semantic_coverage.py index 0147cac..bcf019b 100644 --- a/tests/semantic_coverage/test_semantic_coverage.py +++ b/tests/semantic_coverage/test_semantic_coverage.py @@ -68,6 +68,11 @@ class SemanticCoverageTests(unittest.TestCase): # S_ADD_U32 is declared in the registry but absent from the compiled tables. self.assertEqual(self.counts()["Decoder-supported"], 1) + def test_a_variant_without_its_form_is_an_error_not_a_traceback(self): + self.registry["encoding_variant"] = [{"family": "VOP3", "opcode": 1, "operands": "x"}] + with self.assertRaisesRegex(ValueError, "every encoding_variant needs"): + coverage.read_declarations(self.registry, self.identified) + def test_generated_table_parser(self): source = ( "pub const FORM_IDS: [(&str, EncodingFamily); 1] = [\n" diff --git a/tests/semantics_generator/test_generate_semantics.py b/tests/semantics_generator/test_generate_semantics.py index d2be136..fce2781 100644 --- a/tests/semantics_generator/test_generate_semantics.py +++ b/tests/semantics_generator/test_generate_semantics.py @@ -937,6 +937,22 @@ class Validate(unittest.TestCase): reg["encoding_variant"][0][key] = [] self.rejects(reg, f"[{key!r}] must be strings") + def test_a_variant_of_an_incomplete_form_reports_the_form_not_a_traceback(self): + reg = variants() + base = next(f for f in reg["form"] if f["name"] == reg["encoding_variant"][0]["of"]) + del base["width"] + errors = self.errors(reg) + self.assertTrue(any("missing ['width']" in error for error in errors), errors) + self.assertTrue(any("is incomplete" in error for error in errors), errors) + + def test_a_non_array_or_non_table_variant_is_a_diagnostic(self): + reg = variants() + reg["encoding_variant"] = 1 + self.rejects(reg, "encoding_variant must be an array of tables") + reg = variants() + reg["encoding_variant"].append(1) + self.rejects(reg, "must be a table, got 1") + def test_renders_variant_dispatch_and_rows(self): text = gen.render(variants(), snapshot()) self.assertIn("pub enum VectorAluVop3Op {", text) @@ -1230,6 +1246,18 @@ class LoadRegistry(unittest.TestCase): gen.load_registry(root) self.assertIn(fragment, str(raised.exception)) + def test_a_standalone_registry_needs_no_family_directory(self): + (self.dir / "rdna2").rmdir() + root = self.write('[[form]]\nname = "S_ADD_U32"\nfamily = "SOP2"\n', {}) + self.assertEqual(gen.load_registry(root)["form"][0]["name"], "S_ADD_U32") + root.write_text("schema = 1\ninclude = []\n", encoding="utf-8") + self.assertEqual(gen.load_registry(root)["form"], []) + + def test_a_malformed_variant_list_is_a_registry_error(self): + self.fails(self.write("encoding_variant = 1\n", {}), "encoding_variant must be an array") + root = self.write('include = ["rdna2/vop3.toml"]\n', {"vop3.toml": "encoding_variant = 1\n"}) + self.fails(root, "vop3.toml: encoding_variant must be an array") + def test_the_real_split_registry_equals_one_concatenated_file(self): registry = gen.load_registry() self.assertNotIn("include", registry) @@ -1240,6 +1268,23 @@ class LoadRegistry(unittest.TestCase): declared = set(runs) | {variant["family"] for variant in registry.get("encoding_variant", [])} for name, rule in registry["operand_rules"].items(): self.assertIn(rule["family"], declared, name) + # The whole merged result equals the files concatenated by hand: every + # form, rule and variant, in order, with nothing dropped or reordered. + import tomllib + + with open(gen.REGISTRY, "rb") as handle: + expected = tomllib.load(handle) + includes = expected.pop("include") + expected.setdefault("operand_rules", {}) + expected.setdefault("form", []) + for include in includes: + with open(gen.REGISTRY.parent / include, "rb") as handle: + part = tomllib.load(handle) + expected["operand_rules"].update(part.get("operand_rules", {})) + expected["form"] += part.get("form", []) + if "encoding_variant" in part: + expected.setdefault("encoding_variant", []).extend(part["encoding_variant"]) + self.assertEqual(registry, expected) def test_merges_family_files_in_include_order(self): root = self.write('include = ["rdna2/vop2.toml", "rdna2/sop2.toml"]\n', { From e1e261ea8275222f3c6d6cd9b09bddac3238bfdf Mon Sep 17 00:00:00 2001 From: elforeign <324243036+elforeign@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:30:54 -0600 Subject: [PATCH 13/15] isa, decoder, shader: move the six VOP2 logical and shift forms into the registry (#215) v_and_b32, v_or_b32, v_xor_b32, v_lshlrev_b32, v_lshrrev_b32 and v_ashrrev_i32 (_e32) are now registry forms under a new operand rule vop2_vgpr2: both sources VGPRs, the subset the hand-written decoder accepted. The rule shares the VectorAluOp enum with vop2_vgpr; the generator renders one enum per shared rule set and an operand_rule() the decoder dispatches on. VectorBinary gains And, Or, Xor and the three shifts with the count masked to S0[4:0]; the shifts declare reversed sources, and the generator now checks the XML count format on SRC0 for reversed forms. The six hand-written Instruction variants, decoder arms and shader Binary variants are removed; the runtime-region allowlist admits exactly the same six forms. No behaviour change: 132,608 VOP2/VOP1/SOP1 words decode to the same text, length and error before and after; the MSL goldens are unchanged. Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com> --- CHANGELOG.md | 1 + crates/decoder/src/lib.rs | 64 +---- crates/decoder/tests/gfx1030.rs | 43 +-- crates/isa/generate_semantics.py | 56 +++- crates/isa/semantics/rdna2/vop2.toml | 125 +++++++++ crates/isa/src/lib.rs | 24 -- crates/isa/src/semantics.rs | 15 + crates/isa/src/semantics_gen.rs | 258 ++++++++++++++++-- crates/shader/src/lib.rs | 90 +++--- docs/shaders/semantic-coverage.md | 5 +- docs/shaders/semantic-registry.md | 13 +- .../test_generate_semantics.py | 19 ++ 12 files changed, 530 insertions(+), 183 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ada8094..15209cb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game remains unsupported. ### Changed +- Moved the six hand-written gfx1030 VOP2 logical and shift forms (`v_and_b32`, `v_or_b32`, `v_xor_b32`, `v_lshlrev_b32`, `v_lshrrev_b32`, `v_ashrrev_i32`, AMD guide section 12.7) into the semantic registry under a new VGPR-only operand rule `vop2_vgpr2`, with no behaviour change: a sweep of 132,608 VOP2, VOP1 and SOP1 words decodes to the same text, length and error before and after, the MSL goldens are unchanged, and the runtime-region allowlist admits exactly the same six forms. The per-lane `VectorBinary` gained `And`, `Or`, `Xor` and the three shifts (count masked to S0[4:0]); 6 hand-written instruction variants and their decoder and lowering arms are gone (17 hand-written forms remain). Part of #215. - Added non-blocking Metal compute submission through `submit_words` and `wait`, with completion-aware resource retirement and a sixteen-dispatch in-flight limit. Synchronous calls keep their existing behavior. The benchmark reports the host submission split and compares synchronous and pipelined batches. - Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits. diff --git a/crates/decoder/src/lib.rs b/crates/decoder/src/lib.rs index 398a88a..658bff2 100644 --- a/crates/decoder/src/lib.rs +++ b/crates/decoder/src/lib.rs @@ -10,13 +10,12 @@ pub use xenora_isa::{ use xenora_isa::{ BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_BRANCH, S_CBRANCH_EXECZ, S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_ENDPGM, S_MOV_B32, S_WAITCNT, S_WAITCNT_VSCNT, V_ADD_F32, - V_AND_B32, V_ASHRREV_I32, 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, VCC_LO, + V_INTERP_P1_F32, V_INTERP_P2_F32, V_MOV_B32, V_MUL_F32, VCC_LO, }; use xenora_isa::meta::EncodingFamily; -use xenora_isa::semantics::FORM_IDS; pub use xenora_isa::semantics::VectorBinary; +use xenora_isa::semantics::{FORM_IDS, OperandRule}; /// Metadata forms that [`decode`] turns into an [`Instruction`] for at least one /// operand combination: the hand-written forms below followed by every form of @@ -41,7 +40,7 @@ const fn concat_forms() -> [(&'static str, EncodingFamily); N] { } /// Decoded forms not yet described by the semantic registry. -const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 23] = [ +const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 17] = [ ("BUFFER_LOAD_DWORD", EncodingFamily::Mubuf), ("BUFFER_STORE_DWORD", EncodingFamily::Mubuf), ("EXP", EncodingFamily::Exp), @@ -55,16 +54,10 @@ const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 23] = [ ("S_WAITCNT", EncodingFamily::Sopp), ("S_WAITCNT_VSCNT", EncodingFamily::Sopk), ("V_ADD_F32", EncodingFamily::Vop2), - ("V_AND_B32", EncodingFamily::Vop2), - ("V_ASHRREV_I32", EncodingFamily::Vop2), ("V_INTERP_P1_F32", EncodingFamily::Vintrp), ("V_INTERP_P2_F32", EncodingFamily::Vintrp), - ("V_LSHLREV_B32", EncodingFamily::Vop2), - ("V_LSHRREV_B32", EncodingFamily::Vop2), ("V_MOV_B32", EncodingFamily::Vop1), ("V_MUL_F32", EncodingFamily::Vop2), - ("V_OR_B32", EncodingFamily::Vop2), - ("V_XOR_B32", EncodingFamily::Vop2), ]; /// A successfully decoded instruction and its location in the input stream. @@ -401,7 +394,14 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco // VOP2: SRC0 in bits 0-8, VSRC1 in bits 9-16, VDST in bits 17-24. let dst = ((first >> 17) & 0xff) as u8; let src1 = ((first >> 9) & 0xff) as u8; - let (src0, len) = vector_src0(first, bytes, op.assembly_name())?; + let (src0, len) = match op.operand_rule() { + // Operand rule `vop2_vgpr2`: SRC0 must select a VGPR (256-511). + OperandRule::Vop2Vgpr2 => { + let (_, src0, _) = vop2_registers(first, op.assembly_name())?; + (VectorSource::Register(src0), 4) + } + _ => vector_src0(first, bytes, op.assembly_name())?, + }; return Ok(( Instruction::VectorAlu { op, @@ -412,48 +412,6 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco len, )); } - if V_LSHLREV_B32.matches(first) { - let (dst, src0, src1) = vop2_registers(first, "v_lshlrev_b32_e32")?; - return Ok(( - Instruction::VectorLshlrevB32 { dst, src0, src1 }, - V_LSHLREV_B32.byte_len(), - )); - } - if V_ASHRREV_I32.matches(first) { - let (dst, src0, src1) = vop2_registers(first, "v_ashrrev_i32_e32")?; - return Ok(( - Instruction::VectorAshrrevI32 { dst, src0, src1 }, - V_ASHRREV_I32.byte_len(), - )); - } - if V_LSHRREV_B32.matches(first) { - let (dst, src0, src1) = vop2_registers(first, "v_lshrrev_b32_e32")?; - return Ok(( - Instruction::VectorLshrrevB32 { dst, src0, src1 }, - V_LSHRREV_B32.byte_len(), - )); - } - if V_AND_B32.matches(first) { - let (dst, src0, src1) = vop2_registers(first, "v_and_b32_e32")?; - return Ok(( - Instruction::VectorAndB32 { dst, src0, src1 }, - V_AND_B32.byte_len(), - )); - } - if V_OR_B32.matches(first) { - let (dst, src0, src1) = vop2_registers(first, "v_or_b32_e32")?; - return Ok(( - Instruction::VectorOrB32 { dst, src0, src1 }, - V_OR_B32.byte_len(), - )); - } - if V_XOR_B32.matches(first) { - let (dst, src0, src1) = vop2_registers(first, "v_xor_b32_e32")?; - return Ok(( - Instruction::VectorXorB32 { dst, src0, src1 }, - V_XOR_B32.byte_len(), - )); - } if V_ADD_F32.matches(first) { let (dst, src0, src1) = vop2_registers(first, "v_add_f32_e32")?; return Ok(( diff --git a/crates/decoder/tests/gfx1030.rs b/crates/decoder/tests/gfx1030.rs index ae9f8b9..94a616d 100644 --- a/crates/decoder/tests/gfx1030.rs +++ b/crates/decoder/tests/gfx1030.rs @@ -432,22 +432,32 @@ fn reference_op(instruction: Instruction) -> Op { target, condition: BranchCondition::Always, }, - Instruction::VectorAndB32 { dst, src0, src1 } => { - Op::Vector(VectorAlu::And, dst, src0, src1) - } - Instruction::VectorLshlrevB32 { dst, src0, src1 } => { - Op::Vector(VectorAlu::ShiftLeft, dst, src0, src1) - } - Instruction::VectorAshrrevI32 { dst, src0, src1 } => { - Op::Vector(VectorAlu::ArithmeticShiftRight, dst, src0, src1) - } - Instruction::VectorLshrrevB32 { dst, src0, src1 } => { - Op::Vector(VectorAlu::ShiftRight, dst, src0, src1) - } - Instruction::VectorOrB32 { dst, src0, src1 } => Op::Vector(VectorAlu::Or, dst, src0, src1), - Instruction::VectorXorB32 { dst, src0, src1 } => { - Op::Vector(VectorAlu::Xor, dst, src0, src1) - } + // The six logical and shift forms migrated from hand-written code + // (#215 M27) keep the reference's VGPR-only VectorAlu ops. + Instruction::VectorAlu { + op: + op @ (VectorAluOp::AndB32 + | VectorAluOp::OrB32 + | VectorAluOp::XorB32 + | VectorAluOp::LshlrevB32 + | VectorAluOp::LshrrevB32 + | VectorAluOp::AshrrevI32), + dst, + src0: VectorSource::Register(src0), + src1, + } => Op::Vector( + match op { + VectorAluOp::AndB32 => VectorAlu::And, + VectorAluOp::OrB32 => VectorAlu::Or, + VectorAluOp::XorB32 => VectorAlu::Xor, + VectorAluOp::LshlrevB32 => VectorAlu::ShiftLeft, + VectorAluOp::LshrrevB32 => VectorAlu::ShiftRight, + _ => VectorAlu::ArithmeticShiftRight, + }, + dst, + src0, + src1, + ), Instruction::VectorAddF32 { dst, src0, src1 } => { Op::Vector(VectorAlu::FloatAdd, dst, src0, src1) } @@ -500,6 +510,7 @@ fn reference_op(instruction: Instruction) -> Op { VectorAluOp::AddNcU32 => VectorInteger::Add, VectorAluOp::SubNcU32 => VectorInteger::Subtract, VectorAluOp::SubrevNcU32 => VectorInteger::SubtractReverse, + _ => panic!("{op:?} decodes only with a VGPR SRC0 (operand rule vop2_vgpr2)"), }, dst, match src0 { diff --git a/crates/isa/generate_semantics.py b/crates/isa/generate_semantics.py index 00db2d0..055f2c6 100755 --- a/crates/isa/generate_semantics.py +++ b/crates/isa/generate_semantics.py @@ -222,6 +222,12 @@ VECTOR_PRIMITIVES = { ("mul24", "unsigned"): "Mul24Unsigned", ("mul_hi24", "signed"): "MulHi24Signed", ("mul_hi24", "unsigned"): "MulHi24Unsigned", + ("and", "bitwise"): "And", + ("or", "bitwise"): "Or", + ("xor", "bitwise"): "Xor", + ("lshl", "bitwise"): "ShiftLeft", + ("lshr", "bitwise"): "ShiftRight", + ("ashr", "signed"): "ArithmeticShiftRight", } # Operand rules the decoder implements, each exactly once. A registry rule must @@ -346,6 +352,26 @@ OPERAND_RULES = { }, "kind": "vector", }, + "vop2_vgpr2": { + "rust": "Vop2Vgpr2", + "enum": "VectorAluOp", + "shape": { + "family": "VOP2", + "dst": {"field": "VDST", "class": "vgpr", "min": 0, "max": 255}, + "src": [ + {"field": "SRC0", "class": "vgpr"}, + {"field": "VSRC1", "class": "vgpr"}, + ], + "max_literals": 0, + }, + # The subset the hand-written decoder accepted before the registry (#215 + # M27): SRC0 must select a VGPR (256-511); the decoder rejects the rest. + "unsupported": { + "src_sgpr", "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_null", "src_inline", + "src_float_inline", "src_special", "src_literal", + }, + "kind": "vector", + }, } VARIANT = re.compile(r"^[A-Z][A-Za-z0-9]*$") @@ -546,7 +572,8 @@ def _check_xml(form, rule, snapshot, errors): fields = [(rule["dst"]["field"], False)] if "dst" in rule else [] fields += [(src["field"], True) for src in rule["src"]] shift = form["operation"] in CONTROL_S1 and len(rule["src"]) > 1 - count_field = rule["src"][1]["field"] if shift else None + # The shift count is S1, or S0 for a form that reads its sources reversed. + count_field = rule["src"][0 if SOURCE_ORDER_KEY in form else 1]["field"] if shift else None for field, is_source in fields: if field not in operands: errors.append(f"{label}: XML has no operand {field}") @@ -939,8 +966,15 @@ def render(registry, snapshot): "/// Registry schema of the generated tables.", f"pub const GENERATED_SCHEMA: u32 = {registry['schema']};", ] + # Rules that share a generated enum (VOP2 `vop2_vgpr` and `vop2_vgpr2`) render + # it once, with the forms of all of them in registry order. + rendered = set() for rule_name in rule_names: - selected = [form for form in forms if form["operands"] == rule_name] + enum = OPERAND_RULES[rule_name]["enum"] + if enum in rendered: + continue + rendered.add(enum) + selected = [form for form in forms if OPERAND_RULES[form["operands"]]["enum"] == enum] out += _render_enum(rule_name, selected, snapshot, positions) variants = registry.get("encoding_variant", []) variant_positions = { @@ -1090,6 +1124,9 @@ def _render_variants(rule_name, variants, registry, snapshot, positions): def _render_enum(rule_name, forms, snapshot, positions): enum = OPERAND_RULES[rule_name]["enum"] kind = OPERAND_RULES[rule_name]["kind"] + rules = sorted({form["operands"] for form in forms}) + if any(OPERAND_RULES[name]["kind"] != kind for name in rules): + raise ValueError(f"{enum}: operand rules {rules} of one enum differ in kind") table = re.sub(r"(? 1 else ''} {', '.join(f'`{name}`' for name in rules)}).", "#[derive(Clone, Copy, Debug, Eq, PartialEq)]", f"pub enum {enum} {{", ] @@ -1238,6 +1276,18 @@ def _render_enum(rule_name, forms, snapshot, positions): f" Self::{form['variant']} => {'true' if SOURCE_ORDER_KEY in form else 'false'}," for form in forms ] + out += [ + " }", + " }", + "", + " /// The operand rule the decoder applies to the 32-bit encoding.", + " pub const fn operand_rule(self) -> OperandRule {", + " match self {", + ] + out += [ + f" Self::{form['variant']} => OperandRule::{OPERAND_RULES[form['operands']]['rust']}," + for form in forms + ] out += [" }", " }", "}"] return out if kind == "vector_compare": diff --git a/crates/isa/semantics/rdna2/vop2.toml b/crates/isa/semantics/rdna2/vop2.toml index 1ccce38..bd91b2a 100644 --- a/crates/isa/semantics/rdna2/vop2.toml +++ b/crates/isa/semantics/rdna2/vop2.toml @@ -223,3 +223,128 @@ wave = "any" operands = "vop2_vgpr" spec = [{ document = "guide", section = "12.7", page = 134 }] verify = ["reference", "independent", "metal", "llvm_encoding"] + +# ---- VOP2 logical and shift forms migrated from hand-written code (#215 M27) ---- +# Per lane under EXEC; no SCC, VCC or EXEC write (guide 12.7). The shifts read +# their sources reversed: D = S1 shifted by S0[4:0]; ASHRREV fills with S1's sign. +# These keep the subset the hand-written decoder accepted: both sources VGPRs. +[operand_rules.vop2_vgpr2] +family = "VOP2" +dst = { field = "VDST", class = "vgpr", min = 0, max = 255 } +src = [ + { field = "SRC0", class = "vgpr" }, + { field = "VSRC1", class = "vgpr" }, +] +max_literals = 0 +unsupported = [ + "src_sgpr", "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_null", "src_inline", + "src_float_inline", "src_special", "src_literal", +] + +[[form]] +name = "V_LSHRREV_B32" +family = "VOP2" +opcode = 22 +variant = "LshrrevB32" +operation = "lshr" +signedness = "bitwise" +carry_in = "none" +width = 32 +shift_count_bits = 5 +source_order = "reversed" +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "vop2_vgpr2" +spec = [{ document = "guide", section = "12.7", page = 133 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_ASHRREV_I32" +family = "VOP2" +opcode = 24 +variant = "AshrrevI32" +operation = "ashr" +signedness = "signed" +carry_in = "none" +width = 32 +shift_count_bits = 5 +source_order = "reversed" +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "vop2_vgpr2" +spec = [{ document = "guide", section = "12.7", page = 133 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_LSHLREV_B32" +family = "VOP2" +opcode = 26 +variant = "LshlrevB32" +operation = "lshl" +signedness = "bitwise" +carry_in = "none" +width = 32 +shift_count_bits = 5 +source_order = "reversed" +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "vop2_vgpr2" +spec = [{ document = "guide", section = "12.7", page = 133 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_AND_B32" +family = "VOP2" +opcode = 27 +variant = "AndB32" +operation = "and" +signedness = "bitwise" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "vop2_vgpr2" +spec = [{ document = "guide", section = "12.7", page = 133 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_OR_B32" +family = "VOP2" +opcode = 28 +variant = "OrB32" +operation = "or" +signedness = "bitwise" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "vop2_vgpr2" +spec = [{ document = "guide", section = "12.7", page = 133 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] + +[[form]] +name = "V_XOR_B32" +family = "VOP2" +opcode = 29 +variant = "XorB32" +operation = "xor" +signedness = "bitwise" +carry_in = "none" +width = 32 +scc = "unchanged" +vcc = "unchanged" +exec = "unchanged" +wave = "any" +operands = "vop2_vgpr2" +spec = [{ document = "guide", section = "12.7", page = 133 }] +verify = ["reference", "independent", "metal", "llvm_encoding"] diff --git a/crates/isa/src/lib.rs b/crates/isa/src/lib.rs index aad5376..e902f62 100644 --- a/crates/isa/src/lib.rs +++ b/crates/isa/src/lib.rs @@ -209,18 +209,6 @@ pub enum Instruction { BranchVccZero { target: usize }, /// SOPP unconditional jump to a stream byte offset. Branch { target: usize }, - /// VOP2 logical left shift with the count in src0. - VectorLshlrevB32 { dst: u8, src0: u8, src1: u8 }, - /// VOP2 logical right shift with the count in src0. - VectorLshrrevB32 { dst: u8, src0: u8, src1: u8 }, - /// VOP2 arithmetic right shift with the count in src0. - VectorAshrrevI32 { dst: u8, src0: u8, src1: u8 }, - /// VOP2 bitwise AND. - VectorAndB32 { dst: u8, src0: u8, src1: u8 }, - /// VOP2 bitwise OR. - VectorOrB32 { dst: u8, src0: u8, src1: u8 }, - /// VOP2 bitwise XOR. - VectorXorB32 { dst: u8, src0: u8, src1: u8 }, /// VOP2 single-precision addition. Execution requires an explicit FP mode. VectorAddF32 { dst: u8, src0: u8, src1: u8 }, /// VOP2 single-precision multiplication. Execution requires an explicit FP mode. @@ -288,12 +276,6 @@ impl Instruction { Self::BranchExecZero { .. } => "s_cbranch_execz", Self::BranchVccZero { .. } => "s_cbranch_vccz", Self::Branch { .. } => "s_branch", - Self::VectorLshlrevB32 { .. } => "v_lshlrev_b32_e32", - Self::VectorLshrrevB32 { .. } => "v_lshrrev_b32_e32", - Self::VectorAshrrevI32 { .. } => "v_ashrrev_i32_e32", - Self::VectorAndB32 { .. } => "v_and_b32_e32", - Self::VectorOrB32 { .. } => "v_or_b32_e32", - Self::VectorXorB32 { .. } => "v_xor_b32_e32", Self::VectorAddF32 { .. } => "v_add_f32_e32", Self::VectorMulF32 { .. } => "v_mul_f32_e32", Self::Export { .. } => "exp", @@ -337,12 +319,6 @@ impl fmt::Display for Instruction { Self::VectorAluVop3 { dst, src0, src1, .. } - | Self::VectorLshlrevB32 { dst, src0, src1 } - | Self::VectorLshrrevB32 { dst, src0, src1 } - | Self::VectorAshrrevI32 { dst, src0, src1 } - | Self::VectorAndB32 { dst, src0, src1 } - | Self::VectorOrB32 { dst, src0, src1 } - | Self::VectorXorB32 { dst, src0, src1 } | Self::VectorAddF32 { dst, src0, src1 } | Self::VectorMulF32 { dst, src0, src1 } => { write!(formatter, " v{dst}, v{src0}, v{src1}") diff --git a/crates/isa/src/semantics.rs b/crates/isa/src/semantics.rs index 3ef28a0..4b38981 100644 --- a/crates/isa/src/semantics.rs +++ b/crates/isa/src/semantics.rs @@ -119,6 +119,18 @@ pub enum VectorBinary { MulHi24Signed, /// Bits 63:32 of `a[23:0] * b[23:0]`. MulHi24Unsigned, + /// `a & b`. + And, + /// `a | b`. + Or, + /// `a ^ b`. + Xor, + /// `a << (b & 31)`. + ShiftLeft, + /// Logical `a >> (b & 31)`. + ShiftRight, + /// Arithmetic (sign-filling) `a >> (b & 31)`. + ArithmeticShiftRight, } /// How the operands are interpreted. `Bitwise` exactly when the operation is logical. @@ -204,6 +216,9 @@ pub enum OperandRule { /// integer -16..64 or a literal word; VSRC1 is a VGPR. Everything else is /// rejected as unsupported. Vop2Vgpr, + /// VOP2 vector, VGPR sources only: VDST is v0-v255; SRC0 and VSRC1 are VGPRs. + /// Everything else (SGPR, inline, literal SRC0) is rejected as unsupported. + Vop2Vgpr2, } /// Evidence a form needs before it counts as verified. diff --git a/crates/isa/src/semantics_gen.rs b/crates/isa/src/semantics_gen.rs index 7f25966..af57a2d 100644 --- a/crates/isa/src/semantics_gen.rs +++ b/crates/isa/src/semantics_gen.rs @@ -1198,7 +1198,7 @@ impl ScalarCompareOp { } } -/// VOP2 operations declared in the semantic registry (operand rule `vop2_vgpr`). +/// VOP2 operations declared in the semantic registry (operand rules `vop2_vgpr`, `vop2_vgpr2`). #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum VectorAluOp { /// `v_mul_i32_i24` (VOP2 opcode 9): signed mul24, SCC = unchanged. @@ -1225,6 +1225,18 @@ pub enum VectorAluOp { SubNcU32, /// `v_subrev_nc_u32` (VOP2 opcode 39): unsigned sub, SCC = unchanged. SubrevNcU32, + /// `v_lshrrev_b32` (VOP2 opcode 22): bitwise lshr, SCC = unchanged. + LshrrevB32, + /// `v_ashrrev_i32` (VOP2 opcode 24): signed ashr, SCC = unchanged. + AshrrevI32, + /// `v_lshlrev_b32` (VOP2 opcode 26): bitwise lshl, SCC = unchanged. + LshlrevB32, + /// `v_and_b32` (VOP2 opcode 27): bitwise and, SCC = unchanged. + AndB32, + /// `v_or_b32` (VOP2 opcode 28): bitwise or, SCC = unchanged. + OrB32, + /// `v_xor_b32` (VOP2 opcode 29): bitwise xor, SCC = unchanged. + XorB32, } /// VectorAluOp by VOP2 OP field value; `None` for undeclared opcodes. @@ -1251,14 +1263,14 @@ const VECTOR_ALU_OP_BY_OPCODE: [Option; 64] = [ Some(VectorAluOp::MinU32), Some(VectorAluOp::MaxU32), None, + Some(VectorAluOp::LshrrevB32), None, + Some(VectorAluOp::AshrrevI32), None, - None, - None, - None, - None, - None, - None, + Some(VectorAluOp::LshlrevB32), + Some(VectorAluOp::AndB32), + Some(VectorAluOp::OrB32), + Some(VectorAluOp::XorB32), Some(VectorAluOp::XnorB32), None, None, @@ -1297,7 +1309,7 @@ const VECTOR_ALU_OP_BY_OPCODE: [Option; 64] = [ impl VectorAluOp { /// Every operation, in registry order. - pub const ALL: [Self; 12] = [ + pub const ALL: [Self; 18] = [ Self::MulI32I24, Self::MulHiI32I24, Self::MulU32U24, @@ -1310,6 +1322,12 @@ impl VectorAluOp { Self::AddNcU32, Self::SubNcU32, Self::SubrevNcU32, + Self::LshrrevB32, + Self::AshrrevI32, + Self::LshlrevB32, + Self::AndB32, + Self::OrB32, + Self::XorB32, ]; /// Selects the operation from a first instruction word: the VOP2 encoding @@ -1336,6 +1354,12 @@ impl VectorAluOp { Self::AddNcU32 => "v_add_nc_u32", Self::SubNcU32 => "v_sub_nc_u32", Self::SubrevNcU32 => "v_subrev_nc_u32", + Self::LshrrevB32 => "v_lshrrev_b32", + Self::AshrrevI32 => "v_ashrrev_i32", + Self::LshlrevB32 => "v_lshlrev_b32", + Self::AndB32 => "v_and_b32", + Self::OrB32 => "v_or_b32", + Self::XorB32 => "v_xor_b32", } } @@ -1354,6 +1378,12 @@ impl VectorAluOp { Self::AddNcU32 => 65, Self::SubNcU32 => 66, Self::SubrevNcU32 => 67, + Self::LshrrevB32 => 68, + Self::AshrrevI32 => 69, + Self::LshlrevB32 => 70, + Self::AndB32 => 71, + Self::OrB32 => 72, + Self::XorB32 => 73, }] } @@ -1372,6 +1402,12 @@ impl VectorAluOp { Self::AddNcU32 => "v_add_nc_u32_e32", Self::SubNcU32 => "v_sub_nc_u32_e32", Self::SubrevNcU32 => "v_subrev_nc_u32_e32", + Self::LshrrevB32 => "v_lshrrev_b32_e32", + Self::AshrrevI32 => "v_ashrrev_i32_e32", + Self::LshlrevB32 => "v_lshlrev_b32_e32", + Self::AndB32 => "v_and_b32_e32", + Self::OrB32 => "v_or_b32_e32", + Self::XorB32 => "v_xor_b32_e32", } } @@ -1390,6 +1426,12 @@ impl VectorAluOp { Self::AddNcU32 => VectorBinary::Add, Self::SubNcU32 => VectorBinary::Sub, Self::SubrevNcU32 => VectorBinary::Sub, + Self::LshrrevB32 => VectorBinary::ShiftRight, + Self::AshrrevI32 => VectorBinary::ArithmeticShiftRight, + Self::LshlrevB32 => VectorBinary::ShiftLeft, + Self::AndB32 => VectorBinary::And, + Self::OrB32 => VectorBinary::Or, + Self::XorB32 => VectorBinary::Xor, } } @@ -1408,6 +1450,36 @@ impl VectorAluOp { Self::AddNcU32 => false, Self::SubNcU32 => false, Self::SubrevNcU32 => true, + Self::LshrrevB32 => true, + Self::AshrrevI32 => true, + Self::LshlrevB32 => true, + Self::AndB32 => false, + Self::OrB32 => false, + Self::XorB32 => false, + } + } + + /// The operand rule the decoder applies to the 32-bit encoding. + pub const fn operand_rule(self) -> OperandRule { + match self { + Self::MulI32I24 => OperandRule::Vop2Vgpr, + Self::MulHiI32I24 => OperandRule::Vop2Vgpr, + Self::MulU32U24 => OperandRule::Vop2Vgpr, + Self::MulHiU32U24 => OperandRule::Vop2Vgpr, + Self::MinI32 => OperandRule::Vop2Vgpr, + Self::MaxI32 => OperandRule::Vop2Vgpr, + Self::MinU32 => OperandRule::Vop2Vgpr, + Self::MaxU32 => OperandRule::Vop2Vgpr, + Self::XnorB32 => OperandRule::Vop2Vgpr, + Self::AddNcU32 => OperandRule::Vop2Vgpr, + Self::SubNcU32 => OperandRule::Vop2Vgpr, + Self::SubrevNcU32 => OperandRule::Vop2Vgpr, + Self::LshrrevB32 => OperandRule::Vop2Vgpr2, + Self::AshrrevI32 => OperandRule::Vop2Vgpr2, + Self::LshlrevB32 => OperandRule::Vop2Vgpr2, + Self::AndB32 => OperandRule::Vop2Vgpr2, + Self::OrB32 => OperandRule::Vop2Vgpr2, + Self::XorB32 => OperandRule::Vop2Vgpr2, } } } @@ -1764,22 +1836,22 @@ impl VectorCompareOp { /// The validated registry row. pub fn semantics(self) -> &'static FormSemantics { &FORMS[match self { - Self::CmpLtI32 => 68, - Self::CmpEqI32 => 69, - Self::CmpLeI32 => 70, - Self::CmpGtI32 => 71, - Self::CmpNeI32 => 72, - Self::CmpGeI32 => 73, - Self::CmpLtU32 => 74, - Self::CmpEqU32 => 75, - Self::CmpLeU32 => 76, - Self::CmpGtU32 => 77, - Self::CmpNeU32 => 78, - Self::CmpGeU32 => 79, - Self::CmpFI32 => 80, - Self::CmpTI32 => 81, - Self::CmpFU32 => 82, - Self::CmpTU32 => 83, + Self::CmpLtI32 => 74, + Self::CmpEqI32 => 75, + Self::CmpLeI32 => 76, + Self::CmpGtI32 => 77, + Self::CmpNeI32 => 78, + Self::CmpGeI32 => 79, + Self::CmpLtU32 => 80, + Self::CmpEqU32 => 81, + Self::CmpLeU32 => 82, + Self::CmpGtU32 => 83, + Self::CmpNeU32 => 84, + Self::CmpGeU32 => 85, + Self::CmpFI32 => 86, + Self::CmpTI32 => 87, + Self::CmpFU32 => 88, + Self::CmpTU32 => 89, }] } @@ -1915,13 +1987,13 @@ impl VectorAluVop3Op { /// The validated registry row of this encoding. pub fn semantics(self) -> &'static FormSemantics { &FORMS[match self { - Self::AddNcU32 => 84, + Self::AddNcU32 => 90, }] } } /// Identity of every registry form and encoding variant, in registry order. -pub const FORM_IDS: [(&str, EncodingFamily); 85] = [ +pub const FORM_IDS: [(&str, EncodingFamily); 91] = [ ("S_ADD_U32", EncodingFamily::Sop2), ("S_SUB_U32", EncodingFamily::Sop2), ("S_ADD_I32", EncodingFamily::Sop2), @@ -1990,6 +2062,12 @@ pub const FORM_IDS: [(&str, EncodingFamily); 85] = [ ("V_ADD_NC_U32", EncodingFamily::Vop2), ("V_SUB_NC_U32", EncodingFamily::Vop2), ("V_SUBREV_NC_U32", EncodingFamily::Vop2), + ("V_LSHRREV_B32", EncodingFamily::Vop2), + ("V_ASHRREV_I32", EncodingFamily::Vop2), + ("V_LSHLREV_B32", EncodingFamily::Vop2), + ("V_AND_B32", EncodingFamily::Vop2), + ("V_OR_B32", EncodingFamily::Vop2), + ("V_XOR_B32", EncodingFamily::Vop2), ("V_CMP_LT_I32", EncodingFamily::Vopc), ("V_CMP_EQ_I32", EncodingFamily::Vopc), ("V_CMP_LE_I32", EncodingFamily::Vopc), @@ -2010,7 +2088,7 @@ pub const FORM_IDS: [(&str, EncodingFamily); 85] = [ ]; /// One validated row per registry form, in registry order. -pub static FORMS: [FormSemantics; 85] = [ +pub static FORMS: [FormSemantics; 91] = [ FormSemantics { name: "S_ADD_U32", family: EncodingFamily::Sop2, @@ -3439,6 +3517,132 @@ pub static FORMS: [FormSemantics; 85] = [ spec: &[SpecRef { document: Document::Guide, section: "12.7", page: 134 }], verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], }, + FormSemantics { + name: "V_LSHRREV_B32", + family: EncodingFamily::Vop2, + opcode: 22, + operation: Operation::LogicalShiftRight, + signedness: Signedness::Bitwise, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 5, + shift_amount: 0, + swap_sources: true, + source_bits: 32, + relation: None, + scc: SccEffect::Unchanged, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::Vop2Vgpr2, + spec: &[SpecRef { document: Document::Guide, section: "12.7", page: 133 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_ASHRREV_I32", + family: EncodingFamily::Vop2, + opcode: 24, + operation: Operation::ArithmeticShiftRight, + signedness: Signedness::Signed, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 5, + shift_amount: 0, + swap_sources: true, + source_bits: 32, + relation: None, + scc: SccEffect::Unchanged, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::Vop2Vgpr2, + spec: &[SpecRef { document: Document::Guide, section: "12.7", page: 133 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_LSHLREV_B32", + family: EncodingFamily::Vop2, + opcode: 26, + operation: Operation::ShiftLeft, + signedness: Signedness::Bitwise, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 5, + shift_amount: 0, + swap_sources: true, + source_bits: 32, + relation: None, + scc: SccEffect::Unchanged, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::Vop2Vgpr2, + spec: &[SpecRef { document: Document::Guide, section: "12.7", page: 133 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_AND_B32", + family: EncodingFamily::Vop2, + opcode: 27, + operation: Operation::And, + signedness: Signedness::Bitwise, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: None, + scc: SccEffect::Unchanged, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::Vop2Vgpr2, + spec: &[SpecRef { document: Document::Guide, section: "12.7", page: 133 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_OR_B32", + family: EncodingFamily::Vop2, + opcode: 28, + operation: Operation::Or, + signedness: Signedness::Bitwise, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: None, + scc: SccEffect::Unchanged, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::Vop2Vgpr2, + spec: &[SpecRef { document: Document::Guide, section: "12.7", page: 133 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "V_XOR_B32", + family: EncodingFamily::Vop2, + opcode: 29, + operation: Operation::Xor, + signedness: Signedness::Bitwise, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + swap_sources: false, + source_bits: 32, + relation: None, + scc: SccEffect::Unchanged, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::Vop2Vgpr2, + spec: &[SpecRef { document: Document::Guide, section: "12.7", page: 133 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, FormSemantics { name: "V_CMP_LT_I32", family: EncodingFamily::Vopc, diff --git a/crates/shader/src/lib.rs b/crates/shader/src/lib.rs index c61a905..2a1745b 100644 --- a/crates/shader/src/lib.rs +++ b/crates/shader/src/lib.rs @@ -9,8 +9,8 @@ pub use graphics::{PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics}; pub use xenora_decoder::Architecture; use xenora_decoder::{ - DecodeError, DecodedInstruction, Instruction, ScalarSource, VectorAluVop3Op, VectorBinary, - VectorCompareOp, VectorSource, + DecodeError, DecodedInstruction, Instruction, ScalarSource, VectorAluOp, VectorAluVop3Op, + VectorBinary, VectorCompareOp, VectorSource, }; /// SGPR index of `vcc_lo`. @@ -156,14 +156,7 @@ impl Op { Binary::FloatAdd | Binary::FloatMul => format!( "as_type(as_type({left}) {symbol} as_type({right}))" ), - Binary::ArithmeticShiftRight => { - format!("as_type(as_type({left}) {symbol} ({right} & 31u))") - } - Binary::ShiftLeft | Binary::ShiftRight => { - format!("{left} {symbol} ({right} & 31u)") - } Binary::Vector(operation) => vector_expression(operation, &left, &right), - _ => format!("{left} {symbol} {right}"), } } Self::MergeLanes { @@ -215,12 +208,6 @@ fn compare_expression(op: VectorCompareOp, left: &str, right: &str) -> String { #[derive(Clone, Copy)] enum Binary { - ShiftLeft, - ShiftRight, - ArithmeticShiftRight, - And, - Or, - Xor, FloatAdd, FloatMul, /// A registry VOP2 integer operation (or its VOP3 encoding), lowered by its @@ -231,12 +218,6 @@ enum Binary { impl Binary { fn operator(self) -> (&'static str, &'static str) { match self { - Self::ShiftLeft => ("lshl.b32", "<<"), - Self::ShiftRight => ("lshr.b32", ">>"), - Self::ArithmeticShiftRight => ("ashr.i32", ">>"), - Self::And => ("and.b32", "&"), - Self::Or => ("or.b32", "|"), - Self::Xor => ("xor.b32", "^"), Self::FloatAdd => ("add.f32", "+"), Self::FloatMul => ("mul.f32", "*"), Self::Vector(operation) => ( @@ -252,6 +233,12 @@ impl Binary { VectorBinary::Mul24Unsigned => "mul24.u32", VectorBinary::MulHi24Signed => "mulhi24.i32", VectorBinary::MulHi24Unsigned => "mulhi24.u32", + VectorBinary::And => "and.b32", + VectorBinary::Or => "or.b32", + VectorBinary::Xor => "xor.b32", + VectorBinary::ShiftLeft => "lshl.b32", + VectorBinary::ShiftRight => "lshr.b32", + VectorBinary::ArithmeticShiftRight => "ashr.i32", }, "", ), @@ -286,6 +273,15 @@ fn vector_expression(operation: VectorBinary, left: &str, right: &str) -> String format!("as_type(mulhi({}, {}))", i24(left), i24(right)) } VectorBinary::MulHi24Unsigned => format!("mulhi({}, {})", u24(left), u24(right)), + VectorBinary::And => format!("{left} & {right}"), + VectorBinary::Or => format!("{left} | {right}"), + VectorBinary::Xor => format!("{left} ^ {right}"), + // MSL leaves shifts by 32 or more undefined; the guide reads S0[4:0]. + VectorBinary::ShiftLeft => format!("{left} << ({right} & 31u)"), + VectorBinary::ShiftRight => format!("{left} >> ({right} & 31u)"), + VectorBinary::ArithmeticShiftRight => { + format!("as_type(as_type({left}) >> ({right} & 31u))") + } } } @@ -689,12 +685,19 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result dst, + // Of the registry VOP2 forms, the contract admits only the six + // logical and shift forms that were hand-written before (#215 M27). + | Instruction::VectorAlu { + op: + VectorAluOp::LshlrevB32 + | VectorAluOp::LshrrevB32 + | VectorAluOp::AshrrevI32 + | VectorAluOp::AndB32 + | VectorAluOp::OrB32 + | VectorAluOp::XorB32, + dst, + .. + } => dst, _ => { return Err(error( "code skipped by a runtime s_cbranch_vccz may contain only v_mov_b32, v_add_nc_u32_e64 and the hand-written integer VOP2 forms", @@ -728,12 +731,6 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result continue, @@ -851,27 +848,6 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result ( - Some(dst), - Op::Binary(Binary::ShiftLeft, read(src1)?, read(src0)?), - ), - Instruction::VectorAshrrevI32 { dst, src0, src1 } => ( - Some(dst), - Op::Binary(Binary::ArithmeticShiftRight, read(src1)?, read(src0)?), - ), - Instruction::VectorLshrrevB32 { dst, src0, src1 } => ( - Some(dst), - Op::Binary(Binary::ShiftRight, read(src1)?, read(src0)?), - ), - Instruction::VectorAndB32 { dst, src0, src1 } => { - (Some(dst), Op::Binary(Binary::And, read(src0)?, read(src1)?)) - } - Instruction::VectorOrB32 { dst, src0, src1 } => { - (Some(dst), Op::Binary(Binary::Or, read(src0)?, read(src1)?)) - } - Instruction::VectorXorB32 { dst, src0, src1 } => { - (Some(dst), Op::Binary(Binary::Xor, read(src0)?, read(src1)?)) - } Instruction::ScalarMoveB32 { dst, src } => { let value = read_scalar(src)?; if dst < 8 { @@ -1084,9 +1060,9 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result KnownBits::constant(bits), - Op::Binary(Binary::And, left, right) => facts[left.0].and(facts[right.0]), - Op::Binary(Binary::Or, left, right) => facts[left.0].or(facts[right.0]), - Op::Binary(Binary::Xor, left, right) => facts[left.0].xor(facts[right.0]), + Op::Binary(Binary::Vector(VectorBinary::And), left, right) => facts[left.0].and(facts[right.0]), + Op::Binary(Binary::Vector(VectorBinary::Or), left, right) => facts[left.0].or(facts[right.0]), + Op::Binary(Binary::Vector(VectorBinary::Xor), left, right) => facts[left.0].xor(facts[right.0]), Op::Binary(operator @ (Binary::FloatAdd | Binary::FloatMul), left, right) => { exact_float_result(operator, facts[left.0], facts[right.0]) .ok_or_else(|| error("FP32 operation is not proven exact for positive normal operands and results"))? diff --git a/docs/shaders/semantic-coverage.md b/docs/shaders/semantic-coverage.md index d759c40..fa89193 100644 --- a/docs/shaders/semantic-coverage.md +++ b/docs/shaders/semantic-coverage.md @@ -31,12 +31,12 @@ acceptance remain outside the verified count. All results concern synthetic fixt | 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 | 20 | 12 | 20 | 20 | 20 | 7 | 7 | 7 | +| VOP2 | 47 | 20 | 18 | 20 | 20 | 20 | 7 | 7 | 11 | | VOP3 | 416 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 12 | | VOP3P | 29 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | | VOP3SDST | 10 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | | VOPC | 190 | 16 | 16 | 16 | 16 | 16 | 0 | 0 | 7 | -| **Total** | 1465 | 104 | 85 | 108 | 104 | 104 | 18 | 18 | 56 | +| **Total** | 1465 | 104 | 91 | 108 | 104 | 104 | 18 | 18 | 60 | ## Unsupported operand variants @@ -48,5 +48,6 @@ The table counts distinct variant names per family across registry operand rules | 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` | | SOPC | `sopc_scalar` | `src_exec`, `src_float_inline`, `src_m0`, `src_special`, `src_ttmp`, `src_vcc`, `two_literals` | | VOP2 | `vop2_vgpr` | `src_exec`, `src_float_inline`, `src_m0`, `src_null`, `src_special`, `src_ttmp`, `src_vcc_hi` | +| VOP2 | `vop2_vgpr2` | `src_exec`, `src_float_inline`, `src_inline`, `src_literal`, `src_m0`, `src_null`, `src_sgpr`, `src_special`, `src_ttmp`, `src_vcc` | | VOP3 | `vop3_vgpr2` | `modifiers`, `src2`, `src_exec`, `src_float_inline`, `src_inline`, `src_literal`, `src_m0`, `src_null`, `src_sgpr`, `src_special`, `src_ttmp`, `src_vcc` | | VOPC | `vopc_vcc` | `src_exec`, `src_float_inline`, `src_m0`, `src_null`, `src_special`, `src_ttmp`, `src_vcc_hi` | diff --git a/docs/shaders/semantic-registry.md b/docs/shaders/semantic-registry.md index 26f94dc..794f094 100644 --- a/docs/shaders/semantic-registry.md +++ b/docs/shaders/semantic-registry.md @@ -151,7 +151,9 @@ fixes the `scc` value: | `lshl_add` / `unsigned` | `carry_out` | `lshl_add_carry_u32` (with `shift_amount`) | no | | `compare` / `signed` or `unsigned` | `relation` | `eq_b32`, `ne_b32` (for both signednesses), `gt_i32`/`gt_u32`, `ge_*`, `lt_*`, `le_*` | no | -Vector forms (operand rule `vop2_vgpr`, kind `vector`) use a separate table: +Vector forms (operand rules `vop2_vgpr` and `vop2_vgpr2`, kind `vector`; both +generate the one `VectorAluOp` enum, whose `operand_rule()` tells the decoder +which rule a form uses) use a separate table: the pair picks the per-lane `VectorBinary` the MSL lowering uses, and `scc` must be `unchanged` (VOP2 integer forms write no SCC, VCC or EXEC): @@ -161,6 +163,15 @@ must be `unchanged` (VOP2 integer forms write no SCC, VCC or EXEC): | `xnor` / `bitwise` | `Xnor` | | `min`, `max` / `signed` or `unsigned` | `MinSigned`, `MinUnsigned`, `MaxSigned`, `MaxUnsigned` | | `mul24`, `mul_hi24` / `signed` or `unsigned` | `Mul24Signed`, `Mul24Unsigned`, `MulHi24Signed`, `MulHi24Unsigned` | +| `and`, `or`, `xor` / `bitwise` | `And`, `Or`, `Xor` | +| `lshl`, `lshr` / `bitwise`, `ashr` / `signed` (with `shift_count_bits = 5`) | `ShiftLeft`, `ShiftRight`, `ArithmeticShiftRight` | + +`vop2_vgpr2` is the VGPR-only subset (SRC0 256-511) that the hand-written decoder +accepted for `v_and_b32`, `v_or_b32`, `v_xor_b32`, `v_lshlrev_b32`, `v_lshrrev_b32` +and `v_ashrrev_i32` before they moved into the registry (#215 M27); widening them +to `vop2_vgpr` would be a behaviour change and needs its own oracle. The three +shifts declare `source_order = "reversed"` (D = S1 shifted by S0[4:0]), so the +generator checks the XML's unsigned count format on SRC0, not VSRC1. VOPC compares (operand rule `vopc_vcc`, kind `vector_compare`: SRC0 a `vector_source` as for VOP2, VSRC1 a VGPR, destination implicitly `vcc_lo`) diff --git a/tests/semantics_generator/test_generate_semantics.py b/tests/semantics_generator/test_generate_semantics.py index fce2781..6a1ab46 100644 --- a/tests/semantics_generator/test_generate_semantics.py +++ b/tests/semantics_generator/test_generate_semantics.py @@ -371,6 +371,25 @@ class Validate(unittest.TestCase): def test_accepts_the_real_registry(self): self.assertEqual(gen.validate(gen.load_registry(), gen.load_snapshot()), []) + def test_a_reversed_shift_takes_its_count_from_src0(self): + # V_ASHRREV_I32: D = S1 >> S0[4:0]; the XML gives SRC0 FMT_NUM_U32 (the + # count) and VSRC1 FMT_NUM_I32. Without the declared reversed order the + # count check lands on VSRC1 and must fail. + reg = gen.load_registry() + form = next(f for f in reg["form"] if f["name"] == "V_ASHRREV_I32") + del form["source_order"] + errors = gen.validate(reg, gen.load_snapshot()) + self.assertIn( + "V_ASHRREV_I32: control operand VSRC1 has XML format FMT_NUM_I32, not FMT_NUM_U32", + errors, + ) + + def test_rules_sharing_an_enum_render_it_once_with_each_forms_rule(self): + text = gen.render(gen.load_registry(), gen.load_snapshot()) + self.assertEqual(text.count("pub enum VectorAluOp {"), 1) + self.assertIn("Self::AndB32 => OperandRule::Vop2Vgpr2,", text) + self.assertIn("Self::MinI32 => OperandRule::Vop2Vgpr,", text) + # ---- top level ---- def test_rejects_wrong_schema(self): From 263284ff4fb91004e66735bd37b3817cf3700947 Mon Sep 17 00:00:00 2001 From: elforeign <324243036+elforeign@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:34:00 -0600 Subject: [PATCH 14/15] isa, scripts: two more registry crash paths become diagnostics (#215) - A variant whose first duplicate base form is incomplete: the completeness check and the XML check now use the same base row (no KeyError). - qa rdna2 inventory and rank report a malformed encoding_variant (missing 'of', non-string operands) as an error with exit 2, not a traceback; the coverage reader checks the field types. Each has a test that fails on the previous code. Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com> --- crates/isa/generate_semantics.py | 9 ++-- scripts/audit/semantic_coverage.py | 8 ++- scripts/qa/__main__.py | 14 +++++- tests/qa/test_rdna2_malformed_registry.py | 49 +++++++++++++++++++ .../test_generate_semantics.py | 9 ++++ 5 files changed, 82 insertions(+), 7 deletions(-) create mode 100644 tests/qa/test_rdna2_malformed_registry.py diff --git a/crates/isa/generate_semantics.py b/crates/isa/generate_semantics.py index 00db2d0..38bf856 100755 --- a/crates/isa/generate_semantics.py +++ b/crates/isa/generate_semantics.py @@ -779,9 +779,10 @@ def _well_formed(rule): ) -def variant_row(registry, variant): +def variant_row(registry, variant, base=None): """The base form re-encoded: its declaration with the variant's identity.""" - base = next(form for form in registry["form"] if form.get("name") == variant["of"]) + if base is None: + base = next(form for form in registry["form"] if form.get("name") == variant["of"]) return dict( base, family=variant["family"], opcode=variant["opcode"], operands=variant["operands"], spec=variant["spec"], verify=variant["verify"], @@ -854,7 +855,9 @@ def _check_variants(registry, rules, documents, snapshot, seen, errors): if FORM_KEYS - set(base): errors.append(f"{label}: not checked, its form {variant['of']} is incomplete") continue - _check_xml(variant_row(registry, variant), rule, snapshot, errors) + # The same base row as the completeness check above (with duplicate + # declarations, the dict keeps the last one). + _check_xml(variant_row(registry, variant, base), 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"]))) diff --git a/scripts/audit/semantic_coverage.py b/scripts/audit/semantic_coverage.py index 498a0e9..f7075a2 100644 --- a/scripts/audit/semantic_coverage.py +++ b/scripts/audit/semantic_coverage.py @@ -182,11 +182,15 @@ def read_declarations(registry, identified): # An encoding variant declares its base form in another encoding family. raw_variants = registry.get("encoding_variant", []) if not isinstance(raw_variants, list) or not all( - isinstance(variant, dict) and {"family", "of", "opcode", "operands"} <= set(variant) + isinstance(variant, dict) + and {"family", "of", "opcode", "operands"} <= set(variant) + and all(isinstance(variant[key], str) for key in ("family", "of", "operands")) + and type(variant["opcode"]) is int for variant in raw_variants ): raise ValueError( - f"{REGISTRY}: every encoding_variant needs family, of, opcode and operands" + f"{REGISTRY}: every encoding_variant needs string family, of and operands" + " and an integer opcode" ) variants = [ {"family": variant["family"], "name": variant["of"], "opcode": variant["opcode"], diff --git a/scripts/qa/__main__.py b/scripts/qa/__main__.py index 8876930..aeb0b48 100644 --- a/scripts/qa/__main__.py +++ b/scripts/qa/__main__.py @@ -172,7 +172,12 @@ def main(argv: list[str] | None = None) -> int: if args.command == "rdna2" and args.action == "rank": from .rdna2_rank import run_rank - return run_rank(_root(), args) + try: + return run_rank(_root(), args) + except ValueError as exc: + # A malformed registry is a diagnostic, not a traceback. + print(f"rdna2: {exc}", file=sys.stderr) + return 2 if args.command == "rdna2" and args.no_float: r.error("--no-float requires the rank action") root = _root() @@ -263,7 +268,12 @@ def main(argv: list[str] | None = None) -> int: else: print(json.dumps(payload, indent=2, sort_keys=True)) return 0 - data = load_inventories(root) + try: + data = load_inventories(root) + except ValueError as exc: + # A malformed registry is a diagnostic, not a traceback. + print(f"rdna2: {exc}", file=sys.stderr) + return 2 inv = summarize_inventory(data) exclude_families: list[str] = [] claimed_paths: list[str] = [] diff --git a/tests/qa/test_rdna2_malformed_registry.py b/tests/qa/test_rdna2_malformed_registry.py new file mode 100644 index 0000000..5cae41b --- /dev/null +++ b/tests/qa/test_rdna2_malformed_registry.py @@ -0,0 +1,49 @@ +"""A malformed encoding variant gives the planner a diagnostic, not a traceback.""" + +import contextlib +import io +import unittest +from unittest import mock + +import qa.__main__ as cli +from qa import rdna2_plan +from audit import semantic_coverage as coverage + + +def malformed_loader(variant): + def load(_root): + registry = { + "schema": 1, + "form": [{"family": "SOP2", "name": "S_ADD_U32", "opcode": 0, + "operands": "scalar", "verify": ["reference"]}], + "operand_rules": {"scalar": {"family": "SOP2", "unsupported": ["two_literals"]}}, + "encoding_variant": [variant], + } + # The real reader, as load_inventories uses it. + coverage.read_declarations(registry, {("SOP2", "S_ADD_U32"): 0}) + raise AssertionError("the malformed variant was accepted") + + return load + + +class MalformedVariant(unittest.TestCase): + def test_inventory_and_rank_report_registry_errors(self): + variants = { + "missing of": {"family": "VOP3", "opcode": 1, "operands": "x"}, + "list operands": {"family": "VOP3", "of": "S_ADD_U32", "opcode": 1, "operands": []}, + } + for action in ("inventory", "rank"): + for name, variant in variants.items(): + with self.subTest(action=action, variant=name): + stderr = io.StringIO() + loader = malformed_loader(variant) + with mock.patch.object(cli, "load_inventories", loader), \ + mock.patch.object(rdna2_plan, "load_inventories", loader), \ + contextlib.redirect_stderr(stderr), contextlib.redirect_stdout(io.StringIO()): + code = cli.main(["rdna2", action]) + self.assertEqual(code, 2) + self.assertIn("encoding_variant needs", stderr.getvalue()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/semantics_generator/test_generate_semantics.py b/tests/semantics_generator/test_generate_semantics.py index fce2781..b2a5a1c 100644 --- a/tests/semantics_generator/test_generate_semantics.py +++ b/tests/semantics_generator/test_generate_semantics.py @@ -945,6 +945,15 @@ class Validate(unittest.TestCase): self.assertTrue(any("missing ['width']" in error for error in errors), errors) self.assertTrue(any("is incomplete" in error for error in errors), errors) + def test_a_variant_of_an_incomplete_first_duplicate_is_a_diagnostic(self): + reg = variants() + base = next(f for f in reg["form"] if f["name"] == reg["encoding_variant"][0]["of"]) + incomplete = copy.deepcopy(base) + del incomplete["width"] + reg["form"].insert(reg["form"].index(base), incomplete) + errors = self.errors(reg) + self.assertTrue(any("missing ['width']" in error for error in errors), errors) + def test_a_non_array_or_non_table_variant_is_a_diagnostic(self): reg = variants() reg["encoding_variant"] = 1 From d6b751976d56a6e29c3068d5f25f04dcec4173b5 Mon Sep 17 00:00:00 2001 From: elforeign <324243036+elforeign@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:35:00 -0600 Subject: [PATCH 15/15] docs, shader, isa: review fixes for the VOP2 logical and shift move (#215) The registry doc states where a reversed shift takes its count and which side masks it, and that a family may have several operand rules; the runtime-region rejection message and a test comment no longer call the six forms hand-written. Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com> --- crates/isa/tests/semantics.rs | 4 ++-- crates/shader/src/lib.rs | 2 +- docs/shaders/semantic-registry.md | 13 +++++++------ 3 files changed, 10 insertions(+), 9 deletions(-) diff --git a/crates/isa/tests/semantics.rs b/crates/isa/tests/semantics.rs index 14826d0..744f085 100644 --- a/crates/isa/tests/semantics.rs +++ b/crates/isa/tests/semantics.rs @@ -102,8 +102,8 @@ fn vector_alu_dispatch_selects_exactly_the_registry_vop2_forms() { assert_eq!(op.swaps_sources(), row.swap_sources); assert_eq!(row.scc, SccEffect::Unchanged); } - // The hand-written VOP2 forms (v_and_b32, v_add_f32, ...) must not be - // dispatched here. + // Exactly the registry VOP2 forms are dispatched here; the hand-written + // ones (v_add_f32, v_mul_f32) must not be. dispatch_selects_exactly(EncodingFamily::Vop2, |word| { VectorAluOp::from_word(word).map(|op| op.semantics().name) }); diff --git a/crates/shader/src/lib.rs b/crates/shader/src/lib.rs index 2a1745b..4007f67 100644 --- a/crates/shader/src/lib.rs +++ b/crates/shader/src/lib.rs @@ -700,7 +700,7 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result dst, _ => { return Err(error( - "code skipped by a runtime s_cbranch_vccz may contain only v_mov_b32, v_add_nc_u32_e64 and the hand-written integer VOP2 forms", + "code skipped by a runtime s_cbranch_vccz may contain only v_mov_b32, v_add_nc_u32_e64 and the VOP2 logical and shift forms", )); } }; diff --git a/docs/shaders/semantic-registry.md b/docs/shaders/semantic-registry.md index 794f094..a655d01 100644 --- a/docs/shaders/semantic-registry.md +++ b/docs/shaders/semantic-registry.md @@ -90,12 +90,13 @@ The root file holds: `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.]`: 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 +- `[operand_rules.]`: an operand rule of one family, shared by its forms. + The decoder implements each rule once, and the generator only accepts a rule + whose declaration matches the decoder's implementation exactly. A family may + have several rules (VOP2 has `vop2_vgpr` and the VGPR-only `vop2_vgpr2`). For + example `sop2_sgpr` is 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 + literal. A rule's `unsupported` list names the encodings it rejects, which stay unsupported instead of being guessed. The list must name exactly the encodings the decoder rejects. @@ -116,7 +117,7 @@ error. | `relation` | Compares only: the relation tested with S0 on the left | `eq`, `lg` (not equal), `gt`, `ge`, `lt`, `le`; required for `compare`, rejected elsewhere | | `source_order` | Vector forms only: `reversed` when the guide computes `op(S1, S0)` (the XML records no operand order); absent otherwise | `reversed` | | `shift_amount` | `lshl_add` only: the fixed left shift of S0 before the add | `1` to `4`; required for `lshl_add`, rejected elsewhere | -| `shift_count_bits` | Shifts only: the low bits of S1 used as the count. The generator masks S1 with it, and the XML must list S1 as unsigned | `5` (log2 of `width`); required for shifts, rejected elsewhere | +| `shift_count_bits` | Shifts only: the low bits of the count source used as the count: S1, or S0 for a vector form with `source_order = "reversed"`. Scalar forms mask it in the generated evaluation, vector forms in their MSL template; the XML must list the count source as unsigned | `5` (log2 of `width`); required for shifts, rejected elsewhere | | `scc` | What the form writes to SCC | `carry_out`, `borrow`, `signed_overflow`, `nonzero`, `relation` (SOPC compares only), `selected_src0` (min and max: S0 won the strict compare, so a tie gives 0), `unchanged` | | `vcc`, `exec` | Effect on VCC and EXEC, stated rather than implied | `unchanged`; `vcc` is `lane_mask` exactly for the VOPC compares (VCC_LO bit n = EXEC[n] & test, fully written; VCC_HI unknown afterwards, see [vector-compare.md](vector-compare.md)); `exec` must be `unchanged` (no EXEC-writing contract yet) | | `wave` | Wave sizes the form is valid in | `wave32` exactly for the VOPC compares (their one entry point is the Wave32 compute fixture ABI, vector-compare.md section 2), `any` for everything else; the decoder has no wave-size input, so no other form may claim `wave32` |