isa: independent LLVM corpus check of gfx1030 identification (#209)

Issue #209 asks for LLVM-generated original samples beyond the existing
oracle cases, with measured coverage and unresolved differences. The
corpus has 317 original instructions assembled by llvm-mc and 6,574 byte
probes built from every metadata form's identifying bits: one with zero
operands, one per extension selector its family can carry, and two with
random operand bits. llvm-objdump decodes each probe, giving LLVM's
instruction and the bytes its decoder consumed (llvm-mc --disassemble
re-encodes, which hides consumed length for MIMG NSA).

The test compares identify with every row and pins per-source class
counts, the 130 disagreeing rows and a digest of the random probes, so
any metadata change fails until reviewed. Disagreements are reported, not
fixed: 18 MIMG names LLVM does not know, 6 VOP3 interpolation forms whose
attribute field 255 is read as a literal, and 21 extension cases on
operand-less or SGPR-pair instructions.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
This commit is contained in:
elforeign committed 2026-11-24 02:05:58 -06:00
1 parent 1212280ab8
commit bf3cca0718
5 files changed
+8047

No files matched your search

+311
View File
@@ -0,0 +1,311 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
"""Regenerate the gfx1030 Wave32 instruction-identification oracle corpus."""
import argparse
from collections import defaultdict
from itertools import islice, zip_longest
from pathlib import Path
import random
import re
import runpy
import subprocess
import tempfile
HERE = Path(__file__).resolve().parent
ISA = HERE.parents[1]
TARGET = ("-triple=amdgcn-amd-amdhsa", "-mcpu=gfx1030", "-mattr=+wavefrontsize32")
BASE_32 = {"SOP1", "SOP2", "SOPC", "SOPK", "SOPP", "VINTRP", "VOP1", "VOP2", "VOPC"}
ENCODING = re.compile(r"^\s*(.*?)\s*; encoding: \[([^\]]+)\]", re.MULTILINE)
SECTION = re.compile(r"^Disassembly of section \.text\.(\d+):")
# Instruction text, offset, consumed words, then optional trailing text: a
# branch-target annotation such as `<.text+0x841c>` or an LLVM warning such as
# `; Warning: ... scalar reg isn't aligned`, neither of which stops decoding.
INSTRUCTION = re.compile(r"^\t(.*?)\s*// ([0-9A-F]{12}): ((?:[0-9A-F]{8}(?: |$))+)(.*)$")
def llvm(executable, *args, source=None):
return subprocess.run(
[executable, *TARGET, "-show-encoding", *args],
input=source, text=True, capture_output=True, check=True,
)
def encodings(output):
for text, bytes_text in ENCODING.findall(output):
yield " ".join(text.split()), bytes(int(token, 16) for token in bytes_text.split(","))
def disassemble_batch(llvm_bin, blobs):
"""LLVM's decode of the first instruction of each blob.
Each blob goes into its own section of one object built from `.byte`
directives; llvm-objdump disassembles every section from offset zero and
prints the words it consumed. That length is what the decoder read, not the
length of a re-encoding (llvm-mc --disassemble re-encodes, which shortens
inconsistent MIMG NSA probes). Returns (text, consumed bytes) or None when
LLVM cannot decode offset zero (it prints `.long`/`.short`/`.byte`).
"""
source = []
for index, blob in enumerate(blobs):
source.append(f'.section .text.{index},"ax"')
if blob:
source.append(".byte " + ",".join(f"0x{byte:02x}" for byte in blob))
with tempfile.TemporaryDirectory() as directory:
assembly_path = Path(directory) / "probes.s"
object_path = Path(directory) / "probes.o"
assembly_path.write_text("\n".join(source) + "\n")
subprocess.run(
[llvm_bin / "llvm-mc", *TARGET, "-filetype=obj", assembly_path, "-o", object_path],
check=True, capture_output=True,
)
dump = subprocess.run(
[llvm_bin / "llvm-objdump", "-d", "--mcpu=gfx1030", "--mattr=+wavefrontsize32", object_path],
check=True, capture_output=True, text=True,
).stdout
first = {}
section = None
for line in dump.splitlines():
header = SECTION.match(line)
if header:
section = int(header.group(1))
continue
instruction = INSTRUCTION.match(line)
if section is None or section in first or not instruction:
continue
text, offset, words, warning = instruction.groups()
if int(offset, 16) != 0:
continue
if text.startswith((".long", ".short", ".byte")):
first[section] = None
else:
text = " ".join(text.split())
warning = warning.strip()
if warning.startswith(";"):
text += f" [LLVM: {warning.lstrip('; ')}]"
first[section] = (text, 4 * len(words.split()))
return [first.get(index) for index in range(len(blobs))]
CRASHED = "crashed"
def disassemble_all(llvm_bin, blobs):
"""Batches of 128; a batch that crashes llvm-objdump is split until the
crashing blobs are isolated, and each of those is reported as CRASHED."""
results = []
for start in range(0, len(blobs), 128):
results.extend(_isolate(llvm_bin, blobs[start:start + 128]))
return results
def _isolate(llvm_bin, blobs):
try:
return disassemble_batch(llvm_bin, blobs)
except subprocess.CalledProcessError as error:
if error.returncode != -11:
raise
if len(blobs) == 1:
return [CRASHED]
half = len(blobs) // 2
return _isolate(llvm_bin, blobs[:half]) + _isolate(llvm_bin, blobs[half:])
def extension(text, length, family):
mnemonic = text.split()[0]
if "dpp8:" in text:
return "dpp8fi" if "fi:1" in text else "dpp8"
if mnemonic.endswith("_dpp"):
return "dpp16"
if mnemonic.endswith("_sdwa"):
return "sdwa"
base_bytes = 4 if family in BASE_32 else 8
if mnemonic.endswith("_e64"):
base_bytes = 8
extra = length - base_bytes
if mnemonic.startswith("image_") and extra > 0:
return f"nsa{extra // 4}"
# After excluding vector control and image addresses, an extra dword
# carrying a numeric operand is the literal (including mandatory literals).
if extra == 4 and re.search(r"(?:,|\s)\s*-?(?:0x[\da-f]+|\d+)(?=,|\s|$|/\*)", text):
return "literal"
if extra > 0:
raise ValueError(f"unclassified LLVM extension: {length} bytes {text}")
return "-"
def assembly(executable):
source = HERE / "corpus.s"
families = [
line.split("//", 1)[1].strip()
for line in source.read_text().splitlines()
if line.split("//", 1)[0].strip()
]
result = llvm(executable, source)
if result.stderr:
raise ValueError(result.stderr)
decoded = list(encodings(result.stdout))
if len(decoded) != len(families):
raise ValueError("LLVM must emit exactly one encoding per assembly line")
return [(family, text, data) for family, (text, data) in zip(families, decoded)]
def metadata_forms():
snapshot = ISA / "data/rdna2.jsonl"
project = runpy.run_path(str(ISA / "generate_rdna2_meta.py"))["forms_from_snapshot"]
return project(snapshot.read_text())[2]
def probes():
# The normalized snapshot stores instruction variants and encoding records
# separately. Reuse its projection to obtain identifiers, widths and labels
# for coverage. The projected mnemonic and extensions are never consulted.
forms = metadata_forms()
rng = random.Random(209)
for form in forms:
width = form["bytes"]
# One probe with every non-identifying bit zero (operands s0/v0, no
# modifiers), then two with seeded random operand bits.
yield "zero", form["encoding"].upper(), form["bits"].to_bytes(width, "little") + bytes(16)
for _ in range(2):
value = form["bits"] | (rng.getrandbits(width * 8) & ~form["mask"])
yield "random", form["encoding"].upper(), value.to_bytes(width, "little") + rng.randbytes(16)
# Extension selectors from the RDNA 2 ISA reference: the SRC0 (VOP1, VOP2,
# VOPC, VOP3*) or SSRC0 (SOP1, SOP2, SOPC) value that makes one extra dword
# follow the base encoding.
SELECTORS = {"literal": 0xFF, "sdwa": 0xF9, "dpp16": 0xFA, "dpp8": 0xE9, "dpp8fi": 0xEA}
# Instructions whose last dword is a legal control word for each extension;
# LLVM assembles them, so the control words are LLVM's own.
CONTROL_SOURCES = {
"sdwa": "v_add_f32_sdwa v0, v0, v0 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:DWORD src1_sel:DWORD",
"sdwa-vop1": "v_mov_b32_sdwa v0, v0 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:DWORD",
"sdwa-vopc": "v_cmp_eq_f32_sdwa vcc_lo, v0, v0 src0_sel:DWORD src1_sel:DWORD",
"dpp16": "v_add_f32_dpp v0, v0, v0 quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0xf",
"dpp8": "v_add_f32_dpp v0, v0, v0 dpp8:[0,1,2,3,4,5,6,7]",
"dpp8fi": "v_add_f32_dpp v0, v0, v0 dpp8:[0,1,2,3,4,5,6,7] fi:1",
}
LITERAL = (0x12345678).to_bytes(4, "little")
def controls(executable):
source = "\n".join(CONTROL_SOURCES.values()) + "\n"
decoded = list(encodings(llvm(executable, source=source).stdout))
return {name: data[-4:] for name, (_, data) in zip(CONTROL_SOURCES, decoded)}
def extension_probes(executable, forms):
"""Every form's zero-operand base with each extension selector its family
can carry, followed by a legal control dword or literal. LLVM decides which
combinations are instructions; the metadata's extension list is not read."""
control = controls(executable)
for form in forms:
family = form["encoding"].upper()
base = form["bits"]
if family in ("VOP1", "VOP2", "VOPC"):
kinds = ["literal", "sdwa", "dpp16", "dpp8", "dpp8fi"]
shift = 0
elif family in ("VOP3", "VOP3SDST", "VOP3P"):
kinds, shift = ["literal"], 32
elif family in ("SOP1", "SOP2", "SOPC"):
kinds, shift = ["literal"], 0
else:
continue
field = 0x1FF if shift == 32 or family.startswith("VOP") else 0xFF
if base & form["mask"] & (field << shift):
continue # SRC0/SSRC0 is part of this form's identifier
for kind in kinds:
value = (base & ~(field << shift)) | (SELECTORS[kind] << shift)
if kind == "literal":
trailer = LITERAL
elif kind == "sdwa" and family in ("VOPC", "VOP1"):
trailer = control[f"sdwa-{family.lower()}"]
else:
trailer = control[kind]
yield kind, family, value.to_bytes(form["bytes"], "little") + trailer + bytes(12)
def truncations(entries):
by_family = defaultdict(list)
for entry in entries:
by_family[entry[0]].append(entry)
groups = [
sorted(group, key=lambda entry: -len(entry[2]))
for _, group in sorted(by_family.items())
]
interleaved = (entry for batch in zip_longest(*groups) for entry in batch if entry)
yield from islice(interleaved, 40)
def decoded_columns(text, length, family):
return text.split()[0], str(length), extension(text, length, family)
def generate(llvm_bin):
rows = []
entries = assembly(llvm_bin / "llvm-mc")
for family, text, data in entries:
rows.append(("asm", data.hex(), *decoded_columns(text, len(data), family), f"{family} {text}"))
probe_list = list(probes()) + [
(f"ext-{kind}", family, data)
for kind, family, data in extension_probes(llvm_bin / "llvm-mc", metadata_forms())
]
cut_list = [
(family, text, data, data[:size])
for family, text, data in truncations(entries)
for size in range(0, len(data), 4)
]
decoded_all = disassemble_all(llvm_bin, [data for _, _, data in probe_list] + [cut for *_, cut in cut_list])
for (kind, family, data), decoded in zip(probe_list, decoded_all):
if decoded is None:
columns = ("invalid", "0", "-")
note = "LLVM cannot decode offset zero"
elif decoded == CRASHED:
columns = ("crashed", "0", "-")
note = "llvm-objdump crashed (SIGSEGV)"
elif "/*Invalid" not in decoded[0]:
text, length = decoded
columns = decoded_columns(text, length, family)
note = text
if decoded not in (None, CRASHED) and "/*Invalid" in decoded[0]:
# LLVM decodes the words (so it knows the opcode and the length)
# but flags an operand the instruction cannot take, for example an
# SGPR or literal for a VGPR-only source.
text, length = decoded
mnemonic, *rest = decoded_columns(text, length, family)
columns = (f"invalid-operand:{mnemonic}", *rest)
note = text
source = f"probe-{kind}" if kind in ("zero", "random") else "probe-ext"
if kind.startswith("ext-"):
note = f"{kind[4:]} {note}"
rows.append((source, data.hex(), *columns, f"{family} {note}"))
for (family, text, data, prefix), decoded in zip(cut_list, decoded_all[len(probe_list):]):
if decoded is None:
observed = "cannot decode" if prefix else "no instruction"
elif decoded == CRASHED:
observed = "crashed (SIGSEGV)"
else:
observed = f"decoded {decoded[1]} bytes: {decoded[0]}"
note = f"{family} LLVM {observed} | cut {data.hex()} {text}"
rows.append(("truncation", prefix.hex(), "truncated", "0", "-", note))
header = "source\thex\tllvm_mnemonic\tllvm_len\tllvm_ext\tnote\n"
return header + "".join("\t".join(row) + "\n" for row in sorted(rows))
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--llvm-bin", required=True, type=Path)
parser.add_argument("--check", action="store_true")
args = parser.parse_args()
data = generate(args.llvm_bin.resolve())
output = HERE / "corpus.tsv"
if args.check:
if output.read_bytes() != data.encode():
parser.exit(1, f"{output} differs from the LLVM output\n")
else:
output.write_bytes(data.encode())
if __name__ == "__main__":
main()
+320
View File
@@ -0,0 +1,320 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Original gfx1030 Wave32 instruction identification cases.
s_mov_b32 s105, s0 // SOP1
s_mov_b32 exec_lo, -16 // SOP1
s_mov_b32 m0, 64 // SOP1
s_mov_b32 vcc_hi, 0xdeadbeef // SOP1
s_mov_b64 exec, vcc // SOP1
s_mov_b64 vcc, 0x12345678 // SOP1
s_not_b32 s0, s105 // SOP1
s_not_b64 s[104:105], s[0:1] // SOP1
s_brev_b32 s105, m0 // SOP1
s_bcnt1_i32_b32 s0, exec_lo // SOP1
s_ff1_i32_b32 s105, -16 // SOP1
s_flbit_i32_b32 s105, 0x80000100 // SOP1
s_sext_i32_i8 s0, s105 // SOP1
s_sext_i32_i16 s105, s0 // SOP1
s_getpc_b64 s[104:105] // SOP1
s_setpc_b64 s[0:1] // SOP1
s_and_saveexec_b64 s[0:1], s[104:105] // SOP1
s_wqm_b64 s[104:105], exec // SOP1
s_add_u32 s105, s0, 0x12345678 // SOP2
s_add_u32 s0, 0xdeadbeef, s105 // SOP2
s_add_i32 s0, -16, 64 // SOP2
s_sub_i32 s105, s0, m0 // SOP2
s_subb_u32 s0, vcc_lo, exec_lo // SOP2
s_min_i32 s105, s104, -16 // SOP2
s_max_u32 s0, s105, 64 // SOP2
s_cselect_b32 s105, -1, s0 // SOP2
s_and_b64 s[104:105], exec, vcc // SOP2
s_or_b64 vcc, s[0:1], exec // SOP2
s_xor_b32 s0, s0, 0xdeadbeef // SOP2
s_nand_b32 s105, m0, vcc_lo // SOP2
s_lshl_b32 s0, s105, 31 // SOP2
s_lshr_b64 s[104:105], s[0:1], 63 // SOP2
s_ashr_i32 s105, 0x87654321, 31 // SOP2
s_mul_i32 s0, s105, -16 // SOP2
s_bfe_u32 s105, s0, 0x0010000f // SOP2
s_cmp_eq_i32 s0, s105 // SOPC
s_cmp_lg_i32 m0, -16 // SOPC
s_cmp_gt_i32 64, s105 // SOPC
s_cmp_ge_i32 s105, 0xdeadbeef // SOPC
s_cmp_lt_u32 0x12345678, exec_hi // SOPC
s_cmp_le_u32 vcc_lo, 64 // SOPC
s_cmp_eq_u64 s[104:105], vcc // SOPC
s_bitcmp0_b32 s105, 31 // SOPC
s_bitcmp1_b64 exec, 63 // SOPC
s_movk_i32 s0, -32768 // SOPK
s_movk_i32 s105, 32767 // SOPK
s_movk_i32 m0, -1 // SOPK
s_addk_i32 s105, -32768 // SOPK
s_mulk_i32 s0, 32767 // SOPK
s_cmpk_eq_i32 s105, -32768 // SOPK
s_cmpk_lg_u32 s0, 65535 // SOPK
s_getreg_b32 s105, hwreg(HW_REG_MODE) // SOPK
s_setreg_b32 hwreg(HW_REG_MODE, 4, 8), s0 // SOPK
s_setreg_imm32_b32 hwreg(HW_REG_MODE, 8, 16), 0xdeadbeef // SOPK
s_setreg_imm32_b32 hwreg(HW_REG_MODE), 0 // SOPK
s_nop 15 // SOPP
s_endpgm 0 // SOPP
s_branch -32768 // SOPP
s_cbranch_scc0 32767 // SOPP
s_cbranch_scc1 -1 // SOPP
s_cbranch_vccz 0 // SOPP
s_cbranch_vccnz 3 // SOPP
s_cbranch_execz 7 // SOPP
s_cbranch_execnz -7 // SOPP
s_barrier // SOPP
s_waitcnt vmcnt(0) lgkmcnt(1) expcnt(7) // SOPP
s_sleep 127 // SOPP
s_trap 255 // SOPP
s_load_dword s105, s[0:1], 1048575 // SMEM
s_load_dword s0, s[104:105], -1048576 // SMEM
s_load_dwordx2 s[104:105], s[0:1], 0 glc // SMEM
s_load_dwordx4 s[0:3], s[100:101], s105 // SMEM
s_load_dwordx8 s[96:103], s[0:1], 7 // SMEM
s_load_dwordx16 s[0:15], s[104:105], 16 // SMEM
s_buffer_load_dword s105, s[0:3], 4095 // SMEM
s_buffer_load_dwordx2 s[104:105], s[0:3], 0 // SMEM
s_buffer_load_dwordx4 s[0:3], s[100:103], s105 // SMEM
s_memtime s[104:105] // SMEM
s_dcache_inv // SMEM
v_mov_b32_e32 v255, v0 // VOP1
v_mov_b32_e32 v0, s105 // VOP1
v_mov_b32_e32 v255, 0xdeadbeef // VOP1
v_mov_b32_e32 v0, -16 // VOP1
v_mov_b32_e32 v255, 64 // VOP1
v_mov_b32_e32 v0, 0.5 // VOP1
v_mov_b32_e32 v255, -4.0 // VOP1
v_mov_b32_e32 v0, 0.15915494 // VOP1
v_cvt_f32_i32_e32 v255, v0 // VOP1
v_cvt_f32_u32_e32 v0, v255 // VOP1
v_cvt_i32_f32_e32 v255, 0x3f800001 // VOP1
v_rcp_f32_e32 v0, v255 // VOP1
v_sqrt_f32_e32 v255, v0 // VOP1
v_readfirstlane_b32 s105, v255 // VOP1
v_mov_b32_sdwa v255, v0 dst_sel:BYTE_3 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0 // VOP1
v_mov_b32_dpp v0, v255 quad_perm:[3,2,1,0] row_mask:0x1 bank_mask:0x8 // VOP1
v_mov_b32_dpp v255, v0 row_shl:15 bound_ctrl:1 // VOP1
v_mov_b32_dpp v0, v255 row_share:15 // VOP1
v_mov_b32_dpp v255, v0 dpp8:[7,6,5,4,3,2,1,0] fi:0 // VOP1
v_mov_b32_dpp v0, v255 dpp8:[0,0,0,0,7,7,7,7] fi:1 // VOP1
v_mov_b32_e32 v255, 0x3e22f983 // VOP1
v_add_f32_e32 v0, v255, v0 // VOP2
v_sub_f32_e32 v255, 0x3f800001, v0 // VOP2
v_subrev_f32_e32 v0, s105, v255 // VOP2
v_mul_f32_e32 v255, -4.0, v0 // VOP2
v_mul_i32_i24_e32 v0, -16, v255 // VOP2
v_mul_u32_u24_e32 v255, 64, v0 // VOP2
v_min_f32_e32 v0, 0.5, v255 // VOP2
v_max_f32_e32 v255, 0.15915494, v0 // VOP2
v_lshrrev_b32_e32 v0, 31, v255 // VOP2
v_ashrrev_i32_e32 v255, 31, v0 // VOP2
v_lshlrev_b32_e32 v0, 31, v255 // VOP2
v_and_b32_e32 v255, 0xdeadbeef, v0 // VOP2
v_or_b32_e32 v0, m0, v255 // VOP2
v_xor_b32_e32 v255, vcc_lo, v0 // VOP2
v_add_nc_u32_e32 v0, exec_lo, v255 // VOP2
v_fmamk_f32 v255, v0, 0x3f800001, v255 // VOP2
v_fmaak_f32 v0, v255, v0, 0xdeadbeef // VOP2
v_add_f32_sdwa v255, v0, v255 dst_sel:WORD_1 dst_unused:UNUSED_SEXT src0_sel:BYTE_0 src1_sel:WORD_0 // VOP2
v_add_f32_dpp v0, v255, v0 row_shl:7 bound_ctrl:1 // VOP2
v_mul_f32_dpp v255, v0, v255 dpp8:[1,2,3,4,5,6,7,0] fi:1 // VOP2
v_cmp_eq_f32_e32 vcc_lo, 0.5, v255 // VOPC
v_cmp_lt_f32_e32 vcc_lo, -4.0, v0 // VOPC
v_cmp_ge_f32_e32 vcc_lo, 0x3f800001, v255 // VOPC
v_cmp_ne_u32_e32 vcc_lo, 0xdeadbeef, v0 // VOPC
v_cmp_gt_i32_e32 vcc_lo, -16, v255 // VOPC
v_cmp_le_i32_e32 vcc_lo, s105, v0 // VOPC
v_cmpx_eq_u32_e32 64, v255 // VOPC
v_cmp_eq_i32_sdwa s105, v255, v0 src0_sel:WORD_0 src1_sel:BYTE_3 // VOPC
v_cmp_lt_u32_sdwa vcc_lo, v0, v255 src0_sel:BYTE_1 src1_sel:WORD_1 // VOPC
v_cmp_class_f32_e32 vcc_lo, v0, v255 // VOPC
v_add_f32_e64 v255, -v0, |v255| clamp // VOP3
v_add_f32_e64 v0, 0x3f800001, v255 // VOP3
v_mul_f32_e64 v255, v0, 0.5 mul:2 // VOP3
v_fma_f32 v0, v255, 0x3f800001, v0 // VOP3
v_fma_f32 v255, -v0, |v255|, -4.0 // VOP3
v_mad_u32_u24 v0, v255, 64, v0 // VOP3
v_mad_i32_i24 v255, v0, -16, v255 // VOP3
v_min3_f32 v0, v255, v0, 0.5 // VOP3
v_max3_i32 v255, v0, v255, -16 // VOP3
v_med3_u32 v0, v255, v0, 64 // VOP3
v_bfe_u32 v255, v0, 31, 1 // VOP3
v_bfe_i32 v0, v255, 0, 32 // VOP3
v_bfi_b32 v255, v0, v255, 0x12345678 // VOP3
v_alignbit_b32 v0, v255, v0, 31 // VOP3
v_cmp_eq_u32_e64 s105, v255, 0xdeadbeef // VOP3
v_readlane_b32 s105, v255, 31 // VOP3
v_writelane_b32 v255, s105, 31 // VOP3
v_add_co_u32 v255, s105, v0, v255 // VOP3SDST
v_add_co_u32 v0, vcc_lo, 0xdeadbeef, v255 // VOP3SDST
v_sub_co_u32 v255, s0, v0, v255 // VOP3SDST
v_subrev_co_u32 v0, s105, v255, v0 // VOP3SDST
v_div_scale_f32 v255, s105, v0, v0, v255 // VOP3SDST
v_div_scale_f64 v[254:255], vcc_lo, v[0:1], v[0:1], v[2:3] // VOP3SDST
v_pk_add_f16 v255, v0, v255 op_sel:[1,0] op_sel_hi:[0,1] // VOP3P
v_pk_mul_f16 v0, v255, 0x3c01 // VOP3P
v_pk_fma_f16 v255, v0, v255, 0x3c01 // VOP3P
v_pk_add_i16 v0, v255, 64 clamp // VOP3P
v_pk_sub_i16 v255, v0, -16 // VOP3P
v_pk_mul_lo_u16 v0, v255, v0 // VOP3P
v_pk_min_i16 v255, v0, v255 // VOP3P
v_pk_max_u16 v0, v255, v0 // VOP3P
v_pk_lshlrev_b16 v255, 15, v0 // VOP3P
v_dot2_f32_f16 v0, v255, v0, 0.5 // VOP3P
v_interp_p1_f32 v255, v0, attr32.w // VINTRP
v_interp_p2_f32 v0, v255, attr0.x // VINTRP
v_interp_mov_f32 v255, p0, attr32.y // VINTRP
v_interp_mov_f32 v0, p10, attr1.z // VINTRP
v_interp_p1_f32 v0, v255, attr1.y // VINTRP
v_interp_p2_f32 v255, v0, attr31.z // VINTRP
ds_write_b32 v255, v0 offset:65535 // DS
ds_read_b32 v0, v255 offset:65535 // DS
ds_write_b8 v0, v255 offset:0 // DS
ds_write_b16 v255, v0 offset:32768 // DS
ds_read_u8 v0, v255 offset:1 // DS
ds_read_i16 v255, v0 offset:65534 // DS
ds_write_b64 v255, v[254:255] offset:8 // DS
ds_read_b64 v[0:1], v255 offset:16 // DS
ds_write2_b32 v0, v255, v0 offset0:255 offset1:0 // DS
ds_read2_b32 v[254:255], v0 offset0:0 offset1:255 // DS
ds_add_u32 v255, v0 offset:65535 // DS
ds_add_rtn_u32 v0, v255, v0 offset:1 // DS
ds_cmpst_b32 v0, v255, v0 offset:32 // DS
ds_bpermute_b32 v255, v0, v255 // DS
ds_permute_b32 v0, v255, v0 // DS
buffer_load_dword v255, off, s[100:103], 0 offset:4095 // MUBUF
buffer_load_dword v0, v255, s[0:3], s105 offen offset:1 // MUBUF
buffer_load_dword v255, v0, s[0:3], 0 idxen // MUBUF
buffer_load_dword v0, v[254:255], s[0:3], 0 idxen offen glc slc // MUBUF
buffer_load_ubyte v255, off, s[0:3], 0 // MUBUF
buffer_load_sshort v0, off, s[0:3], 0 // MUBUF
buffer_load_dwordx2 v[254:255], off, s[0:3], 0 offset:4095 // MUBUF
buffer_load_dwordx3 v[0:2], off, s[0:3], 0 // MUBUF
buffer_store_dwordx4 v[252:255], off, s[100:103], 0 offset:4095 // MUBUF
buffer_store_byte v0, v255, s[0:3], s105 offen // MUBUF
buffer_atomic_add v255, off, s[0:3], 0 glc // MUBUF
buffer_atomic_cmpswap v[254:255], off, s[0:3], 0 glc // MUBUF
tbuffer_load_format_x v255, off, s[100:103], 0 format:[BUF_FMT_32_UINT] offset:4095 // MTBUF
tbuffer_load_format_xy v[0:1], v255, s[0:3], s105 format:[BUF_FMT_32_32_FLOAT] offen // MTBUF
tbuffer_load_format_xyz v[253:255], off, s[0:3], 0 format:[BUF_FMT_32_32_32_FLOAT] // MTBUF
tbuffer_load_format_xyzw v[0:3], off, s[0:3], 0 format:[BUF_FMT_32_32_32_32_FLOAT] // MTBUF
tbuffer_store_format_x v255, v0, s[100:103], 0 format:[BUF_FMT_32_SINT] idxen // MTBUF
tbuffer_store_format_xy v[254:255], off, s[0:3], 0 format:[BUF_FMT_32_32_UINT] // MTBUF
tbuffer_store_format_xyz v[0:2], off, s[0:3], 0 format:[BUF_FMT_32_32_32_UINT] // MTBUF
tbuffer_store_format_xyzw v[252:255], off, s[0:3], 0 format:[BUF_FMT_32_32_32_32_UINT] offset:4095 // MTBUF
tbuffer_load_format_d16_xy v255, off, s[0:3], 0 format:[BUF_FMT_16_16_FLOAT] // MTBUF
tbuffer_store_format_d16_xyzw v[254:255], off, s[0:3], 0 format:[BUF_FMT_16_16_16_16_FLOAT] // MTBUF
image_load v255, v0, s[96:103] dmask:0x1 dim:SQ_RSRC_IMG_1D unorm // MIMG
image_load_mip v[254:255], v[0:2], s[0:7] dmask:0x9 dim:SQ_RSRC_IMG_2D unorm // MIMG
image_store v255, v[0:1], s[0:7] dmask:0x8 dim:SQ_RSRC_IMG_2D unorm // MIMG
image_sample v[252:255], [v255,v0], s[0:7], s[100:103] dmask:0xf dim:SQ_RSRC_IMG_2D // MIMG
image_sample v255, [v0,v128,v255], s[0:7], s[8:11] dmask:0x1 dim:SQ_RSRC_IMG_3D // MIMG
image_sample_c v[254:255], [v255,v5,v1,v0], s[0:7], s[8:11] dmask:0x5 dim:SQ_RSRC_IMG_2D_ARRAY // MIMG
image_sample_c_l v255, [v0,v2,v4,v6,v255], s[0:7], s[8:11] dmask:0x1 dim:SQ_RSRC_IMG_2D_ARRAY // MIMG
image_sample_d v255, [v0,v2,v4,v6,v8,v255], s[0:7], s[8:11] dmask:0x1 dim:SQ_RSRC_IMG_2D // MIMG
image_sample_d v0, [v255,v2,v4,v6,v8,v10,v12,v14,v16], s[0:7], s[8:11] dmask:0x1 dim:SQ_RSRC_IMG_3D // MIMG
image_gather4 v[252:255], v[0:1], s[0:7], s[8:11] dmask:0x8 dim:SQ_RSRC_IMG_2D // MIMG
image_atomic_add v255, v[0:1], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc // MIMG
image_sample_d_cl v255, [v0,v2,v4,v6,v8,v10,v12,v14,v16,v18], s[0:7], s[8:11] dmask:0x1 dim:SQ_RSRC_IMG_3D // MIMG
image_sample_c_d_cl v0, [v0,v2,v4,v6,v8,v10,v12,v14,v16,v18,v20], s[0:7], s[8:11] dmask:0x1 dim:SQ_RSRC_IMG_3D // MIMG
exp mrt0 v255, off, off, v0 done // EXP
exp mrt7 off, v255, v0, off // EXP
exp pos0 v0, v255, v0, v255 done // EXP
exp pos3 v255, v0, v255, v0 // EXP
exp param0 v255, off, v0, off // EXP
exp param31 v0, v255, off, off // EXP
exp null off, off, off, off done // EXP
flat_load_dword v255, v[0:1] offset:2047 // FLAT
flat_load_dword v0, v[254:255] offset:1024 // FLAT
flat_load_ubyte v255, v[0:1] offset:0 // FLAT
flat_load_sbyte v0, v[254:255] glc // FLAT
flat_load_dwordx2 v[254:255], v[0:1] slc // FLAT
flat_load_dwordx4 v[0:3], v[254:255] // FLAT
flat_store_dword v[254:255], v0 offset:2047 // FLAT
flat_store_short v[0:1], v255 offset:1 // FLAT
flat_atomic_add v255, v[0:1], v255 glc // FLAT
flat_atomic_swap v[254:255], v0 // FLAT
global_load_dword v255, v[0:1], off offset:-2048 // GLOBAL
global_load_dword v0, v255, s[104:105] offset:2047 // GLOBAL
global_load_ubyte v255, v0, s[0:1] // GLOBAL
global_load_dwordx3 v[253:255], v[0:1], off glc // GLOBAL
global_store_dword v255, v0, s[104:105] offset:-2048 // GLOBAL
global_store_dwordx4 v[254:255], v[0:3], off offset:2047 // GLOBAL
global_store_byte v0, v255, s[0:1] // GLOBAL
global_atomic_or v255, v0, v255, s[104:105] glc // GLOBAL
global_atomic_add v[254:255], v0, off // GLOBAL
scratch_load_dword v255, v0, off offset:2047 // SCRATCH
scratch_load_dword v0, off, s105 offset:-2048 // SCRATCH
scratch_load_ushort v255, v0, off // SCRATCH
scratch_load_dwordx2 v[254:255], off, s0 // SCRATCH
scratch_load_dwordx4 v[0:3], v255, off // SCRATCH
scratch_store_dword v255, v0, off offset:-2048 // SCRATCH
scratch_store_dword off, v255, s0 offset:2047 // SCRATCH
scratch_store_byte v0, v255, off // SCRATCH
scratch_store_dwordx4 off, v[252:255], s105 // SCRATCH
// Forms the byte probes could not reach with legal operands (FLAT SADDR, DS GDS, BVH).
ds_gws_init v1 offset:65535 gds // DS
ds_gws_barrier v1 offset:0 gds // DS
ds_gws_sema_v gds // DS
ds_gws_sema_br v1 gds // DS
ds_gws_sema_p gds // DS
ds_gws_sema_release_all gds // DS
ds_ordered_count v0, v1 offset:65535 gds // DS
flat_load_dwordx3 v[0:2], v[254:255] offset:2047 // FLAT
flat_load_sshort v255, v[254:255] offset:2047 // FLAT
flat_load_ushort v0, v[254:255] offset:2047 // FLAT
flat_load_sbyte_d16 v0, v[254:255] offset:2047 // FLAT
flat_load_sbyte_d16_hi v0, v[254:255] offset:2047 // FLAT
flat_load_short_d16 v0, v[254:255] offset:2047 // FLAT
flat_load_short_d16_hi v0, v[254:255] offset:2047 // FLAT
flat_load_ubyte_d16 v0, v[254:255] offset:2047 // FLAT
flat_load_ubyte_d16_hi v0, v[254:255] offset:2047 // FLAT
flat_store_byte v[0:1], v2 // FLAT
flat_store_byte_d16_hi v[0:1], v2 // FLAT
flat_store_dwordx2 v[0:1], v[2:3] // FLAT
flat_store_dwordx3 v[0:1], v[2:4] // FLAT
flat_store_dwordx4 v[0:1], v[2:5] // FLAT
flat_store_short_d16_hi v[0:1], v2 // FLAT
flat_atomic_add v0, v[0:1], v2 glc // FLAT
flat_atomic_add_x2 v[0:1], v[2:3] // FLAT
flat_atomic_and v0, v[0:1], v2 glc // FLAT
flat_atomic_and_x2 v[0:1], v[2:3] // FLAT
flat_atomic_dec v0, v[0:1], v2 glc // FLAT
flat_atomic_dec_x2 v[0:1], v[2:3] // FLAT
flat_atomic_inc v0, v[0:1], v2 glc // FLAT
flat_atomic_inc_x2 v[0:1], v[2:3] // FLAT
flat_atomic_or v0, v[0:1], v2 glc // FLAT
flat_atomic_or_x2 v[0:1], v[2:3] // FLAT
flat_atomic_smax v0, v[0:1], v2 glc // FLAT
flat_atomic_smax_x2 v[0:1], v[2:3] // FLAT
flat_atomic_smin v0, v[0:1], v2 glc // FLAT
flat_atomic_smin_x2 v[0:1], v[2:3] // FLAT
flat_atomic_sub v0, v[0:1], v2 glc // FLAT
flat_atomic_sub_x2 v[0:1], v[2:3] // FLAT
flat_atomic_umax v0, v[0:1], v2 glc // FLAT
flat_atomic_umax_x2 v[0:1], v[2:3] // FLAT
flat_atomic_umin v0, v[0:1], v2 glc // FLAT
flat_atomic_umin_x2 v[0:1], v[2:3] // FLAT
flat_atomic_xor v0, v[0:1], v2 glc // FLAT
flat_atomic_xor_x2 v[0:1], v[2:3] // FLAT
flat_atomic_fmax v0, v[0:1], v2 glc // FLAT
flat_atomic_fmax_x2 v[0:1], v[2:3] // FLAT
flat_atomic_fmin v0, v[0:1], v2 glc // FLAT
flat_atomic_fmin_x2 v[0:1], v[2:3] // FLAT
flat_atomic_swap_x2 v[0:1], v[2:3] offset:2047 // FLAT
flat_atomic_cmpswap v0, v[0:1], v[2:3] glc // FLAT
flat_atomic_cmpswap_x2 v[0:1], v[2:5] // FLAT
flat_atomic_fcmpswap v[0:1], v[2:3] // FLAT
flat_atomic_fcmpswap_x2 v[0:1], v[2:5] // FLAT
image_bvh_intersect_ray v[0:3], v[0:10], s[0:3] // MIMG
image_bvh64_intersect_ray v[0:3], v[0:11], s[0:3] // MIMG
image_bvh_intersect_ray v[0:3], [v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14], s[0:3] // MIMG
v_interp_p1ll_f16 v0, v1, attr0.x // VOP3
v_interp_p1lv_f16 v0, v1, attr0.x, v2 // VOP3
v_interp_p2_f16 v0, v1, attr0.x, v2 // VOP3
v_mqsad_u32_u8 v[0:3], v[2:3], v4, v[4:7] // VOP3
v_permlane16_b32 v0, v1, s2, s3 // VOP3
v_permlanex16_b32 v255, v1, s105, m0 op_sel:[1,1] // VOP3
v_swaprel_b32 v0, v1 // VOP1
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,133 @@
# Rows of the asm, probe-zero and probe-ext sources where identify and LLVM do not simply agree
# (neither `identified` nor `both_reject`), as `class hex`, sorted by hex. Pinned by meta_corpus.rs;
# review each change against LLVM.
operand_flagged 000000d60000000000000000000000000000000000000000
mismatch 000000d6ff00000078563412000000000000000000000000
metadata_only 000000dd0000000000000000000000000000000000000000
operand_flagged 000001d60000000000000000000000000000000000000000
mismatch 000001d6ff00000078563412000000000000000000000000
mismatch 000002d6ff00000078563412000000000000000000000000
metadata_only 000008f10000000000000000000000000000000000000000
metadata_only 00000cf10000000000000000000000000000000000000000
metadata_only 000020dc0000000000000000000000000000000000000000
metadata_only 000024dc0000000000000000000000000000000000000000
metadata_only 000028dc0000000000000000000000000000000000000000
metadata_only 000028f10000000000000000000000000000000000000000
metadata_only 00002cdc0000000000000000000000000000000000000000
metadata_only 00002cf10000000000000000000000000000000000000000
metadata_only 000030dc0000000000000000000000000000000000000000
metadata_only 000034dc0000000000000000000000000000000000000000
metadata_only 000038dc0000000000000000000000000000000000000000
metadata_only 00003cdc0000000000000000000000000000000000000000
metadata_only 000040dd0000000000000000000000000000000000000000
operand_flagged 000042d70000000000000000000000000000000000000000
mismatch 000042d7ff00000078563412000000000000000000000000
operand_flagged 000043d70000000000000000000000000000000000000000
mismatch 000043d7ff00000078563412000000000000000000000000
metadata_only 000044dd0000000000000000000000000000000000000000
metadata_only 000048dd0000000000000000000000000000000000000000
metadata_only 000048f10000000000000000000000000000000000000000
metadata_only 00004cdd0000000000000000000000000000000000000000
metadata_only 00004cf10000000000000000000000000000000000000000
metadata_only 000054dd0000000000000000000000000000000000000000
metadata_only 000058dd0000000000000000000000000000000000000000
operand_flagged 00005ad70000000000000000000000000000000000000000
mismatch 00005ad7ff00000078563412000000000000000000000000
metadata_only 00005cdd0000000000000000000000000000000000000000
operand_flagged 000060d70000000000000000000000000000000000000000
metadata_only 000060d80000000000000000000000000000000000000000
metadata_only 000060dc0000000000000000000000000000000000000000
metadata_only 000060dd0000000000000000000000000000000000000000
metadata_only 000064d80000000000000000000000000000000000000000
metadata_only 000064dc0000000000000000000000000000000000000000
metadata_only 000064dd0000000000000000000000000000000000000000
metadata_only 000068d80000000000000000000000000000000000000000
metadata_only 000068dc0000000000000000000000000000000000000000
metadata_only 000068dd0000000000000000000000000000000000000000
metadata_only 000068f10000000000000000000000000000000000000000
metadata_only 00006cd80000000000000000000000000000000000000000
metadata_only 00006cdc0000000000000000000000000000000000000000
metadata_only 00006cdd0000000000000000000000000000000000000000
metadata_only 00006cf10000000000000000000000000000000000000000
metadata_only 000070d80000000000000000000000000000000000000000
metadata_only 000070dc0000000000000000000000000000000000000000
metadata_only 000070dd0000000000000000000000000000000000000000
metadata_only 000074d80000000000000000000000000000000000000000
metadata_only 000074dc0000000000000000000000000000000000000000
metadata_only 000074dd0000000000000000000000000000000000000000
operand_flagged 000075d50000000000000000000000000000000000000000
operand_flagged 000075d5ff00000078563412000000000000000000000000
operand_flagged 000077d70000000000000000000000000000000000000000
operand_flagged 000077d7ff00000078563412000000000000000000000000
operand_flagged 000078d70000000000000000000000000000000000000000
operand_flagged 000078d7ff00000078563412000000000000000000000000
metadata_only 000078dc0000000000000000000000000000000000000000
metadata_only 000078dd0000000000000000000000000000000000000000
metadata_only 00007cdc0000000000000000000000000000000000000000
metadata_only 00007cdd0000000000000000000000000000000000000000
oracle_only 000080d5ff00000078563412000000000000000000000000
metadata_only 000080dc0000000000000000000000000000000000000000
metadata_only 000080dd0000000000000000000000000000000000000000
metadata_only 000082d50000000000000000000000000000000000000000
metadata_only 000084dc0000000000000000000000000000000000000000
metadata_only 000088dc0000000000000000000000000000000000000000
metadata_only 000088f10000000000000000000000000000000000000000
metadata_only 00008cdc0000000000000000000000000000000000000000
metadata_only 00008cf10000000000000000000000000000000000000000
metadata_only 000090dc0000000000000000000000000000000000000000
metadata_only 000094dc0000000000000000000000000000000000000000
oracle_only 00009bd5ff00000078563412000000000000000000000000
metadata_only 0000c0dc0000000000000000000000000000000000000000
metadata_only 0000c0f10000000000000000000000000000000000000000
oracle_only 0000c1d5ff00000078563412000000000000000000000000
operand_flagged 0000c3d50000000000000000000000000000000000000000
operand_flagged 0000c4d50000000000000000000000000000000000000000
metadata_only 0000c4dc0000000000000000000000000000000000000000
metadata_only 0000c4f10000000000000000000000000000000000000000
operand_flagged 0000c8d50000000000000000000000000000000000000000
metadata_only 0000c8dc0000000000000000000000000000000000000000
metadata_only 0000ccdc0000000000000000000000000000000000000000
metadata_only 0000ccf10000000000000000000000000000000000000000
metadata_only 0000d0f10000000000000000000000000000000000000000
metadata_only 0000d4dc0000000000000000000000000000000000000000
metadata_only 0000d8dc0000000000000000000000000000000000000000
metadata_only 0000d8f10000000000000000000000000000000000000000
metadata_only 0000dcdc0000000000000000000000000000000000000000
metadata_only 0000dcf10000000000000000000000000000000000000000
metadata_only 0000e0dc0000000000000000000000000000000000000000
metadata_only 0000e4dc0000000000000000000000000000000000000000
metadata_only 0000e4f10000000000000000000000000000000000000000
metadata_only 0000e8dc0000000000000000000000000000000000000000
metadata_only 0000e8f10000000000000000000000000000000000000000
metadata_only 0000ecdc0000000000000000000000000000000000000000
metadata_only 0000f0dc0000000000000000000000000000000000000000
metadata_only 0000f4dc0000000000000000000000000000000000000000
metadata_only 0000f8dc0000000000000000000000000000000000000000
metadata_only 0000fcd80000000000000000000000000000000000000000
metadata_only 0000fcdc0000000000000000000000000000000000000000
operand_flagged 0004007e00000000000000000000000000000000
operand_flagged 0086007e00000000000000000000000000000000
operand_flagged 0088007e00000000000000000000000000000000
operand_flagged 0090007e00000000000000000000000000000000
operand_flagged 00ca007e00000000000000000000000000000000
operand_flagged 00d0007e00000000000000000000000000000000
metadata_only 010098f10000000000000000000000000000000000000000
metadata_only 01009cf10000000000000000000000000000000000000000
oracle_only e900007e0088c6fa000000000000000000000000
oracle_only e936007e0088c6fa000000000000000000000000
oracle_only e982007e0088c6fa000000000000000000000000
oracle_only ea00007e0088c6fa000000000000000000000000
oracle_only ea36007e0088c6fa000000000000000000000000
oracle_only ea82007e0088c6fa000000000000000000000000
oracle_only f900007e00060600000000000000000000000000
oracle_only f936007e00060600000000000000000000000000
oracle_only f982007e00060600000000000000000000000000
oracle_only fa00007e00e400ff000000000000000000000000
oracle_only fa36007e00e400ff000000000000000000000000
oracle_only fa82007e00e400ff000000000000000000000000
oracle_only ff00007e78563412000000000000000000000000
oracle_only ff1f80be78563412000000000000000000000000
oracle_only ff2180be78563412000000000000000000000000
oracle_only ff36007e78563412000000000000000000000000
oracle_only ff4980be78563412000000000000000000000000
oracle_only ff82007e78563412000000000000000000000000
+304
View File
@@ -0,0 +1,304 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Independent LLVM corpus check of gfx1030 instruction identification (#209).
//!
//! `llvm/corpus.tsv` is generated by `llvm/corpus.py` from LLVM 23.1.6 alone:
//! llvm-mc assembles the original instructions in `llvm/corpus.s`, and
//! llvm-objdump decodes byte probes built from each metadata form's
//! identifying bits (one with every other bit zero, two with seeded random
//! operand bits). The expected name, consumed length and extension of every
//! row are LLVM's. This test compares `identify` with them and pins what it
//! measures: per-source class counts, the exact rows where the two disagree
//! for assembled and zero-operand inputs, and a digest of the random-probe
//! classification.
//!
//! Identification is not execution support: a row counted as identified only
//! means both agree on which instruction the bytes are and how long it is.
use std::collections::BTreeMap;
use xenora_isa::meta::{FORMS, Identified, IdentifyError, VectorControl, identify};
const CORPUS: &str = include_str!("llvm/corpus.tsv");
/// Row classes, in report order.
const CLASSES: [&str; 9] = [
"identified", // both decode: same name, length and extension
"mismatch", // both decode, but name, length or extension differ
"oracle_only", // LLVM decodes, identify returns an error
"metadata_only", // identify decodes, LLVM cannot
"both_reject", // neither decodes
"oracle_crash", // llvm-objdump crashed; no oracle answer
"truncated", // a proper prefix: identify asks for more bytes
"truncation_other",
"operand_flagged", // same instruction and length; LLVM flags an operand as invalid
];
const SOURCES: [&str; 5] = [
"asm",
"probe-zero",
"probe-ext",
"probe-random",
"truncation",
];
fn base_name(mnemonic: &str) -> String {
let upper = mnemonic.to_ascii_uppercase();
["_E32", "_E64", "_SDWA", "_DPP"]
.into_iter()
.find_map(|suffix| upper.strip_suffix(suffix))
.unwrap_or(&upper)
.to_owned()
}
fn extension(found: &Identified) -> String {
let nsa = format!("nsa{}", found.trailer.nsa_dwords);
let mut parts = Vec::new();
if found.trailer.literal {
parts.push("literal");
}
match found.trailer.vector_control {
Some(VectorControl::Sdwa) => parts.push("sdwa"),
Some(VectorControl::Dpp8 {
fetch_inactive: false,
}) => parts.push("dpp8"),
Some(VectorControl::Dpp8 {
fetch_inactive: true,
}) => parts.push("dpp8fi"),
Some(VectorControl::Dpp16) => parts.push("dpp16"),
None => {}
}
if found.trailer.nsa_dwords != 0 {
parts.push(&nsa);
}
if parts.is_empty() {
"-".into()
} else {
parts.join("+")
}
}
struct Row<'a> {
source: usize,
form: Option<&'static str>,
family: &'a str,
hex: &'a str,
class: usize,
detail: String,
}
fn classify(line: &str) -> Row<'_> {
let [source, hex, mnemonic, len, ext, note] = line.split('\t').collect::<Vec<_>>()[..] else {
panic!("bad corpus row: {line}");
};
let source = SOURCES
.iter()
.position(|s| *s == source)
.unwrap_or_else(|| panic!("bad source: {line}"));
let (family, text) = note.split_once(' ').unwrap();
let bytes: Vec<u8> = (0..hex.len())
.step_by(2)
.map(|i| u8::from_str_radix(&hex[i..i + 2], 16).unwrap())
.collect();
let len: usize = len.parse().unwrap();
let found = identify(&bytes);
let answer = match &found {
Ok(found) => format!(
"{} ({} bytes, {})",
found.form.name,
found.len,
extension(found)
),
Err(error) => format!("{error:?}"),
};
let mut differences = Vec::new();
// LLVM decoded the words but flagged an operand the instruction cannot
// take. identify does not validate operands; it must still agree on the
// instruction and its length, or reject the extension outright.
let (flagged, mnemonic) = match mnemonic.strip_prefix("invalid-operand:") {
Some(mnemonic) => (true, mnemonic),
None => (false, mnemonic),
};
let class = match (mnemonic, &found) {
("truncated", Err(IdentifyError::Truncated { needed })) if *needed > bytes.len() => 6,
("truncated", _) => 7,
("crashed", _) => 5,
("invalid", Err(_)) => 4,
("invalid", Ok(_)) => 3,
(_, Err(IdentifyError::InvalidExtension(_))) if flagged => 4,
(_, Err(_)) => 2,
(_, Ok(found)) => {
if found.form.name != base_name(mnemonic) {
differences.push("name");
}
if found.len != len {
differences.push("length");
}
if extension(found) != ext {
differences.push("extension");
}
if !differences.is_empty() {
1
} else if flagged {
8
} else {
0
}
}
};
let kind = if differences.is_empty() {
CLASSES[class].to_owned()
} else {
format!("mismatch/{}", differences.join("+"))
};
Row {
source,
form: found.ok().map(|found| found.form.name),
family,
hex,
class,
detail: format!("{kind}: {hex} | LLVM {text} ({len} bytes, {ext}) | Xenora {answer}"),
}
}
/// FNV-1a over the sorted `class hex` lines, to pin thousands of rows compactly.
fn digest(lines: &[String]) -> u64 {
lines
.iter()
.flat_map(|l| l.bytes().chain(*b"\n"))
.fold(0xcbf2_9ce4_8422_2325, |hash, byte| {
(hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3)
})
}
// Measured against LLVM 23.1.6 on 2026-11-24. Any change needs the affected
// rows reviewed against LLVM, not an update of these numbers alone.
// Rows: one per source, columns in CLASSES order.
const COUNTS: [[usize; 9]; 5] = [
[317, 0, 0, 0, 0, 0, 0, 0, 0], // asm
[1365, 0, 0, 82, 0, 0, 0, 0, 18], // probe-zero
[1397, 6, 21, 0, 752, 0, 0, 0, 3], // probe-ext
[1236, 0, 0, 1678, 3, 2, 0, 0, 11], // probe-random
[0, 0, 0, 0, 0, 0, 87, 0, 0], // truncation
];
/// Every assembled, zero-operand or extension-probe row where the two disagree
/// (neither `identified` nor `both_reject`), as `class hex`, sorted by hex.
const DISAGREEMENTS: &str = include_str!("llvm/corpus_disagreements.txt");
/// Digest of the sorted `class hex` lines of the random probes.
const RANDOM_DIGEST: u64 = 0x32fb_5d7d_0826_ce14;
#[test]
fn identification_agrees_with_the_llvm_corpus() {
let mut lines = CORPUS.lines();
assert_eq!(
lines.next(),
Some("source\thex\tllvm_mnemonic\tllvm_len\tllvm_ext\tnote")
);
let rows: Vec<_> = lines.map(classify).collect();
let mut counts = [[0usize; 9]; 5];
let mut by_family = BTreeMap::<&str, [usize; 9]>::new();
for row in &rows {
counts[row.source][row.class] += 1;
by_family.entry(row.family).or_default()[row.class] += 1;
}
println!("{:9} {}", "family", CLASSES.join(" "));
for (family, c) in &by_family {
print!("{family:9}");
for (name, n) in CLASSES.iter().zip(c) {
print!(" {n:>w$}", w = name.len());
}
println!();
}
for (source, c) in SOURCES.iter().zip(&counts) {
println!("{source:13} {c:?}");
}
let mut disagreements: Vec<_> = rows
.iter()
.filter(|r| r.source < 3 && !matches!(r.class, 0 | 4))
.collect();
disagreements.sort_unstable_by_key(|r| r.hex);
for r in &disagreements {
println!("{}", r.detail);
}
let disagreements: Vec<_> = disagreements
.iter()
.map(|r| format!("{} {}", CLASSES[r.class], r.hex))
.collect();
let mut random: Vec<_> = rows
.iter()
.filter(|r| r.source == 3)
.map(|r| format!("{} {}", CLASSES[r.class], r.hex))
.collect();
random.sort_unstable();
let random_digest = digest(&random);
println!("random digest {random_digest:#018x}");
for r in rows
.iter()
.filter(|r| r.source == 3 && r.class == 1)
.take(5)
{
println!("random example {}", r.detail);
}
// Distinct metadata forms: agreed by LLVM on at least one row, or only
// ever decoded by Xenora (LLVM rejected every probe of that form).
let mut forms = BTreeMap::<&str, (usize, usize)>::new();
for row in &rows {
if let Some(form) = row.form {
let entry = forms.entry(form).or_default();
match row.class {
0 | 8 => entry.0 += 1,
3 => entry.1 += 1,
_ => {}
}
}
}
let agreed = forms.values().filter(|(a, _)| *a > 0).count();
let never: Vec<_> = forms
.iter()
.filter(|(_, (a, m))| *a == 0 && *m > 0)
.map(|(name, _)| *name)
.collect();
println!(
"distinct forms seen {}: agreed {agreed}, metadata-only on every row {}",
forms.len(),
never.len()
);
println!("never decoded by LLVM: {}", never.join(" "));
let mut all_names: Vec<_> = FORMS.iter().map(|form| form.name).collect();
all_names.sort_unstable();
all_names.dedup();
let unseen: Vec<_> = all_names
.iter()
.filter(|name| !forms.contains_key(*name))
.collect();
println!(
"metadata: {} forms, {} distinct names, {} names with no corpus row: {unseen:?}",
FORMS.len(),
all_names.len(),
unseen.len()
);
assert_eq!(counts, COUNTS, "class counts per source changed");
let pinned: Vec<_> = DISAGREEMENTS
.lines()
.filter(|line| !line.starts_with('#'))
.collect();
assert_eq!(disagreements, pinned, "disagreeing rows changed");
assert_eq!(
random_digest, RANDOM_DIGEST,
"random-probe classification changed"
);
}
#[test]
#[ignore = "requires LLVM with the gfx1030 AMDGPU target (set LLVM_BIN)"]
fn llvm_corpus_is_fresh() {
let bin = std::env::var("LLVM_BIN").expect("LLVM_BIN");
let status = std::process::Command::new("python3")
.arg(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/llvm/corpus.py"))
.args(["--llvm-bin", &bin, "--check"])
.status()
.expect("run corpus.py");
assert!(
status.success(),
"corpus.tsv differs from LLVM's current output"
);
}