diff --git a/CHANGELOG.md b/CHANGELOG.md index 2a63429..cfd9c90 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 +- 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. ### Added @@ -37,6 +38,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 guest mutexes, critical sections, SRW locks, condition variables, synchronous one-time initialization, interlocked SLists, and TLS and FLS slots. Ownership is per guest thread (TEB). Calls that would have to block stop the guest with an explicit runtime-limit fault, because there is no guest scheduler yet. An original PE32+ fixture calls every service through its import table, using two guest TEBs. See `docs/interfaces.md`. diff --git a/benchmarks/src/main.rs b/benchmarks/src/main.rs index 0d068a5..490ae6d 100644 --- a/benchmarks/src/main.rs +++ b/benchmarks/src/main.rs @@ -14,11 +14,12 @@ use std::path::PathBuf; use std::process::Command; use std::time::{SystemTime, UNIX_EPOCH}; -use xenora_metal::NativeCompute; +use xenora_metal::{NativeCompute, RunProfile}; use xenora_shader::{Architecture, ENTRY_POINT, compile}; const WARMUP_REPS: usize = 2; const DEFAULT_REPS: usize = 7; +const BATCH: usize = 8; #[derive(Debug, Clone)] struct Fixture { @@ -83,10 +84,66 @@ struct SizeResult { pipeline: Stats, gpu: Stats, host: Stats, + /// Host submission stages inside `host`, plus readback after it. + submit: SubmitStats, /// Fraction of samples whose GPU timestamp delta was zero. gpu_zero_fraction: f64, } +/// Host-side split of one dispatch's submission path. +/// +/// `other` is `host` minus library, pipeline and the four stages below it, +/// per sample: compile options, function lookup, bounds and validation checks. +#[derive(Debug, Clone, Default)] +struct SubmitStats { + alloc: Stats, + encode: Stats, + commit: Stats, + wait: Stats, + readback: Stats, + other: Stats, +} + +#[derive(Debug, Clone, Default)] +struct SubmitSamples { + alloc: Vec, + encode: Vec, + commit: Vec, + wait: Vec, + readback: Vec, + other: Vec, +} + +impl SubmitSamples { + fn push(&mut self, profile: &RunProfile) { + self.alloc.push(profile.alloc_seconds); + self.encode.push(profile.encode_seconds); + self.commit.push(profile.commit_seconds); + self.wait.push(profile.wait_seconds); + self.readback.push(profile.readback_seconds); + self.other.push( + profile.host_seconds + - profile.library_seconds + - profile.pipeline_seconds + - profile.alloc_seconds + - profile.encode_seconds + - profile.commit_seconds + - profile.wait_seconds, + ); + } + + fn stats(self) -> SubmitStats { + SubmitStats { + alloc: Stats::from_samples(self.alloc), + encode: Stats::from_samples(self.encode), + commit: Stats::from_samples(self.commit), + wait: Stats::from_samples(self.wait), + readback: Stats::from_samples(self.readback), + other: Stats::from_samples(self.other), + } + } +} + #[derive(Debug, Clone)] struct FixtureResult { name: String, @@ -95,6 +152,14 @@ struct FixtureResult { status: String, reason: String, sizes: Vec, + batch: Option, +} + +#[derive(Debug, Clone)] +struct BatchResult { + words: usize, + sync: Stats, + pipelined: Stats, } fn main() -> Result<(), Box> { @@ -180,6 +245,7 @@ fn run_fixture(metal: &NativeCompute, fixture: &Fixture, reps: usize) -> Fixture status: "not-implemented".to_string(), reason: String::new(), sizes: Vec::new(), + batch: None, }; let code = match fs::read(&fixture.path) { @@ -242,6 +308,7 @@ fn run_fixture(metal: &NativeCompute, fixture: &Fixture, reps: usize) -> Fixture let mut pipeline_samples = Vec::with_capacity(reps); let mut gpu_samples = Vec::with_capacity(reps); let mut host_samples = Vec::with_capacity(reps); + let mut submit_samples = SubmitSamples::default(); let mut gpu_zero = 0usize; let mut mismatch = None; @@ -275,6 +342,7 @@ fn run_fixture(metal: &NativeCompute, fixture: &Fixture, reps: usize) -> Fixture pipeline_samples.push(profile.pipeline_seconds); gpu_samples.push(profile.gpu_seconds); host_samples.push(profile.host_seconds); + submit_samples.push(&profile); if profile.gpu_seconds <= 0.0 { gpu_zero += 1; } @@ -294,6 +362,7 @@ fn run_fixture(metal: &NativeCompute, fixture: &Fixture, reps: usize) -> Fixture pipeline: Stats::from_samples(pipeline_samples), gpu: Stats::from_samples(gpu_samples), host: Stats::from_samples(host_samples), + submit: submit_samples.stats(), gpu_zero_fraction: if measured == 0 { 0.0 } else { @@ -302,11 +371,83 @@ fn run_fixture(metal: &NativeCompute, fixture: &Fixture, reps: usize) -> Fixture }); } + let batch_words = fixture + .sizes + .iter() + .copied() + .min_by_key(|words| words.abs_diff(1024)) + .unwrap_or(1024); + match measure_batch(metal, &code, fixture, batch_words, reps) { + Ok(batch) => result.batch = Some(batch), + Err(reason) => { + result.status = "excluded".to_string(); + result.reason = reason; + return result; + } + } result.sizes = sizes; result.status = "benchmarked".to_string(); result } +fn measure_batch( + metal: &NativeCompute, + code: &[u8], + fixture: &Fixture, + words: usize, + reps: usize, +) -> Result { + let input = expand(&fixture.input, words); + let expected = expand(&fixture.expected, words); + let mut sync = Vec::with_capacity(reps); + let mut pipelined = Vec::with_capacity(reps); + for rep in 0..(WARMUP_REPS + reps) { + for (samples, variant) in [(&mut sync, "sync"), (&mut pipelined, "pipelined")] { + let mut tokens = Vec::with_capacity(BATCH); + let mut outputs = Vec::with_capacity(BATCH); + let start = std::time::Instant::now(); + for _ in 0..BATCH { + let compiled = compile(Architecture::Gfx1030, code).map_err(|error| { + format!("{variant} batch compile failed at {words} words: {error}") + })?; + if variant == "sync" { + let profile = metal + .run_words_profiled(&compiled.msl, ENTRY_POINT, &input) + .map_err(|error| { + format!("{variant} batch run failed at {words} words: {error}") + })?; + outputs.push(profile.output); + } else { + let token = metal + .submit_words(&compiled.msl, ENTRY_POINT, &input) + .map_err(|error| { + format!("{variant} batch submit failed at {words} words: {error}") + })?; + tokens.push(token); + } + } + for token in tokens { + let profile = metal.wait(token).map_err(|error| { + format!("{variant} batch wait failed at {words} words: {error}") + })?; + outputs.push(profile.output); + } + let per_dispatch = start.elapsed().as_secs_f64() / BATCH as f64; + if outputs.iter().any(|output| *output != expected) { + return Err(format!("{variant} batch GPU mismatch at {words} words")); + } + if rep >= WARMUP_REPS { + samples.push(per_dispatch); + } + } + } + Ok(BatchResult { + words, + sync: Stats::from_samples(sync), + pipelined: Stats::from_samples(pipelined), + }) +} + fn expand(base: &[u32], words: usize) -> Vec { (0..words).map(|i| base[i % base.len()]).collect() } @@ -612,13 +753,19 @@ fn results_json(results: &[FixtureResult]) -> String { for (size_index, size) in result.sizes.iter().enumerate() { let _ = writeln!( out, - " {{ \"words\": {}, \"compile\": {}, \"library\": {}, \"pipeline\": {}, \"gpu\": {}, \"host\": {}, \"gpu_zero_fraction\": {:.4} }}{}", + " {{ \"words\": {}, \"compile\": {}, \"library\": {}, \"pipeline\": {}, \"gpu\": {}, \"host\": {}, \"alloc\": {}, \"encode\": {}, \"commit\": {}, \"wait\": {}, \"readback\": {}, \"host_other\": {}, \"gpu_zero_fraction\": {:.4} }}{}", size.words, stats_json(&size.compile), stats_json(&size.library), stats_json(&size.pipeline), stats_json(&size.gpu), stats_json(&size.host), + stats_json(&size.submit.alloc), + stats_json(&size.submit.encode), + stats_json(&size.submit.commit), + stats_json(&size.submit.wait), + stats_json(&size.submit.readback), + stats_json(&size.submit.other), size.gpu_zero_fraction, if size_index + 1 == result.sizes.len() { "" @@ -627,9 +774,19 @@ fn results_json(results: &[FixtureResult]) -> String { } ); } + out.push_str(" ]"); + if let Some(batch) = &result.batch { + let _ = write!( + out, + ",\n \"batch\": {{ \"dispatches\": {BATCH}, \"words\": {}, \"sync\": {}, \"pipelined\": {} }}", + batch.words, + stats_json(&batch.sync), + stats_json(&batch.pipelined) + ); + } let _ = writeln!( out, - " ]\n }}{}", + "\n }}{}", if index + 1 == results.len() { "" } else { "," } ); } @@ -644,7 +801,7 @@ fn report_markdown(metadata: &Metadata, results: &[FixtureResult]) -> String { let _ = writeln!( out, "Generated by `xenora-bench`. Every timed fixture passed its correctness test in this run. \ - Timings are single command-buffer samples; see `docs/testing/benchmarks.md` for the protocol." + See `docs/testing/benchmarks.md` for the single-dispatch protocol." ); let _ = writeln!(out); let _ = writeln!(out, "## Environment"); @@ -739,5 +896,70 @@ fn report_markdown(metadata: &Metadata, results: &[FixtureResult]) -> String { ); } } + + let _ = writeln!(out); + let _ = writeln!(out, "## Submission split"); + let _ = writeln!(out); + let _ = writeln!( + out, + "Medians in microseconds of the host stages inside `host`: `alloc` creates the input and \ + output shared buffers, `encode` creates the command buffer and encodes the dispatch, \ + `commit` and `wait` time `commit` and `waitUntilCompleted`, and `other` is the per-sample \ + remainder of `host` after library, pipeline and these four stages. `readback` copies \ + the output after `host` ends." + ); + let _ = writeln!(out); + let _ = writeln!( + out, + "| Fixture | Words | host | alloc | encode | commit | wait | other | readback |" + ); + let _ = writeln!( + out, + "| --- | --- | --- | --- | --- | --- | --- | --- | --- |" + ); + for result in results.iter().filter(|r| r.status == "benchmarked") { + for size in &result.sizes { + let stages = &size.submit; + let _ = writeln!( + out, + "| {} | {} | {:.2} | {:.2} | {:.2} | {:.2} | {:.2} | {:.2} | {:.2} |", + result.name, + size.words, + size.host.median * 1e6, + stages.alloc.median * 1e6, + stages.encode.median * 1e6, + stages.commit.median * 1e6, + stages.wait.median * 1e6, + stages.other.median * 1e6, + stages.readback.median * 1e6 + ); + } + } + let _ = writeln!(out); + let _ = writeln!(out, "## Batched submission"); + let _ = writeln!(out); + let _ = writeln!( + out, + "Median host microseconds per dispatch in batches of {BATCH}, including recompilation." + ); + let _ = writeln!(out); + let _ = writeln!( + out, + "| Fixture | Words | Sync (µs) | Pipelined (µs) | Sync / pipelined |" + ); + let _ = writeln!(out, "| --- | --- | --- | --- | --- |"); + for result in results { + if let Some(batch) = &result.batch { + let _ = writeln!( + out, + "| {} | {} | {:.2} | {:.2} | {:.2}× |", + result.name, + batch.words, + batch.sync.median * 1e6, + batch.pipelined.median * 1e6, + batch.sync.median / batch.pipelined.median + ); + } + } out } 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..d9c3f97 100644 --- a/crates/decoder/tests/gfx1030.rs +++ b/crates/decoder/tests/gfx1030.rs @@ -454,15 +454,17 @@ 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, CompareRelation::Greater => 4, CompareRelation::NotEqual => 5, CompareRelation::GreaterOrEqual => 6, + CompareRelation::False => 0, + CompareRelation::True => 7, }, - signed: op.signed, + signed: op.signed(), }, match src0 { VectorSource::Register(reg) => CompareSource::Vector(reg), @@ -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 2d16376..0328eb5 100755 --- a/crates/isa/generate_semantics.py +++ b/crates/isa/generate_semantics.py @@ -60,8 +60,15 @@ 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"} +# 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 = { @@ -71,6 +78,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. @@ -113,11 +122,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 +267,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", @@ -356,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 @@ -364,8 +398,15 @@ 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. + 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": + # 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: errors.append(f"{label}: XML implicit operands {sorted(implicit)} are not declared") if scc_in != (form["carry_in"] == "scc"): @@ -471,8 +512,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 +577,23 @@ 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)") + 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: + 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 +620,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 +770,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 +898,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 +935,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..29f678a 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,361 @@ 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/src/lib.rs b/crates/isa/src/lib.rs index 160e3c0..b5edab6 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). @@ -108,64 +111,10 @@ pub enum CompareRelation { NotEqual, /// S0 >= S1 (offset 6). 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(), - } - } + /// Never holds (VOPC F, offset 0). + False, + /// Always holds (VOPC T, offset 7). + True, } /// Output targeted by a supported uncompressed four-component export. @@ -327,7 +276,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/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.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..8e889fb 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,468 @@ 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, + /// `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. +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, + 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, + 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::CmpFU32), + Some(VectorCompareOp::CmpLtU32), + Some(VectorCompareOp::CmpEqU32), + Some(VectorCompareOp::CmpLeU32), + Some(VectorCompareOp::CmpGtU32), + Some(VectorCompareOp::CmpNeU32), + Some(VectorCompareOp::CmpGeU32), + Some(VectorCompareOp::CmpTU32), + 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; 16] = [ + Self::CmpLtI32, + Self::CmpEqI32, + Self::CmpLeI32, + Self::CmpGtI32, + Self::CmpNeI32, + Self::CmpGeI32, + Self::CmpLtU32, + Self::CmpEqU32, + Self::CmpLeU32, + 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 + /// 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", + Self::CmpFI32 => "v_cmp_f_i32", + Self::CmpTI32 => "v_cmp_t_i32", + Self::CmpFU32 => "v_cmp_f_u32", + Self::CmpTU32 => "v_cmp_t_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, + Self::CmpFI32 => 80, + Self::CmpTI32 => 81, + Self::CmpFU32 => 82, + Self::CmpTU32 => 83, + }] + } + + /// 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", + 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", + } + } + + /// 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, + Self::CmpFI32 => true, + Self::CmpTI32 => true, + Self::CmpFU32 => false, + Self::CmpTU32 => 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, + Self::CmpFI32 => CompareRelation::False, + Self::CmpTI32 => CompareRelation::True, + Self::CmpFU32 => CompareRelation::False, + Self::CmpTU32 => CompareRelation::True, + } + } + + /// 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), + 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); 68] = [ +pub const FORM_IDS: [(&str, EncodingFamily); 84] = [ ("S_ADD_U32", EncodingFamily::Sop2), ("S_SUB_U32", EncodingFamily::Sop2), ("S_ADD_I32", EncodingFamily::Sop2), @@ -1482,10 +1942,26 @@ 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), + ("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; 68] = [ +pub static FORMS: [FormSemantics; 84] = [ FormSemantics { name: "S_ADD_U32", family: EncodingFamily::Sop2, @@ -2914,4 +3390,340 @@ 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], + }, + 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 fb3de7f..895b7ff 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,56 @@ 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(), + CompareRelation::False => false, + CompareRelation::True => true, + }; + assert_eq!( + op.test(src0, src1), + expected, + "{} {src0:#x} {src1:#x}", + row.name + ); + } + } + } + // 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/metal/Cargo.toml b/crates/metal/Cargo.toml index 9f5789f..556efa5 100644 --- a/crates/metal/Cargo.toml +++ b/crates/metal/Cargo.toml @@ -41,6 +41,7 @@ objc2-metal = { version = "=0.3.2", default-features = false, features = [ "MTLComputePipeline", "MTLDepthStencil", "MTLDevice", + "MTLEvent", "MTLLibrary", "MTLPixelFormat", "MTLPipeline", diff --git a/crates/metal/src/compute.rs b/crates/metal/src/compute.rs index f66c403..ebed2ad 100644 --- a/crates/metal/src/compute.rs +++ b/crates/metal/src/compute.rs @@ -1,9 +1,12 @@ +use std::collections::BTreeMap; use std::ffi::c_void; use std::fmt; use std::mem::size_of_val; use std::ptr::{NonNull, copy_nonoverlapping}; +use std::sync::{Mutex, MutexGuard, PoisonError}; use std::time::Instant; +use objc2::Message; use objc2::rc::{Retained, autoreleasepool}; use objc2::runtime::{NSObjectProtocol, ProtocolObject}; use objc2::sel; @@ -13,8 +16,8 @@ use objc2_metal::{ MTLCompileOptions, MTLComputeCommandEncoder, MTLComputePipelineState, MTLCreateSystemDefaultDevice, MTLDevice, MTLFunction, MTLGPUFamily, MTLLibrary, MTLMathFloatingPointFunctions, MTLMathMode, MTLOrigin, MTLPixelFormat, MTLRegion, - MTLResourceOptions, MTLShaderValidation, MTLSize, MTLStorageMode, MTLTexture, - MTLTextureDescriptor, MTLTextureUsage, + MTLResourceOptions, MTLSamplerState, MTLShaderValidation, MTLSharedEvent, MTLSize, + MTLStorageMode, MTLTexture, MTLTextureDescriptor, MTLTextureUsage, }; use xenora_texture::{ Bc1Upload, BcAlphaFormat, BcAlphaUpload, BcChannelFormat, BcChannelUpload, TiledBc1, @@ -33,6 +36,7 @@ const MAX_THREADS_PER_GROUP: usize = 64; const MAX_GROUPS: usize = 64; const MAX_GRID_WORDS: usize = MAX_GROUPS * MAX_THREADS_PER_GROUP; const MAX_SOURCE_BYTES: usize = 64 * 1024; +const MAX_IN_FLIGHT: usize = 16; const BC_READBACK: &str = r" #include @@ -65,7 +69,7 @@ enum ComputeInput<'a> { Texture(&'a ProtocolObject, usize), SampledTexture { texture: &'a ProtocolObject, - sampler: &'a ProtocolObject, + sampler: &'a ProtocolObject, coords: &'a [u32], }, } @@ -147,7 +151,18 @@ pub struct RunProfile { pub library_seconds: f64, pub pipeline_seconds: f64, pub gpu_seconds: f64, + /// Host wall time from the start of setup until wait observes completion. pub host_seconds: f64, + /// Host time to allocate the input and output shared buffers. + pub alloc_seconds: f64, + /// Host time to create the command buffer and encode the dispatch. + pub encode_seconds: f64, + /// Host time spent in `commit`. + pub commit_seconds: f64, + /// Host time spent in `waitUntilCompleted`. + pub wait_seconds: f64, + /// Host time to copy the output words back; not part of `host_seconds`. + pub readback_seconds: f64, pub output: Vec, } @@ -155,10 +170,161 @@ pub struct RunProfile { pub struct NativeCompute { device: Retained>, queue: Retained>, + submissions: Mutex, +} + +/// A submitted dispatch whose result can be collected by its issuing context. +#[must_use] +pub struct Submission<'a> { + context: &'a NativeCompute, + id: u64, +} + +impl Drop for Submission<'_> { + fn drop(&mut self) { + let mut table = self.context.submissions(); + if let Some(entry) = table.entries.get_mut(&self.id) { + if entry.resources.is_some() { + entry.abandoned = true; + } else { + table.entries.remove(&self.id); + } + } + } +} + +#[doc(hidden)] +pub struct SubmissionGate { + event: Retained>, +} + +impl SubmissionGate { + pub fn open(&self) { + self.event.setSignaledValue(1); + } +} + +impl Drop for SubmissionGate { + fn drop(&mut self) { + self.open(); + } +} + +#[derive(Default)] +struct SubmissionTable { + next_id: u64, + entries: BTreeMap, +} + +impl SubmissionTable { + fn in_flight(&self) -> usize { + self.entries + .values() + .filter(|entry| entry.resources.is_some()) + .count() + } + + fn check_capacity(&self) -> Result<(), MetalError> { + if self.in_flight() >= MAX_IN_FLIGHT { + return Err(MetalError::new( + "in-flight limit", + format!("at most {MAX_IN_FLIGHT} compute submissions may be in flight"), + )); + } + Ok(()) + } +} + +struct SubmissionEntry { + resources: Option, + result: Result, + host_start: Instant, + abandoned: bool, + waiting: bool, +} + +/// Owns every resource referenced by the unretained command buffer until +/// Metal reports Completed or Error. +struct InFlightResources { + command: Retained>, + _pipeline: Retained>, + _input: Option>>, + output: Retained>, + _texture: Option>>, + _sampler: Option>>, + gate: Option>>, + word_count: usize, +} + +// SAFETY: Metal permits command buffers to move between threads with exclusive +// access. The table mutex and waiting flag keep sweeps off a command during its +// wait. Readback uses private shared storage after GPU completion. Retained +// textures and input buffers are only kept alive by the table. +unsafe impl Send for InFlightResources {} + +impl SubmissionEntry { + fn retire(&mut self, status: MTLCommandBufferStatus) { + if !is_terminal(status) { + return; + } + let Some(resources) = self.resources.take() else { + return; + }; + if let Err(error) = check_command_status(&resources.command, status) { + self.result = Err(error); + return; + } + if let Ok(profile) = &mut self.result { + profile.gpu_seconds = resources.command.GPUEndTime() - resources.command.GPUStartTime(); + profile.host_seconds = self.host_start.elapsed().as_secs_f64(); + let readback_start = Instant::now(); + let byte_len = resources.word_count * size_of::(); + // SAFETY: The initialized shared output is distinct from the host + // vector and the GPU has finished writing to it. Both ranges hold + // byte_len bytes and all u32 bit patterns are valid. + unsafe { + copy_nonoverlapping( + resources.output.contents().cast::().as_ptr(), + profile.output.as_mut_ptr().cast::(), + byte_len, + ); + } + profile.readback_seconds = readback_start.elapsed().as_secs_f64(); + } + } +} + +impl Drop for NativeCompute { + fn drop(&mut self) { + // Tokens can be abandoned (or forgotten) while their work is pending. + // Open all remaining gates before draining the queue. + let table = self + .submissions + .get_mut() + .unwrap_or_else(PoisonError::into_inner); + for resources in table + .entries + .values() + .filter_map(|entry| entry.resources.as_ref()) + { + if let Some(gate) = &resources.gate { + gate.setSignaledValue(1); + } + } + for (_, entry) in std::mem::take(&mut table.entries) { + if let Some(resources) = entry.resources { + resources.command.waitUntilCompleted(); + if !is_terminal(resources.command.status()) { + // Preserve the resources if Metal unexpectedly returns before completion. + std::mem::forget(resources); + } + } + } + } } impl NativeCompute { - /// Open the default Apple GPU and create a retained-resource command queue. + /// Open the default Apple GPU and create a command queue. /// /// # Errors /// @@ -178,10 +344,47 @@ impl NativeCompute { let queue = device .newCommandQueue() .ok_or_else(|| MetalError::new("newCommandQueue", "queue creation failed"))?; - Ok(Self { device, queue }) + Ok(Self { + device, + queue, + submissions: Mutex::default(), + }) }) } + fn submissions(&self) -> MutexGuard<'_, SubmissionTable> { + self.submissions + .lock() + .unwrap_or_else(PoisonError::into_inner) + } + + fn retire_completed(&self) { + self.submissions().entries.retain(|_, entry| { + if !entry.waiting + && let Some(resources) = &entry.resources + { + entry.retire(resources.command.status()); + } + !entry.abandoned || entry.resources.is_some() + }); + } + + fn begin_submission(&self) -> Instant { + let host_start = Instant::now(); + self.retire_completed(); + host_start + } + + #[doc(hidden)] + pub fn in_flight(&self) -> usize { + self.submissions().in_flight() + } + + #[doc(hidden)] + pub fn tracked(&self) -> usize { + self.submissions().entries.len() + } + /// Report the selected device's registered name. pub fn device_name(&self) -> String { autoreleasepool(|_| self.device.name().to_string()) @@ -561,6 +764,122 @@ kernel void sample_rgba8(texture2d tex [[texture(0)]], self.run_profiled_words(source, entry, input, None) } + /// Submit trusted MSL with read-only words at buffer 0 and output words at buffer 1. + /// + /// The trusted-kernel requirements of [`Self::run_words`] apply. + /// Use [`Self::wait`] to collect the result. + /// + /// # Errors + /// + /// Returns an error for invalid input or source, compilation or dispatch + /// setup failure, or a full in-flight table. + pub fn submit_words( + &self, + source: &str, + entry: &str, + input: &[u32], + ) -> Result, MetalError> { + autoreleasepool(|_| { + let host_start = self.begin_submission(); + validate_words(source, entry, input)?; + self.submit_sized( + source, + entry, + ComputeInput::Words(input), + None, + None, + host_start, + ) + }) + } + + #[doc(hidden)] + pub fn submit_words_gated( + &self, + source: &str, + entry: &str, + input: &[u32], + ) -> Result<(Submission<'_>, SubmissionGate), MetalError> { + autoreleasepool(|_| { + let host_start = self.begin_submission(); + validate_words(source, entry, input)?; + let event = self + .device + .newSharedEvent() + .ok_or_else(|| MetalError::new("newSharedEvent", "gate creation failed"))?; + let submission = self.submit_sized( + source, + entry, + ComputeInput::Words(input), + None, + Some(&event), + host_start, + )?; + Ok((submission, SubmissionGate { event })) + }) + } + + /// Wait for this context's submission and return its readback and timings. + /// + /// # Errors + /// + /// Returns an error for a token from another context, an unknown submission, + /// or a Metal completion failure. + pub fn wait(&self, submission: Submission<'_>) -> Result { + if !std::ptr::eq(self, submission.context) { + return Err(MetalError::new( + "submission", + "token belongs to another context", + )); + } + autoreleasepool(|_| { + let id = submission.id; + std::mem::forget(submission); + let result = self.take_result(id); + self.retire_completed(); + result + }) + } + + fn take_result(&self, id: u64) -> Result { + let unknown = || MetalError::new("submission", "unknown submission id"); + let command = { + let mut table = self.submissions(); + let entry = table.entries.get_mut(&id).ok_or_else(unknown)?; + entry.resources.as_ref().map(|resources| { + entry.waiting = true; + resources.command.clone() + }) + }; + let wait_seconds = command.map_or(0.0, |command| { + // Keep the table available to other submitters while Metal waits. + let start = Instant::now(); + command.waitUntilCompleted(); + start.elapsed().as_secs_f64() + }); + + let mut table = self.submissions(); + let entry = table.entries.get_mut(&id).ok_or_else(unknown)?; + entry.waiting = false; + let host_seconds = if let Some(resources) = &entry.resources { + let status = resources.command.status(); + if !is_terminal(status) { + entry.abandoned = true; + check_command_status(&resources.command, status)?; + } + entry.retire(status); + None + } else { + Some(entry.host_start.elapsed().as_secs_f64()) + }; + let mut profile = table.entries.remove(&id).ok_or_else(unknown)?.result?; + profile.wait_seconds = wait_seconds; + if let Some(host_seconds) = host_seconds { + profile.host_seconds = host_seconds; + } + Ok(profile) + } + /// Run trusted MSL with an explicit one-dimensional threadgroup width. /// /// The grid still contains one invocation per input word. The requested width @@ -608,13 +927,7 @@ kernel void sample_rgba8(texture2d tex [[texture(0)]], input: &[u32], group_width: Option, ) -> Result { - if !(1..=MAX_GRID_WORDS).contains(&input.len()) { - return Err(MetalError::new( - "dispatch bounds", - format!("expected 1..={MAX_GRID_WORDS} words, got {}", input.len()), - )); - } - validate_source(source, &[entry])?; + validate_words(source, entry, input)?; autoreleasepool(|_| self.run_sized(source, entry, ComputeInput::Words(input), group_width)) } @@ -636,7 +949,20 @@ kernel void sample_rgba8(texture2d tex [[texture(0)]], input: ComputeInput<'_>, group_width: Option, ) -> Result { - let host_start = Instant::now(); + let host_start = self.begin_submission(); + self.wait(self.submit_sized(source, entry, input, group_width, None, host_start)?) + } + + fn submit_sized( + &self, + source: &str, + entry: &str, + input: ComputeInput<'_>, + group_width: Option, + gate: Option<&ProtocolObject>, + host_start: Instant, + ) -> Result, MetalError> { + self.submissions().check_capacity()?; let options = compile_options()?; let library_start = Instant::now(); let library = self.compile_library(source, &options)?; @@ -672,17 +998,29 @@ kernel void sample_rgba8(texture2d tex [[texture(0)]], "fixture exceeds device buffer limit", )); } + let alloc_start = Instant::now(); let input_buffer = match input { ComputeInput::Words(words) => Some(self.new_buffer(words)?), ComputeInput::SampledTexture { coords, .. } => Some(self.new_buffer(coords)?), ComputeInput::Texture(..) => None, }; - let mut words = vec![0xA5A5_A5A5; input.len()]; + let words = vec![0xA5A5_A5A5; input.len()]; let output_buffer = self.new_buffer(&words)?; + let alloc_seconds = alloc_start.elapsed().as_secs_f64(); + let mut table = self.submissions(); + table.check_capacity()?; + let id = table.next_id; + table.next_id = id + .checked_add(1) + .ok_or_else(|| MetalError::new("submission", "submission ids exhausted"))?; + let encode_start = Instant::now(); let command = self .queue - .commandBuffer() + .commandBufferWithUnretainedReferences() .ok_or_else(|| MetalError::new("commandBuffer", "command buffer creation failed"))?; + if let Some(gate) = gate { + command.encodeWaitForEvent_value(gate.as_ref(), 1); + } let encoder = command.computeCommandEncoder().ok_or_else(|| { MetalError::new("computeCommandEncoder", "compute encoder creation failed") })?; @@ -710,27 +1048,49 @@ kernel void sample_rgba8(texture2d tex [[texture(0)]], } encoder.dispatchThreads_threadsPerThreadgroup(size(input.len()), size(width)); encoder.endEncoding(); - complete_command(&command)?; - let gpu_seconds = command.GPUEndTime() - command.GPUStartTime(); - let host_seconds = host_start.elapsed().as_secs_f64(); - // SAFETY: Metal copied the initialized words into distinct shared storage. - // The GPU finished before the CPU touches that storage. Both ranges are - // valid for byte_len bytes and don't overlap. A byte copy requires no - // additional alignment and all u32 bit patterns are valid. - unsafe { - copy_nonoverlapping( - output_buffer.contents().cast::().as_ptr(), - words.as_mut_ptr().cast::(), - byte_len, - ); - } - Ok(RunProfile { - library_seconds, - pipeline_seconds, - gpu_seconds, - host_seconds, - output: words, - }) + let encode_seconds = encode_start.elapsed().as_secs_f64(); + let (texture, sampler) = match input { + ComputeInput::Texture(texture, _) => (Some(texture.retain()), None), + ComputeInput::SampledTexture { + texture, sampler, .. + } => (Some(texture.retain()), Some(sampler.retain())), + ComputeInput::Words(_) => (None, None), + }; + let resources = InFlightResources { + command, + _pipeline: pipeline, + _input: input_buffer, + output: output_buffer, + _texture: texture, + _sampler: sampler, + gate: gate.map(Message::retain), + word_count: input.len(), + }; + let commit_start = Instant::now(); + resources.command.commit(); + let commit_seconds = commit_start.elapsed().as_secs_f64(); + table.entries.insert( + id, + SubmissionEntry { + resources: Some(resources), + result: Ok(RunProfile { + library_seconds, + pipeline_seconds, + gpu_seconds: 0.0, + host_seconds: 0.0, + alloc_seconds, + encode_seconds, + commit_seconds, + wait_seconds: 0.0, + readback_seconds: 0.0, + output: words, + }), + host_start, + abandoned: false, + waiting: false, + }, + ); + Ok(Submission { context: self, id }) } fn compile_library( @@ -790,6 +1150,16 @@ kernel void sample_rgba8(texture2d tex [[texture(0)]], } } +fn validate_words(source: &str, entry: &str, input: &[u32]) -> Result<(), MetalError> { + if !(1..=MAX_GRID_WORDS).contains(&input.len()) { + return Err(MetalError::new( + "dispatch bounds", + format!("expected 1..={MAX_GRID_WORDS} words, got {}", input.len()), + )); + } + validate_source(source, &[entry]) +} + fn validate_source(source: &str, entries: &[&str]) -> Result<(), MetalError> { if source.is_empty() || source.len() > MAX_SOURCE_BYTES @@ -829,11 +1199,29 @@ fn find_function( fn complete_command(command: &ProtocolObject) -> Result<(), MetalError> { command.commit(); - command.waitUntilCompleted(); + wait_command(command) +} - if command.status() != MTLCommandBufferStatus::Completed { +/// Block until a committed command buffer finishes and check its status. +fn wait_command(command: &ProtocolObject) -> Result<(), MetalError> { + command.waitUntilCompleted(); + check_command_status(command, command.status()) +} + +fn is_terminal(status: MTLCommandBufferStatus) -> bool { + matches!( + status, + MTLCommandBufferStatus::Completed | MTLCommandBufferStatus::Error + ) +} + +fn check_command_status( + command: &ProtocolObject, + status: MTLCommandBufferStatus, +) -> Result<(), MetalError> { + if status != MTLCommandBufferStatus::Completed { let error = command.error().map_or_else( - || format!("unexpected command status {:?}", command.status()), + || format!("unexpected command status {status:?}"), |error| error.localizedDescription().to_string(), ); return Err(MetalError::new("waitUntilCompleted", error)); diff --git a/crates/metal/src/lib.rs b/crates/metal/src/lib.rs index a8c56d1..22ff47c 100644 --- a/crates/metal/src/lib.rs +++ b/crates/metal/src/lib.rs @@ -16,7 +16,8 @@ pub mod texture_pipeline; pub use compute::{ BlendDraw, BlendFactor, BlendOperation, BlendPass, BlendState, ColorWriteMask, DepthCompare, DepthDraw, DepthFill, DepthOutput, DepthPass, DepthState, GuestBuffer, GuestBufferView, - IndexBuffer, IndexedDraw, IndexedPass, MetalError, NativeCompute, RunProfile, + IndexBuffer, IndexedDraw, IndexedPass, MetalError, NativeCompute, RunProfile, Submission, + SubmissionGate, }; #[cfg(all(target_arch = "aarch64", target_os = "macos"))] diff --git a/crates/metal/tests/native/submission.rs b/crates/metal/tests/native/submission.rs new file mode 100644 index 0000000..0afbdd5 --- /dev/null +++ b/crates/metal/tests/native/submission.rs @@ -0,0 +1,104 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +use super::{context, fixture, native}; + +const ENTRY: &str = "fixture"; +const INPUT: [u32; 4] = [0, 1, 71, u32::MAX]; +const LIMIT: usize = 16; + +fn source() -> String { + fixture("output[id] = input[id] * 3u + 7u;") +} + +fn expected(input: &[u32]) -> Vec { + input + .iter() + .map(|word| word.wrapping_mul(3).wrapping_add(7)) + .collect() +} + +#[test] +fn sweep_keeps_resources_until_completion() { + let metal = context(); + let source = source(); + let (a, gate) = native(metal.submit_words_gated(&source, ENTRY, &INPUT)); + assert_eq!(metal.in_flight(), 1); + let b = native(metal.submit_words(&source, ENTRY, &INPUT)); + assert_eq!(metal.in_flight(), 2); + gate.open(); + assert_eq!(native(metal.wait(a)).output, expected(&INPUT)); + assert_eq!(native(metal.wait(b)).output, expected(&INPUT)); + assert_eq!(metal.in_flight(), 0); +} + +#[test] +fn batch_can_be_collected_in_either_order() { + let metal = context(); + let source = source(); + for reverse in [false, true] { + let mut batch = Vec::new(); + for seed in 0..8 { + let input = INPUT.map(|word| word.wrapping_add(seed)); + batch.push((input, native(metal.submit_words(&source, ENTRY, &input)))); + } + if reverse { + batch.reverse(); + } + for (input, submission) in batch { + let output = native(metal.wait(submission)).output; + assert_eq!(output, expected(&input)); + assert_eq!(output, native(metal.run_words(&source, ENTRY, &input))); + } + assert_eq!(metal.tracked(), 0); + } +} + +#[test] +fn full_queue_returns_in_flight_limit_error() { + let metal = context(); + let source = source(); + let (first, gate) = native(metal.submit_words_gated(&source, ENTRY, &INPUT)); + let mut tokens = vec![first]; + for _ in 1..LIMIT { + tokens.push(native(metal.submit_words(&source, ENTRY, &INPUT))); + } + assert_eq!(metal.in_flight(), LIMIT); + let Err(error) = metal.submit_words(&source, ENTRY, &INPUT) else { + panic!("submission past the in-flight limit succeeded"); + }; + assert_eq!(error.operation, "in-flight limit"); + gate.open(); + for token in tokens { + assert_eq!(native(metal.wait(token)).output, expected(&INPUT)); + } + assert_eq!(metal.in_flight(), 0); +} + +#[test] +fn dropped_token_retires_after_completion() { + let metal = context(); + let source = source(); + let (a, gate) = native(metal.submit_words_gated(&source, ENTRY, &INPUT)); + drop(a); + let b = native(metal.submit_words(&source, ENTRY, &INPUT)); + assert_eq!(metal.in_flight(), 2); + drop(gate); + assert_eq!(native(metal.wait(b)).output, expected(&INPUT)); + assert_eq!(metal.in_flight(), 0); + assert_eq!(metal.tracked(), 0); +} + +#[test] +fn finished_result_survives_later_submission() { + let metal = context(); + let source = source(); + let a = native(metal.submit_words(&source, ENTRY, &INPUT)); + let b = native(metal.submit_words(&source, ENTRY, &[9])); + assert_eq!(native(metal.wait(b)).output, expected(&[9])); + assert_eq!(metal.in_flight(), 0); + assert_eq!(metal.tracked(), 1); + let profile = native(metal.wait(a)); + assert_eq!(profile.output, expected(&INPUT)); + assert_eq!(profile.wait_seconds, 0.0); + assert_eq!(metal.tracked(), 0); +} diff --git a/crates/metal/tests/native_compute.rs b/crates/metal/tests/native_compute.rs index 2e80250..933cb97 100644 --- a/crates/metal/tests/native_compute.rs +++ b/crates/metal/tests/native_compute.rs @@ -16,6 +16,8 @@ mod indexed; mod indexed_cases; #[path = "native/offscreen.rs"] mod offscreen; +#[path = "native/submission.rs"] +mod submission; #[path = "native/texture.rs"] mod texture; #[path = "native/texture_bc_alpha.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/crates/shader/src/lib.rs b/crates/shader/src/lib.rs index bd41abe..3eae65c 100644 --- a/crates/shader/src/lib.rs +++ b/crates/shader/src/lib.rs @@ -195,15 +195,18 @@ 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 => "<=", 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 { + if op.signed() { format!("as_type({left}) {symbol} as_type({right})") } else { format!("{left} {symbol} {right}") @@ -485,7 +488,7 @@ pub fn compile(architecture: Architecture, bytes: &[u8]) -> Result 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 9cb8104..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 | 0 | 12 | 12 | 12 | 0 | 0 | 0 | -| **Total** | 1465 | 100 | 68 | 104 | 100 | 100 | 18 | 18 | 37 | +| VOPC | 190 | 16 | 16 | 16 | 16 | 16 | 0 | 0 | 7 | +| **Total** | 1465 | 104 | 84 | 108 | 104 | 104 | 18 | 18 | 44 | ## Unsupported operand variants @@ -48,3 +48,4 @@ 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` | +| 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 90af58a..dd706b1 100644 --- a/docs/shaders/semantic-registry.md +++ b/docs/shaders/semantic-registry.md @@ -60,9 +60,9 @@ error. | `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 | -| `scc` | What the form writes to SCC | `carry_out`, `borrow`, `signed_overflow`, `nonzero`, `relation` (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` | -| `wave` | Wave sizes the form is valid in | `any` (`wave32` is in the vocabulary but rejected until the decoder can enforce it) | +| `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` | | `operands` | Name of an `[operand_rules]` entry for the same family | e.g. `sop2_sgpr` | | `spec` | References `{ document, section, page }` | at least one `guide` reference with a page above 0 | | `verify` | Evidence the form needs before it counts as verified | `reference`, `independent`, `metal`, `llvm_encoding` | @@ -105,7 +105,15 @@ must be `unchanged` (VOP2 integer forms write no SCC, VCC or EXEC): | `min`, `max` / `signed` or `unsigned` | `MinSigned`, `MinUnsigned`, `MaxSigned`, `MaxUnsigned` | | `mul24`, `mul_hi24` / `signed` or `unsigned` | `Mul24Signed`, `Mul24Unsigned`, `MulHi24Signed`, `MulHi24Unsigned` | -A compare must use an operand rule of the compare kind (`sopc_scalar`: two +VOPC compares (operand rule `vopc_vcc`, kind `vector_compare`: SRC0 a +`vector_source` as for VOP2, VSRC1 a VGPR, destination implicitly `vcc_lo`) +take the same `relation` and primitive as SOPC compares, but declare +`scc = "unchanged"`, `vcc = "lane_mask"` and `wave = "wave32"`. The XML's implicit +64-bit VCC output must be present and is accounted for by `lane_mask`. Signedness +still matters for `eq` and `lg`, because the MSL lowering casts signed operands. +`v_cmpx_*` (EXEC writes), the VOP3 encoding and Wave64 stay unsupported. + +A SOPC compare must use an operand rule of the compare kind (`sopc_scalar`: two sources, no destination), a unary operation one of the unary kind (`sop1_sgpr`: one source and an SGPR destination), and a two-source ALU operation `sop2_sgpr`. @@ -119,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 e8acb63..56dd577 100644 --- a/docs/shaders/vector-compare.md +++ b/docs/shaders/vector-compare.md @@ -53,8 +53,13 @@ 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 +(`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), @@ -95,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. @@ -194,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 @@ -202,7 +207,13 @@ 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. -The same file runs each form against 10 boundary values (0, 1, 0x7ffffffe, +`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`. + +`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 @@ -210,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/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 0000000..a12df66 Binary files /dev/null and b/fixtures/rdna2/vector-compare-ft.bin differ 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 5384ffb..e7c1b5c 100644 --- a/tests/semantics_generator/test_generate_semantics.py +++ b/tests/semantics_generator/test_generate_semantics.py @@ -144,9 +144,34 @@ 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, 135, 192, 197)], + } + 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. + "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 +242,29 @@ 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_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 + + def compares(): reg = registry() reg["form"] += [ @@ -738,7 +786,113 @@ 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_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() + self.assertEqual(self.errors(reg), []) + text = gen.render(reg, snapshot()) + 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()) + 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() 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..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(); @@ -1802,12 +1841,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..]); @@ -1894,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"); } } diff --git a/tests/validation/tests/vopc_f_t.rs b/tests/validation/tests/vopc_f_t.rs new file mode 100644 index 0000000..522ec48 --- /dev/null +++ b/tests/validation/tests/vopc_f_t.rs @@ -0,0 +1,704 @@ +// 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; +/// XORed with v1 to give every lane its own old v2 before a masked move. +const OLD: u32 = 0x0bad_f00d; + +const COUNTS: [(&str, usize); 12] = [ + ("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 * 4), + ("vopc exec unchanged", 4 * 2), +]; +/// 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 + 2 + 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 } + })); + } + // 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 +} + +/// 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 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); + 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); + // 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()); + } +} + +#[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() + ); +}