Compare commits

...
Author SHA1 Message Date
Ranveer Soni 430f63e27d Merge branch 'main' into task/266-native-app-gate3 2026-11-24 16:42:24 +05:30
Swastick Chowdhury 9e47234e92 app: persistent guest rendering with pause, resume and stop (#266)
Add persistent frame-loop guest rendering (Gate 3) through the versioned
C runtime interface. The guest fixture (fixtures/pe/frame-loop.exe,
generated by fixtures/pe/frame-loop.py) runs on a dedicated guest thread,
calling xenora.dll!frame_submit(index) until commanded to halt. Each frame
is rendered on native Metal, verified against the geometry strip rule, and
returned as read-back RGBA8 buffers.

Add xenora_session_start_frame_loop, xenora_session_pause_frame_loop,
xenora_session_resume_frame_loop, xenora_session_stop_frame_loop, and
xenora_session_frame_loop_status to the C interface, plus new states.
Destroying a live session safely stops and joins the guest loop without
holding the global session lock.

Xenora.app gains persistent frame-loop controls (start 300 frames, pause,
resume, stop) and displays live frames with their index and completion
count. Add --smoke-loop CLI flag and wire the five GPU acceptance tests
into scripts/test-gpu.sh.

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 16:37:34 +05:30
Ranveer Soni cd224d86f4 Merge pull request #272 from Swastickc/task/63-rex-x-sib
loader: extend the SIB index register with REX.X, not REX.R (#63)
2026-11-24 16:29:21 +05:30
Ranveer Soni dd4bcb30eb Merge pull request #273 from elforeign/task/215-sop2-arith
isa, decoder: sixteen SOP2 integer forms through the semantic registry (#215)
2026-11-24 16:29:07 +05:30
elforeign 3392c226ce validation: SCC stays unset across SOP2 forms that do not write it; compiler rejections at the SOP2 word (#215)
Review follow-up: four programs run BFM, MUL or MUL_HI and then CSELECT
with SCC never written, and every interpreter and the compiler must
refuse the CSELECT. The native test now also requires the compiler to
reject each program at the same word as the interpreters, so a later
failure cannot stand in (shown by a translator that turns an unset SCC
into false, which only this check catches).

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:56:28 -06:00
Swastick Chowdhury 78df3a5c6b loader: extend the SIB index register with REX.X, not REX.R (#63)
The interpreter used REX.R to extend the SIB index field and ignored REX.X
entirely, so the two paths disagreed with the native DBT translator, which
already extends the index with REX.X.

Two defects are fixed in the SIB branch of the MOV r/m effective-address
computation:

- The index register is now extended by REX.X. REX.R extends the ModRM reg
  field and must not affect the index.
- A SIB index field of 100b selects r12 when REX.X is set, and means "no
  index register" only when REX.X is clear.

REX.X is decoded from the REX prefix into the typed Prefixes struct.

Add regression tests covering an extended index register including r12, an
independent REX.R and REX.X combination, both prefix bits set together, and
the no-index case. Every encoding was produced by LLVM 23.1.6 llvm-mc and the
expected addresses were derived from the Intel SDM SIB rules.

The three REX.X tests fail against the unfixed interpreter and pass with the
fix; the no-index test passes in both cases.

Closes #63

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 16:24:57 +05:30
elforeign 133c9df448 Merge remote-tracking branch 'origin/main' into task/215-sop2-arith 2026-11-24 04:54:47 -06:00
elforeign 00f79c10d2 isa, decoder, shader: sixteen SOP2 integer forms through the semantic registry (#215)
Adds s_min/max_{i32,u32}, s_cselect_b32, s_bfm_b32, s_mul_i32,
s_mul_hi_{u32,i32}, s_bfe_{u32,i32}, s_absdiff_i32 and
s_lshl1..4_add_u32 as registry data over new shared primitives. The
vocabulary gains a selected_src0 SCC effect (min and max: S0 won the
strict compare), the select's SCC input (carry_in = scc, required for
cselect), a declared shift_amount for the shift-and-add forms, and a
check that BFE's S1 descriptor is unsigned in the XML. The generated
ScalarAluOp::evaluate now returns an optional SCC, so forms whose XML
shows no SCC output leave it unchanged in the translator. The decoder
picks them up through the generated SOP2 table; the oracle merged from
task/215-sop2-arith-oracle supplies the reference side. A new
LLVM-assembled fixture chains all sixteen.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:51:33 -06:00
Ranveer Soni ee2d29a65c Merge pull request #271 from Swastickc/task/267-app-inspect
app: open a PE executable and show read-only compatibility diagnostics (#267)
2026-11-24 16:12:12 +05:30
Ranveer Soni 83ef49c258 Merge branch 'main' into task/267-app-inspect 2026-11-24 16:11:56 +05:30
elforeign 84b6fb4d50 Merge branch 'task/215-sop2-arith-oracle' into task/215-sop2-arith 2026-11-24 04:41:40 -06:00
Swastick Chowdhury 7fa240f7ba app: open a PE executable and show read-only compatibility diagnostics (#267)
Add xenora_inspect_executable to the C interface: a bounded, read-only
report from the static probe and loader validation (hash, headers,
sections, imports not provided by the standard runtime services, DBT
coverage of the bounded disassembly, relocation and TLS counts). Nothing
in the file is executed. A probe panic becomes a report labelled as a
Xenora defect (#270). Xenora.app opens files via Open Executable..., drag
and drop, and Finder (alternate viewer for Windows executables).

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 16:09:15 +05:30
elforeign 0e9211cd42 validation: s105 operands for the SOP2 integer forms; s_min_i32 is no longer an unsupported example (#215)
A review found that every passing sop2_arith case wrote s8-s10, so an
interpreter refusing a high destination would pass; s105 now appears as
destination, either source and all three. known_answers used s_min_i32
as an opcode outside the subset; it is supported now, so s_cselect_b64
takes its place.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:38:51 -06:00
elforeign c41e034fa1 ref, validation: 16 SOP2 integer forms in both interpreters (#215)
xenora_ref and independent_ref now run s_min/max_{i32,u32},
s_cselect_b32, s_bfm_b32, s_mul_i32, s_bfe_{u32,i32}, s_absdiff_i32,
s_lshl1..4_add_u32 and s_mul_hi_{u32,i32} as the RDNA 2 ISA guide 12.1
describes, so the guide-derived sop2_arith expectations pass on both.
CSELECT reads SCC and is refused when SCC was never written; CSELECT,
BFM, MUL_I32 and MUL_HI leave SCC unchanged. The second interpreter
uses bit loops, a ripple adder and shift-and-add products rather than
the reference's host arithmetic.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:36:31 -06:00
Ranveer Soni 7977dd4bf2 Merge pull request #268 from elforeign/task/215-sop1
isa, decoder: eleven SOP1 unary forms through the semantic registry (#215)
2026-11-24 16:06:11 +05:30
Ranveer Soni cd948d4a14 Merge pull request #269 from Swastickc/task/62-prefix-struct
loader: group interpreter instruction prefixes into a typed struct (#62)
2026-11-24 16:05:46 +05:30
elforeign a2c696b551 validation: guide-derived expectations for 16 SOP2 integer forms (#215)
Expected D and SCC for s_min/max_{i32,u32}, s_cselect_b32, s_bfm_b32,
s_mul_i32, s_bfe_{u32,i32}, s_absdiff_i32, s_lshl1..4_add_u32 and
s_mul_hi_{u32,i32}, written from the RDNA 2 ISA guide (12.1 and the
section 5 tables) before either interpreter supports them, so both fail
here. A separate guide-only table agrees on all 5086 shared inputs.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:34:26 -06:00
Swastick Chowdhury d6189ae3ea loader: group interpreter instruction prefixes into a typed struct (#62)
Replace the #[allow(clippy::too_many_arguments)] on execute_mov_rm with a
Prefixes struct that carries rex_w, rex_r, rex_b, seg_gs and seg_fs. The
interpreter decodes the prefixes once per instruction and passes the struct to
the helpers that need them, so the lint is satisfied by construction instead
of suppressed.

Add a regression test module that pins the prefix and register-extension
behaviour of the interpreter: REX.R and REX.B selecting the expected ModRM
reg and rm registers, the two bits extending independent fields, a move
without REX.W staying 32-bit wide, and the FS prefix adding the FS base.
The test was run against unmodified main first and passed there, so the
refactor is shown to preserve semantics.

Closes #62

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 16:02:10 +05:30
elforeign e6eece6983 validation: require the compiler's SOP1 rejections at the SOP1 word (#215)
Review follow-up: the native test only checked that compilation failed,
so a regressed destination guard still passed when a later instruction
read an uninitialized SGPR (shown by allowing vcc_lo as a destination).
It now requires a decode error at the SOP1 offset. Also check that no
registry form duplicates a hand-written decoder form.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:30:44 -06:00
elforeign 1a78265ede Merge remote-tracking branch 'origin/main' into task/215-sop1
# Conflicts:
#	CHANGELOG.md
2026-11-24 04:27:26 -06:00
elforeign 2e0e5a36f6 isa, decoder, shader: SOP1 unary integer forms through the semantic registry (#215)
Adds eleven SOP1 forms as registry data: complement, bit reverse, bit
counts, find-first and find-last searches, sign extension and absolute
value. Sign extension declares source_bits, which the generator checks
against the XML's 8- and 16-bit source operands; forms whose XML shows
no SCC output must declare SCC unchanged. The decoder dispatches them
through the generated SOP1 table after s_mov_b32, and the translator
folds them with ScalarUnaryOp::evaluate. The separately written oracle
from task/215-sop1-oracle supplies the reference side.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:27:14 -06:00
Ranveer Soni ece0fc27eb Merge pull request #265 from Swastickc/task/263-native-app-gate2
app: show the trusted fixture's guest-driven Metal frame (Gate 2, #263)
2026-11-24 15:56:25 +05:30
Swastick Chowdhury 82f2d9e9e6 app: show the trusted fixture's guest-driven Metal frame (#263)
Add xenora_session_run_trusted_fixture to the C interface. It runs only
the embedded trusted PE fixture through DBT startup; the guest's
fixture_draw import compiles the x9 RDNA2 shaders to MSL and renders on
native Metal. The 4x3 RGBA8 read-back is returned only when the guest
halts with the runner's expected results and every pixel equals the
pixel shader's export. Xenora.app shows the frame; --smoke-frame prints
it. Add a gpu-tests test run by scripts/test-gpu.sh.

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 15:56:07 +05:30
elforeign 391367a531 Merge branch 'task/215-sop1-oracle' into task/215-sop1 2026-11-24 04:23:47 -06:00
Ranveer Soni e71a3da525 Merge pull request #264 from elforeign/task/215-stage-d
isa, decoder: SOPC integer compares through the semantic registry (#215 stage D)
2026-11-24 15:52:40 +05:30
elforeign b96511bfc5 validation: cover s105 in the SOP1 unary cases (#215)
Review found that every register operand was s8 or s10, so a decoder that
dropped the top bit of SDST or SSRC0 would pass. s105 now appears as source,
destination and both.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:22:34 -06:00
elforeign 84bb80d910 ref, validation: evaluate eleven SOP1 unary forms in both interpreters (#215)
Both interpreters now run s_not/brev/bcnt0/bcnt1/ff0/ff1/flbit(_b32)/
sext_i8/sext_i16/abs with SDST s0-s105. Not-found searches return -1,
s_flbit_i32 returns -1 for 0 and -1, abs keeps 0x80000000, and only NOT,
BCNT0, BCNT1 and ABS write SCC (D != 0). The reference uses host bit
intrinsics; the second interpreter works from an explicit bit array and
arithmetic, so they do not share an evaluation path.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:20:56 -06:00
elforeign 9edf644d77 Merge remote-tracking branch 'origin/main' into task/215-stage-d 2026-11-24 04:20:17 -06:00
elforeign b5d0382e89 semantics, docs: review follow-ups for the SOPC compares (#215)
Malformed relations and operand rules are diagnostics instead of
Python exceptions; the fixture now really carries a SOPC literal (LLVM
had encoded 0xffffffff as inline -1); the reference-interpreter table
and registry field table describe the current forms; the docs and
changelog state separately that the 348 rejections run on the CPU
interpreters and the compiler, not on Metal.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:20:16 -06:00
elforeign b705104403 validation: guide-derived expectations for eleven SOP1 unary forms (#215)
D and SCC for s_not/brev/bcnt0/bcnt1/ff0/ff1/flbit(_b32)/sext_i8/sext_i16/abs
are written from the RDNA 2 ISA guide (12.3 pseudocode and examples, Tables 12
and 14 for SCC) before either interpreter implements them.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:19:31 -06:00
Ranveer Soni f148b51a48 Merge pull request #262 from Swastickc/task/261-native-app-gate1
app: native macOS shell and versioned C runtime interface (Gate 1, #261)
2026-11-24 15:46:34 +05:30
elforeign c979870b3a Merge remote-tracking branch 'origin/main' into task/215-stage-d 2026-11-24 04:16:09 -06:00
elforeign cd59e081d9 isa, decoder: SOPC integer compares through the semantic registry (#215 stage D)
Adds a compare operation with a declared relation and the sopc_scalar
operand rule, so all twelve s_cmp_*_{i32,u32} forms are registry data.
The decoder dispatches them through the generated OP table and the
translator resolves SCC with ScalarCompareOp::test; the hand-written
s_cmp_eq_u32 path and its opcode constant are gone. A new LLVM-assembled
fixture records every compare's SCC, and the separately written oracle
from task/215-stage-d-oracle supplies the reference side.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:16:09 -06:00
Ranveer Soni 0bfb12fd17 Merge branch 'main' into task/261-native-app-gate1 2026-11-24 15:45:49 +05:30
Swastick Chowdhury c6d0986da2 app: add native macOS shell and versioned C runtime interface (#261)
Add crates/ffi, a static library exposing a version 1 C interface with
opaque generation-checked session handles, stable status codes and
panic containment. It can create and destroy sessions and parse the
bundled trusted PE fixture; no guest code runs. Add a minimal SwiftUI
app (Swift Package Manager) that links it, and scripts/build-app.sh to
build an ad-hoc signed, arm64-only Xenora.app and run its smoke check.

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 15:43:08 +05:30
Ranveer Soni 9a9422c7da Merge pull request #260 from elforeign/task/215-stage-c
isa: eight SOP2 logical and shift forms through the semantic registry (#215 stage C)
2026-11-24 15:41:50 +05:30
elforeign da41b6420d Merge branch 'task/215-stage-d-oracle' into task/215-stage-d 2026-11-24 04:10:54 -06:00
elforeign 3f710928af validation: close four blind spots in the stage D cases (#215)
Review found cases that a broken implementation would still pass: an inline
or literal value that compares like its neighbour against both registers, an
extra write to the SCC-setting scratch SGPR s12, and rejections accepted at
any offset. Inline and literal cases now also compare a value with itself,
s12 is read back, and every rejection must happen at the SOPC word.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:10:00 -06:00
elforeign 2fdf01fbb3 ref, validation: evaluate the twelve SOPC integer compares in both interpreters (#215)
Both interpreters now run s_cmp_{eq,lg,gt,ge,lt,le}_{i32,u32}: SCC = S0 <rel>
S1, signed for opcodes 0-5 and unsigned for 6-11, with no SGPR written. The
reference keeps Op::CompareEqual for the two EQ opcodes (its public shape is
used by other crates' tests) and adds Op::ScalarCompare for the rest, reusing
the VOPC relation; the second interpreter orders signed operands by flipping
the sign bits, so the two do not share the comparison code.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:08:32 -06:00
elforeign de00cb2bfd Merge remote-tracking branch 'origin/main' into task/215-stage-c 2026-11-24 04:08:15 -06:00
elforeign d8f9669280 semantics: require exact XML number formats and a sane count width (#215)
Review follow-up: a shift count must be FMT_NUM_U32 and other sources
must have the format their signedness implies, so a float format no
longer passes; a negative shift_count_bits is a diagnostic instead of a
crash. The stage C rows cite the guide pages where the forms are listed,
and the scalar ALU page names which suite covers which forms.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:08:15 -06:00
elforeign 19b2e9b5d5 semantics: dispatch through a generated OP-indexed table (#215)
With 17 forms the generated match on the masked word cost about 0.4 ns
(4 %) more per decoded SOP2 instruction than main. The generator now
emits a fixed-bits test plus a static table indexed by the OP field,
both derived from the XML snapshot and checked to select exactly the
same words; decoding is back to main's speed (10.05 ns).

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:07:17 -06:00
Ranveer Soni bb6bc52c95 Merge pull request #258 from Swastickc/task/80-pe-mapping-limits
loader: bound total mapped PE image size before allocation (#80)
2026-11-24 15:37:11 +05:30
Ranveer Soni ba6bbb2e4a Merge pull request #259 from Swastickc/task/77-teb-startup-bounds
loader: validate startup stack and TEB layout before mapping (#77)
2026-11-24 15:36:51 +05:30
elforeign 705b074a08 validation: guide-derived expectations for the stage D scalar compares (#215)
SCC for s_cmp_{eq,lg,gt,ge,lt,le}_{i32,u32} is written from the RDNA 2 ISA
guide (12.4, 13.1.4, 5.3) before either interpreter implements the new forms,
with cases for both branch edges, unchanged SGPRs and rejected operands.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:05:59 -06:00
elforeign d3c1150854 changelog: stage C SOP2 forms through the registry (#215)
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:04:22 -06:00
elforeign a81d62ffe3 decoder: map the stage C SOP2 operations onto the reference in the consistency test (#215)
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:04:00 -06:00
elforeign 8d53d82981 Merge branch 'task/215-stage-c-oracle' into task/215-stage-c 2026-11-24 04:03:01 -06:00
elforeign ba2cfc2a00 validation: close two blind spots in the stage C cases (#215)
Review found that one register operand per inline constant hides some wrong
inline values (ANDN2 with s8 = 0x80000f0f cannot tell 16 from 0), and that the
odd-opcode check used a misaligned SGPR pair. Each inline now runs against a
word and its complement, and the 64-bit neighbours read aligned pairs.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:02:10 -06:00
elforeign b13ab327f2 ref, validation: evaluate the stage C SOP2 forms in both interpreters (#215)
The reference interpreter and the second, independent interpreter now run
s_andn2/orn2/nand/nor/xnor_b32, s_lshl/lshr_b32 and s_ashr_i32 per the RDNA 2
guide: shifts use only S1[4:0] and every form sets SCC = (D != 0). The two use
different arithmetic (host bit ops vs per-bit and power-of-two evaluation),
so they cannot share a mistake with each other or with the expectations.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:00:28 -06:00
Swastick Chowdhury e7cb8db14f loader: bound total mapped PE image size before allocation (#80)
Sum max(VirtualSize, SizeOfRawData) over all sections and reject images
above a 256 MiB loader budget with SectionMappingError(AllocationFailed)
before any host allocation. Adds pe_mapping_limits tests.

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 15:29:34 +05:30
elforeign e7795d0e5a validation: guide-derived expectations for the stage C SOP2 forms (#215)
Expected D and SCC for s_andn2/orn2/nand/nor/xnor_b32, s_lshl/lshr_b32 and
s_ashr_i32 are written from the RDNA 2 ISA guide (12.1, 5.3) before either
interpreter implements them, so the implementation cannot shape the oracle.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:57:55 -06:00
elforeign ff191d89bd isa: declare eight more SOP2 logical and shift forms in the registry (#215 stage C, WIP)
Adds andn2, orn2, nand, nor, xnor, lshl, lshr and ashr as registry
primitives with a declared shift-count width that the generator applies
as a mask and checks against the XML's unsigned count operand. The forms
reach the decoder and translator through the generated dispatch with no
per-form Rust. The independent oracle side lands separately.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:55:00 -06:00
66 changed files with 10713 additions and 286 deletions

No files matched your search

+3
View File
@@ -37,3 +37,6 @@ __pycache__/
*.pyc
/diagnostics/gta6-candidate-*/
/diagnostics/gta6-check/
# Native application build output
/app/.build/
+6
View File
@@ -10,7 +10,13 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
remains unsupported.
### Added
- 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 eleven gfx1030 SOP1 unary forms through the semantic registry: `s_not_b32`, `s_brev_b32`, `s_bcnt0_i32_b32`, `s_bcnt1_i32_b32`, `s_ff0_i32_b32`, `s_ff1_i32_b32`, `s_flbit_i32_b32`, `s_flbit_i32`, `s_sext_i32_i8`, `s_sext_i32_i16` and `s_abs_i32` (AMD guide section 12.3). Searches that find nothing return -1, `s_abs_i32` of 0x80000000 stays 0x80000000, and only NOT, BCNT0, BCNT1 and ABS write SCC. The registry gained these primitives, a `sop1_sgpr` operand rule, and a declared `source_bits` for sign extension that is checked against the XML's 8- and 16-bit source operands. The reference and independent semantic-review interpreters, written separately from the guide, evaluate the same eleven forms and are checked against 4,126 guide-derived cases on both CPU interpreters and on native Metal with validation; 231 rejected programs are refused by both interpreters and by the compiler. A new LLVM-assembled fixture covers all eleven. Part of #215.
- Showed the first guest-driven frame in the native app (Gate 2, #263). The C interface gains `xenora_session_run_trusted_fixture`, which runs only the embedded trusted PE fixture: its x86-64 code is translated and executed, its `xenora.dll!fixture_draw` call compiles the x9 RDNA2 shader fixtures to MSL and renders on the native Metal device, and the 4×3 RGBA8 read-back is returned only if the guest halts with the CLI runner's expected results and every pixel equals the pixel shader's export, (1, 0, 0, 1) as opaque red. Xenora.app's "Run trusted fixture" button shows that frame, and `--smoke-frame` prints it. A `gpu-tests` test, run by `scripts/test-gpu.sh`, executes the fixture three times through the interface with Metal validation enabled. The frame is a read-back image, not drawable presentation, and no caller-supplied executable can run. Verified on one Apple Silicon Mac; the window was checked by screenshot.
- Added a minimal native macOS application shell and its Rust interface (Gate 1 of the native application work). `crates/ffi` builds a static library with a versioned C interface (`crates/ffi/include/xenora.h`, version 1): opaque, generation-checked 64-bit session handles (never pointers), at most 64 live sessions, stable status codes, and panics caught at the boundary. Version 1 can only create and destroy sessions and parse the bundled trusted PE fixture; it executes no guest code. `app/` is a SwiftUI app built with Swift Package Manager that shows the interface version and the fixture's section count and entry point. `scripts/build-app.sh` builds an ad-hoc-signed, arm64-only `build/Xenora.app` with no entitlements and runs its `--smoke` check. Six Rust tests cover invalid, stale and double-destroyed handles, version mismatch, null outputs, 4,000 concurrent create and destroy cycles, and header/constant agreement. The CLI and headless workflows are unchanged. Verified locally on one Apple Silicon Mac (macOS 27.2.1, Swift 6.4, Rust 1.100.0); not yet run in CI.
- Added the gfx1030 SOPC compares `s_cmp_{eq,lg,gt,ge,lt,le}_{i32,u32}` through the semantic registry, which replaces the hand-written `s_cmp_eq_u32` path. Each sets only SCC to whether the relation holds with SSRC0 on the left (AMD guide section 12.4); the registry gained a `compare` operation with a declared `relation` and a `sopc_scalar` operand rule. `Instruction::ScalarCompareEqU32` is now `Instruction::ScalarCompare { op: ScalarCompareOp, .. }`; `s_cmp_eq_u32` behaves as before. The reference and independent semantic-review interpreters, written separately from the guide, evaluate all twelve, checked against 7,824 guide-derived cases on both CPU interpreters and on native Metal with validation; 348 rejected programs are refused by both interpreters and by the compiler. A new LLVM-assembled fixture covers all twelve. Two literal selectors stay rejected. Part of #215, stage D.
- Added eight gfx1030 SOP2 forms through the semantic registry alone: `s_andn2_b32`, `s_orn2_b32`, `s_nand_b32`, `s_nor_b32`, `s_xnor_b32`, `s_lshl_b32`, `s_lshr_b32` and `s_ashr_i32`, each with SCC = result != 0. Each is one registry entry with no per-form Rust; the registry gained these primitives and a declared shift-count width (`shift_count_bits = 5`, so shifts use S1[4:0] as in the AMD guide, section 12.1), which the generator applies as a mask and checks against the XML's unsigned count operand. The reference interpreter and the independent semantic-review interpreter, written separately from the guide, now evaluate the same eight forms and are checked against 6,896 guide-derived cases; a new LLVM-assembled fixture (`fixtures/rdna2/scalar-logic.s`) runs on CPU and native Metal with validation. A NULL destination (s125) stays rejected. Part of #215, stage C.
- Added an independent operand-domain verification harness for the 9 supported SOP2 scalar ALU forms and 12 VOPC integer compares (`tests/validation/tests/operand_domains.rs`, part of #215 stage E): 4,788 generated cases (boundary values, 64-bit carry and borrow chains, aliased registers, every integer inline constant, literals, s105 and v255, partial and zero EXEC, VCCZ) and 498 rejections (missing literal words, and encodings outside Xenora's supported subset) run on `xenora_ref` and, as an ignored test picked up by `scripts/test-gpu.sh`, on native Metal. Expected values come from the public AMD RDNA 2 guide's pseudocode, written out in the test without Xenora code; this is agreement with a spec-derived reference, not with Xbox hardware. Local verification only: 32 deliberate code breaks were each caught; the guide leaves the width of `S1 + SCC` in `s_subb_u32` open, and those 8 cases are kept in their own family.
- Added a declarative semantic registry for gfx1030 instruction forms (`crates/isa/semantics/rdna2.toml`, schema 1) and its generator, `crates/isa/generate_semantics.py`, with `validate`, `generate` and `--check` modes. The generator checks every declaration against a closed vocabulary and the pinned AMD XML snapshot (opcode, family, SCC input and output, operand widths and signed formats), rejects contradictory, incomplete or duplicate definitions, and emits static Rust tables marked as generated. The nine SOP2 forms moved onto it with no change in behaviour: the decoder's SOP2 dispatch and `ScalarAluOp`'s mnemonic, SCC read and evaluation are now generated, and evaluation goes through shared primitives instead of per-opcode code. All existing SOP2 tests, including the native Metal known answers and the LLVM comparison, pass unchanged. Decoding speed is unchanged (10.2 ns before, 10.1 ns after, per SOP2 instruction, release build on an Apple M5 Pro). Also added `scripts/audit/semantic_coverage.py`, which generates `docs/shaders/semantic-coverage.md`: per-family counts of identified, declared, decoded, lowered, reference-verified and Metal-verified forms, taking evidence only from `docs/status.toml`. Part of #215, stages A and B.
- Added a native Metal blend pass, `NativeCompute::render_blend`: up to 16 flat-coloured triangles drawn in order into an RGBA8 target, each with its own colour write mask (any subset of R, G, B, A) and either blending disabled or separate RGB and alpha blend factors (Zero, One, source and destination colour and alpha, and their one-minus forms) and operations (Add, Subtract, ReverseSubtract, and Min and Max, which take the unweighted values). Checked on the GPU with Metal validation in 39 passes over two original overlapping triangles: a clear-only pass; blending disabled; each source factor with the destination term zeroed and each destination factor with the source term zeroed; every operation; additive clamping; separate alpha factors; a separate alpha operation; eight write masks (each channel alone, RGB, none, RGBA, and RG with blending); and a pass whose first draw is itself blended and masked. Colours are compared per channel against images derived independently (in exact fractions) from the public Metal blend equations, which a new CPU reference in `xenora-ref` also reproduces. The tolerance was fixed before measuring: channels whose exact result is a whole 8-bit value must match exactly, and channels that need rounding may differ by 1. On an Apple M5 Pro every rounded channel matched round-to-nearest exactly. Synthetic fixtures only; no console blend state is involved.
Generated
+9
View File
@@ -179,6 +179,15 @@ dependencies = [
"xenora-ref",
]
[[package]]
name = "xenora-ffi"
version = "0.1.0"
dependencies = [
"xenora-loader",
"xenora-metal",
"xenora-shader",
]
[[package]]
name = "xenora-import-gen"
version = "0.1.0"
+13
View File
@@ -0,0 +1,13 @@
// swift-tools-version: 6.0
// SPDX-License-Identifier: GPL-3.0-or-later
// Build with scripts/build-app.sh, which builds the Rust static library first.
import PackageDescription
let package = Package(
name: "Xenora",
platforms: [.macOS(.v14)],
targets: [
.systemLibrary(name: "CXenora", path: "Sources/CXenora"),
.executableTarget(name: "Xenora", dependencies: ["CXenora"]),
]
)
+5
View File
@@ -0,0 +1,5 @@
module CXenora [system] {
header "../../../crates/ffi/include/xenora.h"
link "xenora_ffi"
export *
}
+431
View File
@@ -0,0 +1,431 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//
// Native shell over the versioned C interface. "Run trusted fixture" executes the
// bundled trusted PE fixture (x86-64 translated to ARM64; its draw request is rendered
// by native Metal) and shows the verified read-back frame. No other executable can run.
import AppKit
import CXenora
import Foundation
import SwiftUI
import UniformTypeIdentifiers
struct RuntimeProbe {
var abiVersion: UInt32 = 0
var status: Int32 = -1
var sections: UInt32 = 0
var entryRVA: UInt32 = 0
var connected: Bool { abiVersion == XENORA_ABI_VERSION && status == XENORA_OK }
static func run() -> RuntimeProbe {
var probe = RuntimeProbe(abiVersion: xenora_abi_version())
var session: xenora_session = 0
probe.status = xenora_session_create(XENORA_ABI_VERSION, &session)
guard probe.status == XENORA_OK else { return probe }
defer { _ = xenora_session_destroy(session) }
probe.status = xenora_session_inspect_trusted_fixture(session, &probe.sections, &probe.entryRVA)
return probe
}
var summary: String {
String(format: "abi=%u status=%d sections=%u entry_rva=0x%x", abiVersion, status, sections, entryRVA)
}
}
/// The frame produced by one run of the trusted fixture.
struct GuestFrame {
let status: Int32
let width: Int
let height: Int
let rgba: [UInt8]
static func run() -> GuestFrame {
var session: xenora_session = 0
var status = xenora_session_create(XENORA_ABI_VERSION, &session)
guard status == XENORA_OK else { return GuestFrame(status: status, width: 0, height: 0, rgba: []) }
defer { _ = xenora_session_destroy(session) }
var rgba = [UInt8](repeating: 0, count: Int(XENORA_FIXTURE_FRAME_WIDTH * XENORA_FIXTURE_FRAME_HEIGHT * 4))
var width: UInt32 = 0
var height: UInt32 = 0
status = rgba.withUnsafeMutableBufferPointer { buffer in
xenora_session_run_trusted_fixture(session, buffer.baseAddress, UInt64(buffer.count), &width, &height)
}
return GuestFrame(status: status, width: Int(width), height: Int(height), rgba: status == XENORA_OK ? rgba : [])
}
var image: CGImage? {
guard status == XENORA_OK, let provider = CGDataProvider(data: Data(rgba) as CFData) else { return nil }
return CGImage(
width: width, height: height, bitsPerComponent: 8, bitsPerPixel: 32, bytesPerRow: width * 4,
space: CGColorSpaceCreateDeviceRGB(),
bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue),
provider: provider, decode: nil, shouldInterpolate: false, intent: .defaultIntent)
}
var summary: String {
let first = rgba.prefix(4).map(String.init).joined(separator: ",")
return "status=\(status) frame=\(width)x\(height) first_pixel=\(first)"
}
}
/// Owns the latest fixture run. A class with @Published avoids SwiftUI macros,
/// which the command-line toolchain does not ship.
@MainActor
final class FrameModel: ObservableObject {
@Published var frame: GuestFrame?
@Published var running = false
func run() {
running = true
Task {
// The fixture blocks while it executes and renders, so keep it off the main thread.
frame = await Task.detached { GuestFrame.run() }.value
running = false
}
}
}
/// Persistent guest rendering model (Gate 3, #266).
@MainActor
final class FrameLoopModel: ObservableObject {
@Published var state: UInt32 = UInt32(XENORA_LOOP_NONE)
@Published var completed: UInt32 = 0
@Published var frameId: UInt32 = XENORA_NO_FRAME
@Published var image: CGImage?
@Published var errorMessage: String?
private var session: xenora_session = 0
private var pollTask: Task<Void, Never>?
deinit {
pollTask?.cancel()
if session != 0 {
_ = xenora_session_destroy(session)
}
}
var isRunning: Bool { state == UInt32(XENORA_LOOP_RUNNING) }
var isPaused: Bool { state == UInt32(XENORA_LOOP_PAUSED) }
var canStart: Bool {
session == 0 || state == UInt32(XENORA_LOOP_NONE) || state == UInt32(XENORA_LOOP_FINISHED)
|| state == UInt32(XENORA_LOOP_STOPPED) || state == UInt32(XENORA_LOOP_FAILED)
}
var stateDescription: String {
switch state {
case UInt32(XENORA_LOOP_NONE): return "Idle"
case UInt32(XENORA_LOOP_RUNNING): return "Running"
case UInt32(XENORA_LOOP_PAUSED): return "Paused"
case UInt32(XENORA_LOOP_FINISHED): return "Finished"
case UInt32(XENORA_LOOP_STOPPED): return "Stopped"
case UInt32(XENORA_LOOP_FAILED): return "Failed"
default: return "Unknown (\(state))"
}
}
func start(frameCount: UInt32 = 300) {
errorMessage = nil
if session != 0 {
_ = xenora_session_destroy(session)
session = 0
}
var newSession: xenora_session = 0
let createStatus = xenora_session_create(XENORA_ABI_VERSION, &newSession)
guard createStatus == XENORA_OK else {
errorMessage = "Failed to create session (status \(createStatus))"
return
}
session = newSession
let startStatus = xenora_session_start_frame_loop(session, frameCount)
guard startStatus == XENORA_OK else {
errorMessage = "Failed to start frame loop (status \(startStatus))"
_ = xenora_session_destroy(session)
session = 0
return
}
state = UInt32(XENORA_LOOP_RUNNING)
completed = 0
frameId = XENORA_NO_FRAME
image = nil
startPolling()
}
func pause() {
guard session != 0 else { return }
_ = xenora_session_pause_frame_loop(session)
}
func resume() {
guard session != 0 else { return }
_ = xenora_session_resume_frame_loop(session)
}
func stop() {
guard session != 0 else { return }
_ = xenora_session_stop_frame_loop(session)
}
private func startPolling() {
pollTask?.cancel()
pollTask = Task { [weak self] in
while !Task.isCancelled {
try? await Task.sleep(nanoseconds: 16_000_000)
guard let self = self, self.session != 0 else { break }
var st: UInt32 = 0
var comp: UInt32 = 0
var fId: UInt32 = 0
var rgba = [UInt8](repeating: 0, count: Int(XENORA_FIXTURE_FRAME_WIDTH * XENORA_FIXTURE_FRAME_HEIGHT * 4))
let code = rgba.withUnsafeMutableBufferPointer { buffer in
xenora_session_frame_loop_status(
self.session, &st, &comp, &fId, buffer.baseAddress, UInt64(buffer.count))
}
guard code == XENORA_OK else { break }
self.state = st
self.completed = comp
self.frameId = fId
if fId != XENORA_NO_FRAME, let provider = CGDataProvider(data: Data(rgba) as CFData) {
self.image = CGImage(
width: Int(XENORA_FIXTURE_FRAME_WIDTH),
height: Int(XENORA_FIXTURE_FRAME_HEIGHT),
bitsPerComponent: 8,
bitsPerPixel: 32,
bytesPerRow: Int(XENORA_FIXTURE_FRAME_WIDTH) * 4,
space: CGColorSpaceCreateDeviceRGB(),
bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue),
provider: provider,
decode: nil,
shouldInterpolate: false,
intent: .defaultIntent
)
}
if st != UInt32(XENORA_LOOP_RUNNING) && st != UInt32(XENORA_LOOP_PAUSED) {
break
}
}
}
}
}
/// Read-only compatibility inspection of a user-chosen file. Nothing in it is executed.
@MainActor
final class InspectionModel: ObservableObject {
static let shared = InspectionModel()
@Published var fileName: String?
@Published var report = ""
@Published var status: Int32 = Int32(XENORA_OK)
@Published var busy = false
@Published var importing = false
func inspect(_ url: URL) {
fileName = url.lastPathComponent
busy = true
Task {
let (newStatus, newReport) = await Task.detached { InspectionModel.run(url) }.value
status = newStatus
report = newReport
busy = false
}
}
nonisolated static func run(_ url: URL) -> (Int32, String) {
let scoped = url.startAccessingSecurityScopedResource()
defer { if scoped { url.stopAccessingSecurityScopedResource() } }
// Check the size before reading so an oversized file is never loaded into memory.
guard let size = (try? url.resourceValues(forKeys: [.fileSizeKey]))?.fileSize else {
return (Int32(XENORA_INVALID_ARGUMENT), "Could not read the file's size.")
}
guard UInt64(size) <= UInt64(XENORA_MAX_INSPECT_BYTES) else {
return (Int32(XENORA_LIMIT_EXCEEDED), "The file is \(size) bytes; inspection accepts at most \(XENORA_MAX_INSPECT_BYTES).")
}
guard let data = try? Data(contentsOf: url) else {
return (Int32(XENORA_INVALID_ARGUMENT), "Could not read the file.")
}
return data.withUnsafeBytes { raw in
let bytes = raw.bindMemory(to: UInt8.self).baseAddress
var required: UInt64 = 0
var probe: CChar = 0
var status = xenora_inspect_executable(bytes, UInt64(data.count), &probe, 1, &required)
guard status == Int32(XENORA_BUFFER_TOO_SMALL) else { return (status, "Inspection failed (status \(status)).") }
var text = [CChar](repeating: 0, count: Int(required))
status = xenora_inspect_executable(bytes, UInt64(data.count), &text, required, &required)
return (status, String(cString: text))
}
}
}
/// Receives files opened from Finder (double-click or Open With).
final class AppDelegate: NSObject, NSApplicationDelegate {
func application(_ application: NSApplication, open urls: [URL]) {
guard let url = urls.first else { return }
MainActor.assumeIsolated { InspectionModel.shared.inspect(url) }
}
}
struct InspectorView: View {
@ObservedObject var model: InspectionModel
var body: some View {
Section("Executable inspection (read-only)") {
HStack {
Button("Open Executable…") { model.importing = true }
Text("or drop a file on this window").foregroundStyle(.secondary)
}
if let name = model.fileName {
LabeledContent("File", value: model.busy ? "\(name) (inspecting…)" : name)
ScrollView {
Text(model.report)
.font(.system(.caption, design: .monospaced))
.textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading)
}
.frame(minHeight: 160, maxHeight: 320)
}
Text("Opened files are inspected only. Running them is not available.")
.font(.callout)
.foregroundStyle(.secondary)
}
}
}
struct ContentView: View {
let probe = RuntimeProbe.run()
@ObservedObject var model: FrameModel
@ObservedObject var loop: FrameLoopModel
@ObservedObject var inspection = InspectionModel.shared
private var frame: GuestFrame? { model.frame }
private var running: Bool { model.running }
var body: some View {
Form {
InspectorView(model: inspection)
Section("Guest display") {
if let image = frame?.image {
Image(decorative: image, scale: 1)
.resizable()
.interpolation(.none)
.aspectRatio(contentMode: .fit)
.frame(maxWidth: .infinity, minHeight: 120, maxHeight: 240)
.accessibilityLabel("Guest frame, \(frame!.width) by \(frame!.height) pixels")
Text("Guest code ran, its draw was rendered by native Metal, and all \(frame!.width * frame!.height) pixels matched the fixture shader's output.")
.font(.callout)
.foregroundStyle(.secondary)
} else if let frame {
Text("Run failed (status \(frame.status)). No frame is shown.")
.foregroundStyle(.red)
}
Button(running ? "Running…" : "Run trusted fixture") { model.run() }
.disabled(running || !probe.connected)
}
Section("Persistent frame loop") {
if let image = loop.image {
Image(decorative: image, scale: 1)
.resizable()
.interpolation(.none)
.aspectRatio(contentMode: .fit)
.frame(maxWidth: .infinity, minHeight: 120, maxHeight: 240)
.accessibilityLabel("Guest frame #\(loop.frameId)")
Text("Frame #\(loop.frameId) (\(loop.completed) completed) • \(loop.stateDescription)")
.font(.callout)
.foregroundStyle(.secondary)
} else if let error = loop.errorMessage {
Text(error).foregroundStyle(.red)
} else if loop.state != UInt32(XENORA_LOOP_NONE) {
Text("State: \(loop.stateDescription) • \(loop.completed) completed")
.font(.callout)
.foregroundStyle(.secondary)
}
HStack {
Button("Start 300 frames") { loop.start(frameCount: 300) }
.disabled(!loop.canStart || !probe.connected)
Button("Pause") { loop.pause() }
.disabled(!loop.isRunning)
Button("Resume") { loop.resume() }
.disabled(!loop.isPaused)
Button("Stop") { loop.stop() }
.disabled(!loop.isRunning && !loop.isPaused)
}
}
LabeledContent("Runtime", value: probe.connected ? "Connected" : "Unavailable (status \(probe.status))")
LabeledContent("Interface version", value: "\(probe.abiVersion)")
LabeledContent("Trusted fixture sections", value: "\(probe.sections)")
LabeledContent("Trusted fixture entry RVA", value: String(format: "0x%X", probe.entryRVA))
Text("Only the bundled trusted fixture and frame-loop guest can run. Presentation uses read-back Metal frames. Arbitrary executables and input are not available yet.")
.foregroundStyle(.secondary)
}
.formStyle(.grouped)
.fileImporter(isPresented: $inspection.importing, allowedContentTypes: [.item]) { result in
if case .success(let url) = result { inspection.inspect(url) }
}
.dropDestination(for: URL.self) { urls, _ in
guard let url = urls.first, url.isFileURL else { return false }
inspection.inspect(url)
return true
}
.frame(minWidth: 520, minHeight: 680)
}
}
struct XenoraApp: App {
@NSApplicationDelegateAdaptor(AppDelegate.self) var delegate
let model = FrameModel()
let loop = FrameLoopModel()
var body: some Scene {
WindowGroup("Xenora") { ContentView(model: model, loop: loop) }
}
}
// `--inspect <path>` prints the read-only report for a file and exits with its status.
if let flag = CommandLine.arguments.firstIndex(of: "--inspect"), flag + 1 < CommandLine.arguments.count {
let (status, report) = InspectionModel.run(URL(fileURLWithPath: CommandLine.arguments[flag + 1]))
print(report.hasSuffix("\n") ? report : report + "\n", terminator: "")
print("status=\(status)")
exit(status == Int32(XENORA_OK) ? 0 : 1)
}
// `--smoke-loop` runs 300 frames on the Metal device and exits; it needs a GPU.
if CommandLine.arguments.contains("--smoke-loop") {
var session: xenora_session = 0
guard xenora_session_create(XENORA_ABI_VERSION, &session) == XENORA_OK else {
print("failed to create session")
exit(1)
}
defer { _ = xenora_session_destroy(session) }
guard xenora_session_start_frame_loop(session, 300) == XENORA_OK else {
print("failed to start frame loop")
exit(1)
}
var state: UInt32 = 0
var completed: UInt32 = 0
var frameId: UInt32 = 0
var rgba = [UInt8](repeating: 0, count: Int(XENORA_FIXTURE_FRAME_WIDTH * XENORA_FIXTURE_FRAME_HEIGHT * 4))
while true {
let code = rgba.withUnsafeMutableBufferPointer { buf in
xenora_session_frame_loop_status(session, &state, &completed, &frameId, buf.baseAddress, UInt64(buf.count))
}
if code != XENORA_OK {
print("frame_loop_status failed: \(code)")
exit(1)
}
if state != UInt32(XENORA_LOOP_RUNNING) { break }
Thread.sleep(forTimeInterval: 0.005)
}
print("state=\(state) completed=\(completed) frame_id=\(frameId)")
exit(state == UInt32(XENORA_LOOP_FINISHED) && completed == 300 ? 0 : 1)
}
// `--smoke-frame` runs the trusted fixture on the Metal device and exits; it needs a GPU.
if CommandLine.arguments.contains("--smoke-frame") {
let frame = GuestFrame.run()
print(frame.summary)
exit(frame.status == XENORA_OK ? 0 : 1)
}
// `--smoke` prints the probe and exits without opening a window, for scripts and CI.
if CommandLine.arguments.contains("--smoke") {
let probe = RuntimeProbe.run()
print(probe.summary)
exit(probe.connected ? 0 : 1)
}
XenoraApp.main()
+23 -13
View File
@@ -4,15 +4,15 @@ use std::fmt;
pub use xenora_isa::{
Architecture, CompareRelation, ExportTarget, Instruction, InterpolationPhase, ScalarAluOp,
ScalarSource, VectorCompareOp, VectorSource,
ScalarCompareOp, ScalarSource, ScalarUnaryOp, VectorCompareOp, VectorSource,
};
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_CMP_EQ_U32, S_ENDPGM, S_MOV_B32, S_WAITCNT, S_WAITCNT_VSCNT,
V_ADD_F32, V_ADD_NC_U32, V_AND_B32, V_ASHRREV_I32, V_CMP_EQ_I32, V_CMP_EQ_U32, V_CMP_GE_I32,
V_CMP_GE_U32, V_CMP_GT_I32, V_CMP_GT_U32, V_CMP_LE_I32, V_CMP_LE_U32, V_CMP_LT_I32,
V_CMP_LT_U32, V_CMP_NE_I32, V_CMP_NE_U32, V_INTERP_P1_F32, V_INTERP_P2_F32, V_LSHLREV_B32,
V_LSHRREV_B32, V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32, VCC_LO,
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,
};
use xenora_isa::meta::EncodingFamily;
@@ -41,7 +41,7 @@ const fn concat_forms<const N: usize>() -> [(&'static str, EncodingFamily); N] {
}
/// Decoded forms not yet described by the semantic registry.
const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 37] = [
const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 36] = [
("BUFFER_LOAD_DWORD", EncodingFamily::Mubuf),
("BUFFER_STORE_DWORD", EncodingFamily::Mubuf),
("EXP", EncodingFamily::Exp),
@@ -50,7 +50,6 @@ const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 37] = [
("S_CBRANCH_EXECZ", EncodingFamily::Sopp),
("S_CBRANCH_SCC0", EncodingFamily::Sopp),
("S_CBRANCH_VCCZ", EncodingFamily::Sopp),
("S_CMP_EQ_U32", EncodingFamily::Sopc),
("S_ENDPGM", EncodingFamily::Sopp),
("S_MOV_B32", EncodingFamily::Sop1),
("S_WAITCNT", EncodingFamily::Sopp),
@@ -375,19 +374,30 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
let (src, len) = scalar_source(first as u8, bytes, "s_mov_b32")?;
return Ok((Instruction::ScalarMoveB32 { dst, src }, len));
}
if S_CMP_EQ_U32.matches(first) {
if let Some(op) = ScalarUnaryOp::from_word(first) {
// SOP1: SSRC0 in bits 0-7, SDST in bits 16-22.
let mnemonic = op.mnemonic();
let dst = ((first >> 16) & 0x7f) as u8;
if dst > 105 {
return Err(unsupported(mnemonic, "expected a normal SGPR destination"));
}
let (src, len) = scalar_source(first as u8, bytes, mnemonic)?;
return Ok((Instruction::ScalarUnary { op, dst, src }, len));
}
if let Some(op) = ScalarCompareOp::from_word(first) {
let mnemonic = op.mnemonic();
let src0_bits = first as u8;
let src1_bits = (first >> 8) as u8;
if src0_bits == 255 && src1_bits == 255 {
return Err(unsupported(
"s_cmp_eq_u32",
mnemonic,
"only one source may select a literal",
));
}
let (src0, len0) = scalar_source(src0_bits, bytes, "s_cmp_eq_u32")?;
let (src1, len1) = scalar_source(src1_bits, bytes, "s_cmp_eq_u32")?;
let (src0, len0) = scalar_source(src0_bits, bytes, mnemonic)?;
let (src1, len1) = scalar_source(src1_bits, bytes, mnemonic)?;
return Ok((
Instruction::ScalarCompareEqU32 { src0, src1 },
Instruction::ScalarCompare { op, src0, src1 },
len0.max(len1),
));
}
+66 -5
View File
@@ -4,9 +4,12 @@ use std::process::{Command, Stdio};
use xenora_decoder::{
Architecture, CompareRelation, DecodeError, DecodeErrorKind, DecodedInstruction, Instruction,
ScalarAluOp, ScalarSource, VectorSource, decode, decode_at,
ScalarAluOp, ScalarSource, ScalarUnaryOp, VectorSource, decode, decode_at,
};
use xenora_isa::semantics::Signedness;
use xenora_ref::{
BranchCondition, CompareSource, Comparison, Op, ScalarAlu, ScalarUnary, Source, VectorAlu,
};
use xenora_ref::{BranchCondition, CompareSource, Comparison, Op, ScalarAlu, Source, VectorAlu};
const FIXTURE: &[u8] = include_bytes!("../../../fixtures/rdna2/add.bin");
const BITWISE_FIXTURE: &[u8] = include_bytes!("../../../fixtures/rdna2/bitwise-branch.bin");
@@ -340,6 +343,30 @@ fn reference_op(instruction: Instruction) -> Op {
ScalarAluOp::AndB32 => ScalarAlu::And,
ScalarAluOp::OrB32 => ScalarAlu::Or,
ScalarAluOp::XorB32 => ScalarAlu::Xor,
ScalarAluOp::Andn2B32 => ScalarAlu::AndNot,
ScalarAluOp::Orn2B32 => ScalarAlu::OrNot,
ScalarAluOp::NandB32 => ScalarAlu::Nand,
ScalarAluOp::NorB32 => ScalarAlu::Nor,
ScalarAluOp::XnorB32 => ScalarAlu::Xnor,
ScalarAluOp::LshlB32 => ScalarAlu::ShiftLeft,
ScalarAluOp::LshrB32 => ScalarAlu::ShiftRight,
ScalarAluOp::AshrI32 => ScalarAlu::ArithmeticShiftRight,
ScalarAluOp::MinI32 => ScalarAlu::Minimum { signed: true },
ScalarAluOp::MinU32 => ScalarAlu::Minimum { signed: false },
ScalarAluOp::MaxI32 => ScalarAlu::Maximum { signed: true },
ScalarAluOp::MaxU32 => ScalarAlu::Maximum { signed: false },
ScalarAluOp::CselectB32 => ScalarAlu::Select,
ScalarAluOp::BfmB32 => ScalarAlu::BitfieldMask,
ScalarAluOp::MulI32 => ScalarAlu::Multiply,
ScalarAluOp::BfeU32 => ScalarAlu::BitfieldExtract { signed: false },
ScalarAluOp::BfeI32 => ScalarAlu::BitfieldExtract { signed: true },
ScalarAluOp::AbsdiffI32 => ScalarAlu::AbsoluteDifference,
ScalarAluOp::Lshl1AddU32 => ScalarAlu::ShiftLeftAdd(1),
ScalarAluOp::Lshl2AddU32 => ScalarAlu::ShiftLeftAdd(2),
ScalarAluOp::Lshl3AddU32 => ScalarAlu::ShiftLeftAdd(3),
ScalarAluOp::Lshl4AddU32 => ScalarAlu::ShiftLeftAdd(4),
ScalarAluOp::MulHiU32 => ScalarAlu::MultiplyHigh { signed: false },
ScalarAluOp::MulHiI32 => ScalarAlu::MultiplyHigh { signed: true },
},
dst,
reference_scalar(src0),
@@ -347,8 +374,38 @@ fn reference_op(instruction: Instruction) -> Op {
),
Instruction::AddNoCarryU32 { dst, src0, src1 } => Op::Add(dst, src0, src1),
Instruction::ScalarMoveB32 { dst, src } => Op::ScalarMove(dst, reference_scalar(src)),
Instruction::ScalarCompareEqU32 { src0, src1 } => {
Op::CompareEqual(reference_scalar(src0), reference_scalar(src1))
Instruction::ScalarUnary { op, dst, src } => Op::ScalarUnary(
match op {
ScalarUnaryOp::NotB32 => ScalarUnary::Not,
ScalarUnaryOp::BrevB32 => ScalarUnary::ReverseBits,
ScalarUnaryOp::Bcnt0I32B32 => ScalarUnary::CountZeros,
ScalarUnaryOp::Bcnt1I32B32 => ScalarUnary::CountOnes,
ScalarUnaryOp::Ff0I32B32 => ScalarUnary::FindFirstZero,
ScalarUnaryOp::Ff1I32B32 => ScalarUnary::FindFirstOne,
ScalarUnaryOp::FlbitI32B32 => ScalarUnary::FindLastBit,
ScalarUnaryOp::FlbitI32 => ScalarUnary::FindLastSignBit,
ScalarUnaryOp::SextI32I8 => ScalarUnary::SignExtendByte,
ScalarUnaryOp::SextI32I16 => ScalarUnary::SignExtendShort,
ScalarUnaryOp::AbsI32 => ScalarUnary::Absolute,
},
dst,
reference_scalar(src),
),
Instruction::ScalarCompare { op, src0, src1 } => {
let (src0, src1) = (reference_scalar(src0), reference_scalar(src1));
// The reference keeps CompareEqual for EQ and uses its VOPC relation
// offsets (LT 1, EQ 2, LE 3, GT 4, NE 5, GE 6) for the rest.
match op.relation() {
CompareRelation::Equal => Op::CompareEqual(src0, src1),
relation => Op::ScalarCompare(
Comparison {
offset: relation as u8 + 1,
signed: op.semantics().signedness == Signedness::Signed,
},
src0,
src1,
),
}
}
Instruction::BranchSccZero { target } => Op::Branch {
target,
@@ -434,13 +491,17 @@ fn compares_fixture_instructions_against_llvm() {
SHIFT_FIXTURE,
include_bytes!("../../../fixtures/rdna2/ashr.bin"),
include_bytes!("../../../fixtures/rdna2/scalar-alu.bin"),
include_bytes!("../../../fixtures/rdna2/scalar-logic.bin"),
include_bytes!("../../../fixtures/rdna2/scalar-compare.bin"),
include_bytes!("../../../fixtures/rdna2/scalar-unary.bin"),
include_bytes!("../../../fixtures/rdna2/scalar-arith.bin"),
include_bytes!("../../../fixtures/rdna2/vector-compare.bin"),
high_registers,
&matrix,
] {
count += compare_against_llvm(fixture, &mut forms);
}
assert_eq!(forms.len(), 42, "forms compared: {forms:?}");
assert_eq!(forms.len(), 88, "forms compared: {forms:?}");
eprintln!(
"{count} three-way instruction comparisons across {} forms",
forms.len()
+8
View File
@@ -49,3 +49,11 @@ fn declared_semantic_forms_are_exactly_those_decoded_from_fixtures() {
);
}
}
#[test]
fn registry_forms_do_not_duplicate_hand_written_forms() {
// A form declared in the semantic registry and also decoded by hand-written
// code would have two implementations; the hand-written one would win.
let unique: BTreeSet<_> = SEMANTIC_FORMS.into_iter().collect();
assert_eq!(unique.len(), SEMANTIC_FORMS.len());
}
+22
View File
@@ -0,0 +1,22 @@
[package]
name = "xenora-ffi"
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
description = "Versioned C interface between the native macOS application and the Xenora runtime"
[lib]
crate-type = ["staticlib", "rlib"]
[lints]
workspace = true
[features]
# Runs the tests that need a native Metal device (scripts/test-gpu.sh).
gpu-tests = []
[dependencies]
xenora-loader = { path = "../loader" }
xenora-metal = { path = "../metal" }
xenora-shader = { path = "../shader" }
+132
View File
@@ -0,0 +1,132 @@
/* SPDX-License-Identifier: GPL-3.0-or-later */
/*
* Xenora native application interface, version 1.
*
* Every function returns a xenora_status. Sessions are identified by opaque
* 64-bit handles, never by pointers; 0 is never a valid handle. A destroyed
* handle stays invalid even if its slot is reused. Output pointers are owned
* by the caller and are written only when the call returns XENORA_OK.
* All functions are thread-safe. No Rust panic crosses this boundary: one is
* reported as XENORA_INTERNAL_ERROR.
*/
#ifndef XENORA_H
#define XENORA_H
#include <stdint.h>
#define XENORA_ABI_VERSION 1u
typedef int32_t xenora_status;
enum {
XENORA_OK = 0,
XENORA_INVALID_ARGUMENT = 1,
XENORA_INVALID_HANDLE = 2,
XENORA_VERSION_MISMATCH = 3,
XENORA_INTERNAL_ERROR = 4,
XENORA_PE_ERROR = 5,
XENORA_LIMIT_EXCEEDED = 6,
XENORA_BUFFER_TOO_SMALL = 7,
XENORA_EXECUTION_FAILED = 8,
XENORA_INVALID_STATE = 9,
};
/* Frame-loop states reported by xenora_session_frame_loop_status. */
enum {
XENORA_LOOP_NONE = 0,
XENORA_LOOP_RUNNING = 1,
XENORA_LOOP_PAUSED = 2,
XENORA_LOOP_FINISHED = 3,
XENORA_LOOP_STOPPED = 4,
XENORA_LOOP_FAILED = 5,
};
#define XENORA_FRAME_LOOP_MAX_FRAMES 100000u
/* Frame id reported when no frame has been completed yet. */
#define XENORA_NO_FRAME 0xFFFFFFFFu
/* Size of the frame drawn by the trusted fixture: RGBA8, rows top to bottom. */
#define XENORA_FIXTURE_FRAME_WIDTH 4u
#define XENORA_FIXTURE_FRAME_HEIGHT 3u
typedef uint64_t xenora_session;
/* The interface version this library implements. */
uint32_t xenora_abi_version(void);
/* Create a session. `abi_version` must equal XENORA_ABI_VERSION. */
xenora_status xenora_session_create(uint32_t abi_version, xenora_session *out_session);
/* Destroy a session. Destroying it again returns XENORA_INVALID_HANDLE. */
xenora_status xenora_session_destroy(xenora_session session);
/* Parse the bundled trusted PE fixture with the runtime loader. No guest code runs. */
xenora_status xenora_session_inspect_trusted_fixture(
xenora_session session,
uint32_t *out_section_count,
uint32_t *out_entry_rva);
/*
* Run the bundled trusted PE fixture: its x86-64 code is translated and executed,
* and its single draw request is rendered on the native Metal device. On XENORA_OK,
* `out_rgba` holds width * height * 4 bytes of the read-back frame, which has been
* checked against the fixture shader's known output. `capacity` is the size of
* `out_rgba` in bytes. Blocks the calling thread; call it off the main thread.
* Only the embedded fixture can run; no caller-supplied executable is accepted.
*/
xenora_status xenora_session_run_trusted_fixture(
xenora_session session,
uint8_t *out_rgba,
uint64_t capacity,
uint32_t *out_width,
uint32_t *out_height);
/*
* Persistent rendering (one frame loop per session). Start runs the embedded
* frame-loop fixture on a session-owned guest thread: the guest submits frames
* 0, 1, 2, ... and each is rendered on native Metal and verified before it
* becomes the latest frame. The guest stops after `frame_count` frames
* (1..=XENORA_FRAME_LOOP_MAX_FRAMES). Pause holds the guest at its next frame
* submission; resume continues it; stop makes it leave its loop and halt, and
* waits for its thread. Destroying the session stops the loop first. Starting a
* second loop on the same session returns XENORA_INVALID_STATE.
*/
xenora_status xenora_session_start_frame_loop(xenora_session session, uint32_t frame_count);
xenora_status xenora_session_pause_frame_loop(xenora_session session);
xenora_status xenora_session_resume_frame_loop(xenora_session session);
xenora_status xenora_session_stop_frame_loop(xenora_session session);
/*
* Report the loop's state, the number of completed frames, and the latest
* verified frame: its id (XENORA_NO_FRAME if none yet) and, when one exists,
* its RGBA8 pixels (XENORA_FIXTURE_FRAME_WIDTH x HEIGHT) in `out_rgba`.
*/
xenora_status xenora_session_frame_loop_status(
xenora_session session,
uint32_t *out_state,
uint32_t *out_completed,
uint32_t *out_frame_id,
uint8_t *out_rgba,
uint64_t capacity);
/* Largest file xenora_inspect_executable accepts, in bytes. */
#define XENORA_MAX_INSPECT_BYTES 268435456u
/*
* Read-only compatibility inspection of a caller-supplied PE file. Nothing in
* `bytes` is executed: it is parsed and statically disassembled (bounded) only.
* On XENORA_OK, XENORA_PE_ERROR or XENORA_INTERNAL_ERROR, `out_report` holds a
* NUL-terminated UTF-8 report of `*out_required` bytes including the NUL.
* XENORA_PE_ERROR means the file is not an acceptable PE32+ image;
* XENORA_INTERNAL_ERROR means Xenora's own probe failed on it. The report says which. If `capacity`
* is too small the call returns XENORA_BUFFER_TOO_SMALL with `*out_required`
* set and nothing else written. Files over XENORA_MAX_INSPECT_BYTES return
* XENORA_LIMIT_EXCEEDED.
*/
xenora_status xenora_inspect_executable(
const uint8_t *bytes,
uint64_t length,
char *out_report,
uint64_t capacity,
uint64_t *out_required);
#endif
+243
View File
@@ -0,0 +1,243 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Persistent guest rendering for one session (Gate 3, #266).
//!
//! The embedded `frame-loop.exe` fixture calls `xenora.dll!frame_submit(index)`
//! with index 0, 1, 2, ... and halts when the call returns 0. The guest runs on
//! its own thread for the session's lifetime. Pause, resume and stop act at the
//! frame-submit boundary: a paused guest waits inside that call with its
//! architectural state untouched, and a stop request makes the call return 0 so
//! the guest leaves its loop and halts.
use std::cell::RefCell;
use std::sync::{Arc, Condvar, Mutex, MutexGuard};
use std::thread::JoinHandle;
use xenora_loader::startup::{StartupLayout, run_synthetic_startup};
use xenora_loader::{ExitReason, ImportRegistry, Register};
use xenora_metal::NativeCompute;
use xenora_shader::{Architecture, PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics};
const FIXTURE: &[u8] = include_bytes!("../../../fixtures/pe/frame-loop.exe");
pub const WIDTH: usize = 4;
pub const HEIGHT: usize = 3;
pub const FRAME_BYTES: usize = WIDTH * HEIGHT * 4;
pub const MAX_FRAMES: u32 = 100_000;
/// Guest instructions per loop iteration (mov, call, inc, test, jnz) plus slack.
const STEPS_PER_FRAME: usize = 8;
/// `x9-constant-ps.s` exports (1, 0, 0, 1): opaque red. Everything else is the clear colour.
const RED: [u8; 4] = [255, 0, 0, 255];
const CLEAR: [u8; 4] = [19, 43, 93, 251];
pub const RUNNING: u32 = 1;
pub const PAUSED: u32 = 2;
pub const FINISHED: u32 = 3;
pub const STOPPED: u32 = 4;
pub const FAILED: u32 = 5;
#[derive(Default)]
struct State {
status: u32,
paused: bool,
stop: bool,
limit: u32,
completed: u32,
/// Every `frame_submit` call the guest made, including the one answered with 0.
calls: u64,
latest: Option<(u32, Vec<u8>)>,
}
#[derive(Default)]
pub struct FrameLoop {
state: Mutex<State>,
wake: Condvar,
thread: Mutex<Option<JoinHandle<()>>>,
}
pub struct Snapshot {
pub status: u32,
pub completed: u32,
pub latest: Option<(u32, Vec<u8>)>,
}
impl FrameLoop {
fn lock(&self) -> MutexGuard<'_, State> {
self.state
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
pub fn start(limit: u32) -> Arc<Self> {
let shared = Arc::new(Self::default());
{
let mut state = shared.lock();
state.status = RUNNING;
state.limit = limit;
}
let guest = Arc::clone(&shared);
let handle = std::thread::Builder::new()
.name("xenora-guest".into())
.spawn(move || guest.run())
.ok();
if handle.is_none() {
shared.lock().status = FAILED;
}
*shared.thread.lock().unwrap_or_else(|p| p.into_inner()) = handle;
shared
}
/// Pause or resume. Returns false unless the loop is running or paused.
pub fn set_paused(&self, paused: bool) -> bool {
let mut state = self.lock();
if !matches!(state.status, RUNNING | PAUSED) {
return false;
}
state.paused = paused;
state.status = if paused { PAUSED } else { RUNNING };
self.wake.notify_all();
true
}
/// Ask the guest to stop at its next frame submission and wait for its thread.
pub fn stop(&self) {
{
let mut state = self.lock();
state.stop = true;
self.wake.notify_all();
}
if let Some(handle) = self.thread.lock().unwrap_or_else(|p| p.into_inner()).take() {
let _ = handle.join();
}
}
pub fn snapshot(&self) -> Snapshot {
let state = self.lock();
Snapshot {
status: state.status,
completed: state.completed,
latest: state.latest.clone(),
}
}
fn run(self: Arc<Self>) {
let outcome = self.execute();
let mut state = self.lock();
state.status = match outcome {
Err(_) => FAILED,
Ok(()) if state.stop && state.completed < state.limit => STOPPED,
Ok(()) => FINISHED,
};
}
fn execute(self: &Arc<Self>) -> Result<(), String> {
let shader = compile_graphics(
Architecture::Gfx1030,
include_bytes!("../../../fixtures/rdna2/x9-constant-vs.bin"),
include_bytes!("../../../fixtures/rdna2/x9-constant-ps.bin"),
)
.map_err(|e| format!("shader translation: {e}"))?;
let gpu = NativeCompute::new().map_err(|e| format!("Metal device: {e}"))?;
// The session's GPU resources live on the guest thread, where the import runs.
GPU.with(|slot| *slot.borrow_mut() = Some((gpu, shader.msl)));
let shared = Arc::clone(self);
let mut imports = ImportRegistry::new();
imports.register("xenora.dll", "frame_submit", move |args, _, memory| {
let index = args.get(0, memory).map_err(ExitReason::MemoryFault)?;
shared
.submit(index)
.ok_or(ExitReason::IllegalInstruction(0xff))
});
let limit = self.lock().limit as usize;
let startup = run_synthetic_startup(
FIXTURE,
StartupLayout {
image_base: 0x1_4000_0000,
stack_top: 0x2_0001_0000,
tls_base: 0x3_0000_0000,
},
imports,
(limit + 1) * STEPS_PER_FRAME + 16,
)
.map_err(|e| format!("startup: {e}"));
GPU.with(|slot| slot.borrow_mut().take());
let startup = startup?;
let calls = self.lock().calls;
let rbx = startup.execution.final_state.get(Register::Rbx);
// The guest increments RBX after every call, so it must equal the calls we served.
if startup.execution.exit_reason != ExitReason::Halt || rbx != calls {
return Err(format!(
"guest ended with {:?}, rbx={rbx}, calls={calls}",
startup.execution.exit_reason
));
}
Ok(())
}
/// Handle one `frame_submit`: wait while paused, then render and verify the
/// frame. `None` fails the guest; `Some(0)` tells it to stop.
fn submit(&self, index: u64) -> Option<u64> {
let mut state = self.lock();
state.calls += 1;
while state.paused && !state.stop {
state = self.wake.wait(state).unwrap_or_else(|p| p.into_inner());
}
if state.stop || state.completed >= state.limit {
return Some(0);
}
if index != u64::from(state.completed) {
return None; // frame identities must arrive in order
}
drop(state);
let pixels = render(index as u32)?;
let mut state = self.lock();
state.completed += 1;
state.latest = Some((index as u32, pixels));
Some(u64::from(state.completed < state.limit && !state.stop))
}
}
thread_local! {
static GPU: RefCell<Option<(NativeCompute, String)>> = const { RefCell::new(None) };
}
/// Frame `index` is a red strip in column `index % 4` on the clear colour.
///
/// The triangle (x0, -10), (x0 + 0.7, 0), (x0, 10) in clip space, with x0 the
/// column's left edge, covers that column's pixel centres in all three rows and
/// none of its neighbours'.
fn render(index: u32) -> Option<Vec<u8>> {
let column = (index as usize % WIDTH) as f32;
let x0 = -1.0 + column * (2.0 / WIDTH as f32);
let pixels = GPU.with(|slot| {
let slot = slot.borrow();
let (gpu, msl) = slot.as_ref()?;
gpu.render_rgba8(
msl,
[VERTEX_ENTRY_POINT, PIXEL_ENTRY_POINT],
&[
[x0, -10.0, 0.5, 1.0],
[x0 + 0.7, 0.0, 0.5, 1.0],
[x0, 10.0, 0.5, 1.0],
],
&[[0.0; 4]; 3],
[WIDTH, HEIGHT],
CLEAR,
)
.ok()
})?;
(pixels == expected(index)).then_some(pixels)
}
/// The expected frame for `index`, from the strip rule alone.
pub fn expected(index: u32) -> Vec<u8> {
(0..WIDTH * HEIGHT)
.flat_map(|pixel| {
if pixel % WIDTH == index as usize % WIDTH {
RED
} else {
CLEAR
}
})
.collect()
}
+858
View File
@@ -0,0 +1,858 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Versioned C interface for the native macOS application (see `include/xenora.h`).
//!
//! Sessions are opaque 64-bit handles: the low 32 bits index a slot and the high
//! 32 bits hold that slot's generation, so a stale handle never reaches a reused slot.
//! Every exported function catches panics and reports them as `XENORA_INTERNAL_ERROR`.
use std::fmt::Write as _;
mod frame_loop;
use frame_loop::FrameLoop;
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::{Arc, Mutex};
use xenora_loader::startup::{StartupLayout, run_synthetic_startup};
use xenora_loader::{ExitReason, ImportRegistry, ParsedPe, ProbeConfig, Register, probe_pe_bytes};
use xenora_metal::NativeCompute;
use xenora_shader::{Architecture, PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics};
pub const XENORA_ABI_VERSION: u32 = 1;
pub const XENORA_OK: i32 = 0;
pub const XENORA_INVALID_ARGUMENT: i32 = 1;
pub const XENORA_INVALID_HANDLE: i32 = 2;
pub const XENORA_VERSION_MISMATCH: i32 = 3;
pub const XENORA_INTERNAL_ERROR: i32 = 4;
pub const XENORA_PE_ERROR: i32 = 5;
pub const XENORA_LIMIT_EXCEEDED: i32 = 6;
pub const XENORA_BUFFER_TOO_SMALL: i32 = 7;
pub const XENORA_EXECUTION_FAILED: i32 = 8;
pub const XENORA_INVALID_STATE: i32 = 9;
pub const XENORA_LOOP_NONE: u32 = 0;
pub const XENORA_LOOP_RUNNING: u32 = frame_loop::RUNNING;
pub const XENORA_LOOP_PAUSED: u32 = frame_loop::PAUSED;
pub const XENORA_LOOP_FINISHED: u32 = frame_loop::FINISHED;
pub const XENORA_LOOP_STOPPED: u32 = frame_loop::STOPPED;
pub const XENORA_LOOP_FAILED: u32 = frame_loop::FAILED;
pub const XENORA_FRAME_LOOP_MAX_FRAMES: u32 = frame_loop::MAX_FRAMES;
pub const XENORA_NO_FRAME: u32 = u32::MAX;
pub const XENORA_FIXTURE_FRAME_WIDTH: u32 = 4;
pub const XENORA_FIXTURE_FRAME_HEIGHT: u32 = 3;
const FRAME_BYTES: usize = (XENORA_FIXTURE_FRAME_WIDTH * XENORA_FIXTURE_FRAME_HEIGHT * 4) as usize;
/// Upper bound on simultaneously live sessions.
const MAX_SESSIONS: usize = 64;
const FIXTURE: &[u8] = include_bytes!("../../../fixtures/pe/trusted-runner.exe");
struct Slot {
/// Odd while live, even while free; starts at 0 so the first handle is never 0.
generation: u32,
/// The session's persistent frame loop, if one was started.
frame_loop: Option<Arc<FrameLoop>>,
}
static SESSIONS: Mutex<Vec<Slot>> = Mutex::new(Vec::new());
fn guarded(f: impl FnOnce() -> i32) -> i32 {
catch_unwind(AssertUnwindSafe(f)).unwrap_or(XENORA_INTERNAL_ERROR)
}
fn split(handle: u64) -> (usize, u32) {
((handle & 0xFFFF_FFFF) as usize, (handle >> 32) as u32)
}
fn is_live(slots: &[Slot], handle: u64) -> bool {
let (index, generation) = split(handle);
slots
.get(index)
.is_some_and(|slot| slot.generation == generation && generation % 2 == 1)
}
#[unsafe(no_mangle)]
pub extern "C" fn xenora_abi_version() -> u32 {
XENORA_ABI_VERSION
}
/// # Safety
/// `out_session` must be null or valid for one aligned `u64` write.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn xenora_session_create(abi_version: u32, out_session: *mut u64) -> i32 {
guarded(|| {
if out_session.is_null() {
return XENORA_INVALID_ARGUMENT;
}
if abi_version != XENORA_ABI_VERSION {
return XENORA_VERSION_MISMATCH;
}
let Ok(mut slots) = SESSIONS.lock() else {
return XENORA_INTERNAL_ERROR;
};
let index = match slots.iter().position(|slot| slot.generation % 2 == 0) {
Some(index) => index,
None if slots.len() < MAX_SESSIONS => {
slots.push(Slot {
generation: 0,
frame_loop: None,
});
slots.len() - 1
}
None => return XENORA_LIMIT_EXCEEDED,
};
let slot = &mut slots[index];
// ponytail: a slot retires after 2^31 reuses instead of wrapping its generation.
let Some(generation) = slot.generation.checked_add(1) else {
return XENORA_LIMIT_EXCEEDED;
};
slot.generation = generation;
// SAFETY: checked non-null above; the caller guarantees validity.
unsafe { out_session.write((u64::from(generation) << 32) | index as u64) };
XENORA_OK
})
}
#[unsafe(no_mangle)]
pub extern "C" fn xenora_session_destroy(session: u64) -> i32 {
guarded(|| {
let Ok(mut slots) = SESSIONS.lock() else {
return XENORA_INTERNAL_ERROR;
};
if !is_live(&slots, session) {
return XENORA_INVALID_HANDLE;
}
let slot = &mut slots[split(session).0];
slot.generation += 1;
let running = slot.frame_loop.take();
drop(slots);
// Stop and join the guest thread without holding the session table.
if let Some(running) = running {
running.stop();
}
XENORA_OK
})
}
/// The live session's frame loop, or the status to return.
fn session_loop(session: u64) -> Result<Option<Arc<FrameLoop>>, i32> {
let slots = SESSIONS.lock().map_err(|_| XENORA_INTERNAL_ERROR)?;
if !is_live(&slots, session) {
return Err(XENORA_INVALID_HANDLE);
}
Ok(slots[split(session).0].frame_loop.clone())
}
#[unsafe(no_mangle)]
pub extern "C" fn xenora_session_start_frame_loop(session: u64, frame_count: u32) -> i32 {
guarded(|| {
if !(1..=XENORA_FRAME_LOOP_MAX_FRAMES).contains(&frame_count) {
return XENORA_INVALID_ARGUMENT;
}
let Ok(mut slots) = SESSIONS.lock() else {
return XENORA_INTERNAL_ERROR;
};
if !is_live(&slots, session) {
return XENORA_INVALID_HANDLE;
}
let slot = &mut slots[split(session).0];
if slot.frame_loop.is_some() {
return XENORA_INVALID_STATE;
}
slot.frame_loop = Some(FrameLoop::start(frame_count));
XENORA_OK
})
}
fn set_paused(session: u64, paused: bool) -> i32 {
guarded(|| match session_loop(session) {
Ok(Some(running)) if running.set_paused(paused) => XENORA_OK,
Ok(_) => XENORA_INVALID_STATE,
Err(status) => status,
})
}
#[unsafe(no_mangle)]
pub extern "C" fn xenora_session_pause_frame_loop(session: u64) -> i32 {
set_paused(session, true)
}
#[unsafe(no_mangle)]
pub extern "C" fn xenora_session_resume_frame_loop(session: u64) -> i32 {
set_paused(session, false)
}
#[unsafe(no_mangle)]
pub extern "C" fn xenora_session_stop_frame_loop(session: u64) -> i32 {
guarded(|| match session_loop(session) {
Ok(Some(running)) => {
running.stop();
XENORA_OK
}
Ok(None) => XENORA_INVALID_STATE,
Err(status) => status,
})
}
/// # Safety
/// Each `u32` output must be null or valid for one aligned write; `out_rgba` must be
/// null or valid for `capacity` byte writes.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn xenora_session_frame_loop_status(
session: u64,
out_state: *mut u32,
out_completed: *mut u32,
out_frame_id: *mut u32,
out_rgba: *mut u8,
capacity: u64,
) -> i32 {
guarded(|| {
if out_state.is_null()
|| out_completed.is_null()
|| out_frame_id.is_null()
|| out_rgba.is_null()
{
return XENORA_INVALID_ARGUMENT;
}
if capacity < frame_loop::FRAME_BYTES as u64 {
return XENORA_BUFFER_TOO_SMALL;
}
let running = match session_loop(session) {
Ok(running) => running,
Err(status) => return status,
};
let (state, completed, latest) = match running {
Some(running) => {
let snapshot = running.snapshot();
(snapshot.status, snapshot.completed, snapshot.latest)
}
None => (XENORA_LOOP_NONE, 0, None),
};
// SAFETY: all outputs checked non-null and `out_rgba` at least FRAME_BYTES long.
unsafe {
out_state.write(state);
out_completed.write(completed);
match latest {
Some((id, pixels)) => {
out_frame_id.write(id);
std::ptr::copy_nonoverlapping(
pixels.as_ptr(),
out_rgba,
frame_loop::FRAME_BYTES,
);
}
None => out_frame_id.write(XENORA_NO_FRAME),
}
}
XENORA_OK
})
}
/// # Safety
/// Each output pointer must be null or valid for one aligned `u32` write.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn xenora_session_inspect_trusted_fixture(
session: u64,
out_section_count: *mut u32,
out_entry_rva: *mut u32,
) -> i32 {
guarded(|| {
if out_section_count.is_null() || out_entry_rva.is_null() {
return XENORA_INVALID_ARGUMENT;
}
match SESSIONS.lock() {
Ok(slots) if is_live(&slots, session) => {}
Ok(_) => return XENORA_INVALID_HANDLE,
Err(_) => return XENORA_INTERNAL_ERROR,
}
let Ok(pe) = ParsedPe::parse(FIXTURE) else {
return XENORA_PE_ERROR;
};
// SAFETY: both checked non-null above; the caller guarantees validity.
unsafe {
out_section_count.write(u32::from(pe.number_of_sections));
out_entry_rva.write(pe.entry_point_rva);
}
XENORA_OK
})
}
// The trusted fixture's contract, as checked by the CLI runner (crates/cli/src/runner.rs).
// ponytail: duplicated from the runner so the CLI stays untouched; extract a shared
// fixture-run function into a library when a third caller appears.
const IMAGE_BASE: u64 = 0x1_5000_0000;
const TICKET_ADDRESS: u64 = IMAGE_BASE + 0x3000;
const TICKET: u64 = 17;
const DRAW_RESULT: u64 = 0x42;
const ENTRY_STEPS: usize = 100;
/// `x9-constant-ps.s` exports (1.0, 0, 0, 1.0) to mrt0; in an RGBA8 target that is opaque red.
const EXPECTED_PIXEL: [u8; 4] = [255, 0, 0, 255];
fn draw() -> Result<Vec<u8>, String> {
let shader = compile_graphics(
Architecture::Gfx1030,
include_bytes!("../../../fixtures/rdna2/x9-constant-vs.bin"),
include_bytes!("../../../fixtures/rdna2/x9-constant-ps.bin"),
)
.map_err(|e| format!("shader translation: {e}"))?;
let gpu = NativeCompute::new().map_err(|e| format!("Metal device: {e}"))?;
let pixels = gpu
.render_rgba8(
&shader.msl,
[VERTEX_ENTRY_POINT, PIXEL_ENTRY_POINT],
&[
[-1.0, -1.0, 0.5, 1.0],
[3.0, -1.0, 0.5, 1.0],
[-1.0, 3.0, 0.5, 1.0],
],
&[[0.0; 4]; 3],
[
XENORA_FIXTURE_FRAME_WIDTH as usize,
XENORA_FIXTURE_FRAME_HEIGHT as usize,
],
[19, 43, 93, 251],
)
.map_err(|e| format!("Metal render: {e}"))?;
if pixels != EXPECTED_PIXEL.repeat(FRAME_BYTES / 4) {
return Err("read-back frame differs from the fixture shader's output".into());
}
Ok(pixels)
}
/// Run the embedded fixture and return its verified frame.
fn run_fixture() -> Result<Vec<u8>, String> {
let frame = Arc::new(Mutex::new(None));
let draw_frame = Arc::clone(&frame);
let mut imports = ImportRegistry::new();
imports.register("xenora.dll", "fixture_draw", move |args, _, memory| {
let fault = ExitReason::IllegalInstruction(0xff);
let ticket = args.get(0, memory).map_err(ExitReason::MemoryFault)?;
let mut slot = draw_frame.lock().map_err(|_| fault)?;
if slot.is_some()
|| ticket != TICKET_ADDRESS
|| memory.read_u64(ticket).map_err(ExitReason::MemoryFault)? != TICKET
{
return Err(fault);
}
let result = draw();
let ok = result.is_ok();
*slot = Some(result);
if ok { Ok(DRAW_RESULT) } else { Err(fault) }
});
let startup = run_synthetic_startup(
FIXTURE,
StartupLayout {
image_base: IMAGE_BASE,
stack_top: 0x2_0001_0000,
tls_base: 0x3_0000_0000,
},
imports,
ENTRY_STEPS,
)
.map_err(|e| format!("startup: {e}"))?;
let drawn = frame.lock().map_err(|_| "frame lock poisoned")?.take();
if let Some(Err(e)) = drawn {
return Err(e);
}
let execution = &startup.execution;
if execution.exit_reason != ExitReason::Halt
|| startup.relocations.applied_dir64 != 4
|| startup.bound_imports != 1
|| startup.tls_callbacks != 1
|| execution.final_state.get(Register::Rax) != DRAW_RESULT
{
return Err(format!(
"unexpected guest result: {:?}",
execution.exit_reason
));
}
drawn.ok_or_else(|| String::from("guest halted without a draw"))?
}
/// # Safety
/// `out_rgba` must be null or valid for `capacity` byte writes; each `u32` output
/// must be null or valid for one aligned write.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn xenora_session_run_trusted_fixture(
session: u64,
out_rgba: *mut u8,
capacity: u64,
out_width: *mut u32,
out_height: *mut u32,
) -> i32 {
guarded(|| {
if out_rgba.is_null() || out_width.is_null() || out_height.is_null() {
return XENORA_INVALID_ARGUMENT;
}
match SESSIONS.lock() {
Ok(slots) if is_live(&slots, session) => {}
Ok(_) => return XENORA_INVALID_HANDLE,
Err(_) => return XENORA_INTERNAL_ERROR,
}
if capacity < FRAME_BYTES as u64 {
return XENORA_BUFFER_TOO_SMALL;
}
let Ok(pixels) = run_fixture() else {
return XENORA_EXECUTION_FAILED;
};
// SAFETY: non-null and at least FRAME_BYTES long, both checked above.
unsafe {
std::ptr::copy_nonoverlapping(pixels.as_ptr(), out_rgba, FRAME_BYTES);
out_width.write(XENORA_FIXTURE_FRAME_WIDTH);
out_height.write(XENORA_FIXTURE_FRAME_HEIGHT);
}
XENORA_OK
})
}
pub const XENORA_MAX_INSPECT_BYTES: u64 = 256 * 1024 * 1024;
/// Build the read-only inspection report and its status: `XENORA_OK`, `XENORA_PE_ERROR`
/// for a rejected file, or `XENORA_INTERNAL_ERROR` if Xenora's own probe failed.
fn inspection_report(bytes: &[u8]) -> (i32, String) {
let mut out = String::from("Xenora read-only inspection: nothing in this file was executed.\n");
let _ = writeln!(out, "file_size: {} bytes", bytes.len());
let probed = catch_unwind(AssertUnwindSafe(|| {
probe_pe_bytes(bytes, &ProbeConfig::default())
}));
let report = match probed {
Ok(Ok(report)) => report,
Ok(Err(e)) => {
let _ = writeln!(out, "verdict: not a supported PE32+ (x86-64) image: {e}");
return (XENORA_PE_ERROR, out);
}
Err(_) => {
out.push_str(
"verdict: inspection failed inside Xenora's static probe. This is a Xenora \
defect, not a finding about the file.\n",
);
return (XENORA_INTERNAL_ERROR, out);
}
};
let pe = &report.parsed;
let _ = writeln!(out, "sha256: {}", report.sha256);
let _ = writeln!(
out,
"machine: {:#06x} image_base: {:#x} entry_rva: {:#x} size_of_image: {:#x}",
pe.machine, pe.image_base, pe.entry_point_rva, pe.size_of_image
);
match ParsedPe::parse(bytes) {
Ok(_) => out.push_str("loader_validation: accepted\n"),
Err(e) => {
let _ = writeln!(out, "loader_validation: rejected: {e}");
}
}
let _ = writeln!(out, "\nsections ({}):", pe.sections.len());
for s in &pe.sections {
let p = s.permissions;
let _ = writeln!(
out,
" {:<8} rva {:#010x} vsize {:#x} raw {:#x} {}{}{}",
s.name,
s.virtual_address,
s.virtual_size,
s.raw_data_size,
if p.read { 'r' } else { '-' },
if p.write { 'w' } else { '-' },
if p.execute { 'x' } else { '-' },
);
}
let missing: Vec<_> = report.imports.iter().filter(|i| !i.is_supported).collect();
let _ = writeln!(
out,
"\nimports: {} total, {} provided by Xenora's standard runtime services, {} not provided",
report.imports.len(),
report.imports.len() - missing.len(),
missing.len()
);
for i in &missing {
let _ = writeln!(out, " not provided: {}!{}", i.dll, i.symbol);
}
let decoded = report.instruction_records.len();
let unsupported = report
.instruction_records
.iter()
.filter(|r| !r.is_supported_dbt)
.count();
let _ = writeln!(
out,
"\nstatic disassembly (bounded): {decoded} instructions decoded, {unsupported} not supported by the ARM64 DBT"
);
if let Some(first) = &report.first_unsupported_dbt_insn {
let hex: String = first.bytes.iter().map(|b| format!("{b:02x}")).collect();
let _ = writeln!(
out,
" first unsupported: rva {:#x} {} [{hex}]",
first.rva, first.mnemonic
);
}
let _ = writeln!(
out,
"\nrelocations: {} entries\ntls callbacks: {}",
report.relocations.total_entries,
report.tls.callback_targets.len()
);
out.push_str("\nExecution of opened files is not available (see #257).\n");
(XENORA_OK, out)
}
/// # Safety
/// `bytes` must be valid for `length` reads; `out_report` must be null or valid
/// for `capacity` writes; `out_required` must be null or valid for one `u64` write.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn xenora_inspect_executable(
bytes: *const u8,
length: u64,
out_report: *mut std::ffi::c_char,
capacity: u64,
out_required: *mut u64,
) -> i32 {
guarded(|| {
if bytes.is_null() || out_report.is_null() || out_required.is_null() {
return XENORA_INVALID_ARGUMENT;
}
if length > XENORA_MAX_INSPECT_BYTES {
return XENORA_LIMIT_EXCEEDED;
}
// SAFETY: non-null, and the caller guarantees `length` readable bytes.
let input = unsafe { std::slice::from_raw_parts(bytes, length as usize) };
let (status, text) = inspection_report(input);
let required = text.len() as u64 + 1;
// SAFETY: non-null, checked above.
unsafe { out_required.write(required) };
if capacity < required {
return XENORA_BUFFER_TOO_SMALL;
}
// SAFETY: `capacity >= required`, checked above.
unsafe {
std::ptr::copy_nonoverlapping(text.as_ptr(), out_report.cast::<u8>(), text.len());
out_report.add(text.len()).write(0);
}
status
})
}
#[cfg(test)]
mod tests {
use super::*;
use std::ptr::null_mut;
/// The session table is process-global, so tests that fill or count it run one at a time.
static SERIAL: Mutex<()> = Mutex::new(());
fn serial() -> std::sync::MutexGuard<'static, ()> {
SERIAL
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
fn create() -> u64 {
let mut handle = 0;
assert_eq!(
unsafe { xenora_session_create(XENORA_ABI_VERSION, &mut handle) },
XENORA_OK
);
assert_ne!(handle, 0);
handle
}
fn inspect(handle: u64) -> (i32, u32, u32) {
let (mut sections, mut entry) = (u32::MAX, u32::MAX);
let status =
unsafe { xenora_session_inspect_trusted_fixture(handle, &mut sections, &mut entry) };
(status, sections, entry)
}
#[test]
fn header_and_rust_constants_agree() {
let header = include_str!("../include/xenora.h");
assert!(header.contains(&format!("#define XENORA_ABI_VERSION {XENORA_ABI_VERSION}u")));
for (name, value) in [
("XENORA_OK", XENORA_OK),
("XENORA_INVALID_ARGUMENT", XENORA_INVALID_ARGUMENT),
("XENORA_INVALID_HANDLE", XENORA_INVALID_HANDLE),
("XENORA_VERSION_MISMATCH", XENORA_VERSION_MISMATCH),
("XENORA_INTERNAL_ERROR", XENORA_INTERNAL_ERROR),
("XENORA_PE_ERROR", XENORA_PE_ERROR),
("XENORA_LIMIT_EXCEEDED", XENORA_LIMIT_EXCEEDED),
("XENORA_BUFFER_TOO_SMALL", XENORA_BUFFER_TOO_SMALL),
("XENORA_EXECUTION_FAILED", XENORA_EXECUTION_FAILED),
("XENORA_INVALID_STATE", XENORA_INVALID_STATE),
("XENORA_LOOP_NONE", XENORA_LOOP_NONE as i32),
("XENORA_LOOP_RUNNING", XENORA_LOOP_RUNNING as i32),
("XENORA_LOOP_PAUSED", XENORA_LOOP_PAUSED as i32),
("XENORA_LOOP_FINISHED", XENORA_LOOP_FINISHED as i32),
("XENORA_LOOP_STOPPED", XENORA_LOOP_STOPPED as i32),
("XENORA_LOOP_FAILED", XENORA_LOOP_FAILED as i32),
] {
assert!(header.contains(&format!("{name} = {value},")), "{name}");
}
assert!(header.contains(&format!(
"XENORA_FIXTURE_FRAME_WIDTH {XENORA_FIXTURE_FRAME_WIDTH}u"
)));
assert!(header.contains(&format!(
"XENORA_FIXTURE_FRAME_HEIGHT {XENORA_FIXTURE_FRAME_HEIGHT}u"
)));
assert!(header.contains(&format!(
"XENORA_MAX_INSPECT_BYTES {XENORA_MAX_INSPECT_BYTES}u"
)));
assert!(header.contains(&format!(
"XENORA_FRAME_LOOP_MAX_FRAMES {XENORA_FRAME_LOOP_MAX_FRAMES}u"
)));
assert!(header.contains("XENORA_NO_FRAME 0xFFFFFFFFu"));
}
#[test]
fn session_inspects_the_trusted_fixture() {
let _serial = serial();
let handle = create();
// Independent expectation: read straight from the fixture's COFF and optional headers.
let lfanew = u32::from_le_bytes(FIXTURE[0x3C..0x40].try_into().unwrap()) as usize;
let sections = u16::from_le_bytes(FIXTURE[lfanew + 6..lfanew + 8].try_into().unwrap());
let entry = u32::from_le_bytes(FIXTURE[lfanew + 40..lfanew + 44].try_into().unwrap());
assert_eq!(inspect(handle), (XENORA_OK, u32::from(sections), entry));
assert_eq!(xenora_session_destroy(handle), XENORA_OK);
}
#[test]
fn version_mismatch_and_null_outputs_are_rejected() {
let _serial = serial();
let mut handle = 7;
assert_eq!(
unsafe { xenora_session_create(2, &mut handle) },
XENORA_VERSION_MISMATCH
);
assert_eq!(handle, 7, "output untouched on failure");
assert_eq!(
unsafe { xenora_session_create(1, null_mut()) },
XENORA_INVALID_ARGUMENT
);
let live = create();
let mut x = 0;
assert_eq!(
unsafe { xenora_session_inspect_trusted_fixture(live, null_mut(), &mut x) },
XENORA_INVALID_ARGUMENT
);
xenora_session_destroy(live);
}
#[test]
fn invalid_stale_and_double_destroyed_handles_are_rejected() {
let _serial = serial();
for bogus in [0, u64::MAX, 0xFFFF_FFFF, 1 << 32] {
assert_eq!(
xenora_session_destroy(bogus),
XENORA_INVALID_HANDLE,
"{bogus:#x}"
);
assert_eq!(inspect(bogus), (XENORA_INVALID_HANDLE, u32::MAX, u32::MAX));
}
let handle = create();
assert_eq!(xenora_session_destroy(handle), XENORA_OK);
assert_eq!(xenora_session_destroy(handle), XENORA_INVALID_HANDLE);
assert_eq!(inspect(handle).0, XENORA_INVALID_HANDLE);
// Reusing the slot must not revive the old handle.
let reused: Vec<u64> = (0..MAX_SESSIONS).map(|_| create()).collect();
assert!(!reused.contains(&handle));
assert_eq!(inspect(handle).0, XENORA_INVALID_HANDLE);
for h in reused {
xenora_session_destroy(h);
}
}
#[test]
fn repeated_and_concurrent_lifecycles_do_not_leak_slots() {
let _serial = serial();
let threads: Vec<_> = (0..8)
.map(|_| {
std::thread::spawn(|| {
for _ in 0..500 {
let mut handle = 0;
let status = unsafe { xenora_session_create(1, &mut handle) };
assert_eq!(status, XENORA_OK);
assert_eq!(inspect(handle).0, XENORA_OK);
assert_eq!(xenora_session_destroy(handle), XENORA_OK);
}
})
})
.collect();
for t in threads {
t.join().unwrap();
}
assert!(SESSIONS.lock().unwrap().len() <= MAX_SESSIONS);
}
#[test]
fn panics_do_not_cross_the_boundary() {
assert_eq!(guarded(|| panic!("injected")), XENORA_INTERNAL_ERROR);
}
#[test]
fn fixture_run_rejects_bad_arguments_before_executing() {
let _serial = serial();
let handle = create();
let (mut buf, mut w, mut h) = ([0u8; 48], 0u32, 0u32);
let run = |session, buf: *mut u8, cap, w: *mut u32, h: *mut u32| unsafe {
xenora_session_run_trusted_fixture(session, buf, cap, w, h)
};
assert_eq!(
run(handle, buf.as_mut_ptr(), 47, &mut w, &mut h),
XENORA_BUFFER_TOO_SMALL
);
assert_eq!(
run(handle, null_mut(), 48, &mut w, &mut h),
XENORA_INVALID_ARGUMENT
);
assert_eq!(
run(handle, buf.as_mut_ptr(), 48, null_mut(), &mut h),
XENORA_INVALID_ARGUMENT
);
xenora_session_destroy(handle);
assert_eq!(
run(handle, buf.as_mut_ptr(), 48, &mut w, &mut h),
XENORA_INVALID_HANDLE
);
assert_eq!((w, h), (0, 0), "outputs untouched on failure");
assert!(buf.iter().all(|&b| b == 0));
}
fn inspect_bytes(bytes: &[u8]) -> (i32, String) {
let mut required = 0;
let mut buf = vec![0 as std::ffi::c_char; 1];
let status = unsafe {
xenora_inspect_executable(
bytes.as_ptr(),
bytes.len() as u64,
buf.as_mut_ptr(),
1,
&mut required,
)
};
assert_eq!(status, XENORA_BUFFER_TOO_SMALL);
assert_eq!(buf[0], 0, "nothing written when the buffer is too small");
buf.resize(required as usize, 0);
let status = unsafe {
xenora_inspect_executable(
bytes.as_ptr(),
bytes.len() as u64,
buf.as_mut_ptr(),
required,
&mut required,
)
};
let text = unsafe { std::ffi::CStr::from_ptr(buf.as_ptr()) }
.to_str()
.unwrap()
.to_owned();
assert_eq!(text.len() as u64 + 1, required);
(status, text)
}
#[test]
fn inspection_reports_independently_read_facts_of_a_fixture() {
let (status, text) = inspect_bytes(FIXTURE);
assert_eq!(status, XENORA_OK);
let lfanew = u32::from_le_bytes(FIXTURE[0x3C..0x40].try_into().unwrap()) as usize;
let sections = u16::from_le_bytes(FIXTURE[lfanew + 6..lfanew + 8].try_into().unwrap());
let entry = u32::from_le_bytes(FIXTURE[lfanew + 40..lfanew + 44].try_into().unwrap());
assert!(text.contains(&format!("file_size: {} bytes", FIXTURE.len())));
assert!(text.contains(&format!("entry_rva: {entry:#x}")));
assert!(text.contains(&format!("sections ({sections}):")));
assert!(text.contains("loader_validation: accepted"));
assert!(
text.contains("xenora.dll") || text.contains("1 provided by Xenora"),
"{text}"
);
assert!(text.contains("nothing in this file was executed"));
}
#[test]
fn inspection_rejects_malformed_and_oversized_input() {
for bad in [&b""[..], b"not a pe file", &[0u8; 0x100]] {
let (status, text) = inspect_bytes(bad);
assert_eq!(status, XENORA_PE_ERROR, "{text}");
assert!(text.contains("not a supported PE32+"), "{text}");
}
// Every truncation of a valid file yields a report and a deterministic status.
// Some truncations currently hit a panic inside the loader's static probe
// (probe.rs, #270); the boundary must turn it into a report.
for len in (0..FIXTURE.len()).step_by(7) {
let (status, text) = inspect_bytes(&FIXTURE[..len]);
assert!(
matches!(status, XENORA_OK | XENORA_PE_ERROR | XENORA_INTERNAL_ERROR),
"len {len}"
);
assert_eq!(
inspect_bytes(&FIXTURE[..len]),
(status, text),
"len {len} is deterministic"
);
}
let (mut req, mut c) = (0u64, 0 as std::ffi::c_char);
let one = [0u8];
assert_eq!(
unsafe {
xenora_inspect_executable(
one.as_ptr(),
XENORA_MAX_INSPECT_BYTES + 1,
&mut c,
1,
&mut req,
)
},
XENORA_LIMIT_EXCEEDED
);
assert_eq!(
unsafe { xenora_inspect_executable(std::ptr::null(), 0, &mut c, 1, &mut req) },
XENORA_INVALID_ARGUMENT
);
}
#[test]
fn frame_loop_rejects_bad_arguments_and_states() {
let _serial = serial();
let handle = create();
assert_eq!(
xenora_session_start_frame_loop(handle, 0),
XENORA_INVALID_ARGUMENT
);
assert_eq!(
xenora_session_start_frame_loop(handle, XENORA_FRAME_LOOP_MAX_FRAMES + 1),
XENORA_INVALID_ARGUMENT
);
assert_eq!(
xenora_session_pause_frame_loop(handle),
XENORA_INVALID_STATE
);
assert_eq!(
xenora_session_resume_frame_loop(handle),
XENORA_INVALID_STATE
);
assert_eq!(xenora_session_stop_frame_loop(handle), XENORA_INVALID_STATE);
let (mut state, mut done, mut id, mut rgba) = (9, 9, 9, [0u8; 48]);
let mut status = |h, cap| unsafe {
xenora_session_frame_loop_status(
h,
&mut state,
&mut done,
&mut id,
rgba.as_mut_ptr(),
cap,
)
};
assert_eq!(status(handle, 47), XENORA_BUFFER_TOO_SMALL);
assert_eq!(status(handle, 48), XENORA_OK);
xenora_session_destroy(handle);
assert_eq!(status(handle, 48), XENORA_INVALID_HANDLE);
assert_eq!((state, done, id), (XENORA_LOOP_NONE, 0, XENORA_NO_FRAME));
assert_eq!(
xenora_session_start_frame_loop(handle, 1),
XENORA_INVALID_HANDLE
);
assert_eq!(
xenora_session_pause_frame_loop(handle),
XENORA_INVALID_HANDLE
);
}
}
+259
View File
@@ -0,0 +1,259 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Gate 3 acceptance on a native Metal device: persistent guest rendering through
//! the C interface. Needs `--features gpu-tests` (scripts/test-gpu.sh).
#![cfg(feature = "gpu-tests")]
use std::sync::Mutex;
use std::time::{Duration, Instant};
use xenora_ffi::*;
/// Tests share the process-wide session table and one GPU; run them one at a time.
static SERIAL: Mutex<()> = Mutex::new(());
/// Expected frame `id`, derived only from the geometry: the guest's frame index picks
/// column `id % 4`, which is opaque red (x9-constant-ps exports (1, 0, 0, 1)); the
/// other columns keep the clear colour (19, 43, 93, 251).
fn expected(id: u32) -> Vec<u8> {
let mut frame = Vec::new();
for _row in 0..3 {
for column in 0..4 {
if column == id % 4 {
frame.extend([255, 0, 0, 255]);
} else {
frame.extend([19, 43, 93, 251]);
}
}
}
frame
}
struct Status {
state: u32,
completed: u32,
frame_id: u32,
rgba: [u8; 48],
}
fn status(session: u64) -> Status {
let mut s = Status {
state: 99,
completed: 0,
frame_id: 0,
rgba: [0; 48],
};
let code = unsafe {
xenora_session_frame_loop_status(
session,
&mut s.state,
&mut s.completed,
&mut s.frame_id,
s.rgba.as_mut_ptr(),
48,
)
};
assert_eq!(code, XENORA_OK);
s
}
fn session() -> u64 {
let mut session = 0;
assert_eq!(
unsafe { xenora_session_create(XENORA_ABI_VERSION, &mut session) },
XENORA_OK
);
session
}
fn wait_until(session: u64, what: &str, done: impl Fn(&Status) -> bool) -> Status {
let deadline = Instant::now() + Duration::from_secs(60);
loop {
let s = status(session);
if done(&s) {
return s;
}
assert!(
Instant::now() < deadline,
"timed out waiting for {what} (state {}, completed {})",
s.state,
s.completed
);
std::thread::sleep(Duration::from_millis(2));
}
}
/// Physical memory footprint of this process (macOS `proc_pid_rusage`, RUSAGE_INFO_V2).
fn footprint() -> u64 {
unsafe extern "C" {
fn proc_pid_rusage(pid: i32, flavor: i32, buffer: *mut [u64; 32]) -> i32;
}
let mut info = [0u64; 32];
assert_eq!(
unsafe { proc_pid_rusage(std::process::id() as i32, 2, &mut info) },
0
);
info[9] // after the 16-byte UUID: user, system, idle wakeups, interrupts, pageins, wired, resident, footprint
}
#[test]
fn three_hundred_guest_frames_arrive_verified_and_in_order() {
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
let session = session();
assert_eq!(xenora_session_start_frame_loop(session, 300), XENORA_OK);
assert_eq!(
xenora_session_start_frame_loop(session, 300),
XENORA_INVALID_STATE
);
let s = wait_until(session, "300 frames", |s| s.state != XENORA_LOOP_RUNNING);
assert_eq!(s.state, XENORA_LOOP_FINISHED);
assert_eq!(s.completed, 300);
assert_eq!(s.frame_id, 299);
assert_eq!(s.rgba.to_vec(), expected(299));
assert_eq!(xenora_session_destroy(session), XENORA_OK);
}
#[test]
fn observed_frame_ids_never_go_backwards_and_match_their_pixels() {
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
let session = session();
assert_eq!(xenora_session_start_frame_loop(session, 2_000), XENORA_OK);
let mut previous = None;
let mut samples = 0;
loop {
let s = status(session);
if s.frame_id != XENORA_NO_FRAME {
if let Some(p) = previous {
assert!(s.frame_id >= p, "frame id went from {p} to {}", s.frame_id);
}
assert!(
s.frame_id < s.completed,
"id {} not below completed {}",
s.frame_id,
s.completed
);
assert_eq!(
s.rgba.to_vec(),
expected(s.frame_id),
"frame {}",
s.frame_id
);
previous = Some(s.frame_id);
samples += 1;
}
if s.state != XENORA_LOOP_RUNNING {
assert_eq!(s.state, XENORA_LOOP_FINISHED);
assert_eq!((s.completed, s.frame_id), (2_000, 1_999));
break;
}
}
assert!(samples > 1);
xenora_session_destroy(session);
}
#[test]
fn pause_holds_the_guest_resume_continues_and_stop_halts_it() {
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
let session = session();
assert_eq!(
xenora_session_start_frame_loop(session, XENORA_FRAME_LOOP_MAX_FRAMES),
XENORA_OK
);
wait_until(session, "10 frames", |s| s.completed >= 10);
assert_eq!(xenora_session_pause_frame_loop(session), XENORA_OK);
// At most the frame already being rendered can still complete after pausing.
std::thread::sleep(Duration::from_millis(50));
let held = status(session);
std::thread::sleep(Duration::from_millis(200));
let later = status(session);
assert_eq!(later.state, XENORA_LOOP_PAUSED);
assert_eq!(later.completed, held.completed, "no frames while paused");
assert_eq!(later.frame_id, held.completed - 1);
assert_eq!(later.rgba.to_vec(), expected(later.frame_id));
assert_eq!(xenora_session_resume_frame_loop(session), XENORA_OK);
let resumed = wait_until(session, "progress after resume", |s| {
s.completed >= held.completed + 10
});
assert_eq!(resumed.state, XENORA_LOOP_RUNNING);
assert_eq!(xenora_session_stop_frame_loop(session), XENORA_OK);
let stopped = status(session);
assert_eq!(stopped.state, XENORA_LOOP_STOPPED);
assert!(stopped.completed < XENORA_FRAME_LOOP_MAX_FRAMES);
assert_eq!(stopped.frame_id, stopped.completed - 1);
assert_eq!(stopped.rgba.to_vec(), expected(stopped.frame_id));
// Pause and resume are refused once the guest has halted.
assert_eq!(
xenora_session_pause_frame_loop(session),
XENORA_INVALID_STATE
);
assert_eq!(
xenora_session_resume_frame_loop(session),
XENORA_INVALID_STATE
);
assert_eq!(xenora_session_destroy(session), XENORA_OK);
}
#[test]
fn destroying_a_running_or_paused_session_stops_it() {
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
for pause_first in [false, true] {
let session = session();
assert_eq!(
xenora_session_start_frame_loop(session, XENORA_FRAME_LOOP_MAX_FRAMES),
XENORA_OK
);
wait_until(session, "a frame", |s| s.completed >= 1);
if pause_first {
assert_eq!(xenora_session_pause_frame_loop(session), XENORA_OK);
}
let started = Instant::now();
assert_eq!(xenora_session_destroy(session), XENORA_OK);
assert!(
started.elapsed() < Duration::from_secs(5),
"destroy joined promptly"
);
let mut x = 0;
let mut rgba = [0u8; 48];
assert_eq!(
unsafe {
xenora_session_frame_loop_status(
session,
&mut x,
&mut x,
&mut x,
rgba.as_mut_ptr(),
48,
)
},
XENORA_INVALID_HANDLE
);
}
}
#[test]
fn repeated_sessions_do_not_grow_the_memory_footprint() {
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
let run = || {
let session = session();
assert_eq!(xenora_session_start_frame_loop(session, 300), XENORA_OK);
let s = wait_until(session, "300 frames", |s| s.state != XENORA_LOOP_RUNNING);
assert_eq!((s.state, s.completed), (XENORA_LOOP_FINISHED, 300));
assert_eq!(xenora_session_destroy(session), XENORA_OK);
};
// Warm up so one-time allocations (Metal device, shader compiler) are excluded.
run();
run();
let baseline = footprint();
for _ in 0..5 {
run();
}
let after = footprint();
let growth = after.saturating_sub(baseline);
println!("footprint baseline={baseline} after_5_sessions={after} growth={growth}");
assert!(
growth < 16 << 20,
"footprint grew by {growth} bytes over 5 sessions of 300 frames"
);
}
+40
View File
@@ -0,0 +1,40 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Runs the trusted fixture through the C interface on a native Metal device.
//! Needs `--features gpu-tests` (scripts/test-gpu.sh).
#![cfg(feature = "gpu-tests")]
use xenora_ffi::*;
/// fixtures/rdna2/x9-constant-ps.s: `v_mov_b32 v8, 1.0; v_mov_b32 v9, 0;
/// exp mrt0, v8, v9, v9, v8` writes (1, 0, 0, 1); as RGBA8 unorm that is (255, 0, 0, 255).
const SHADER_OUTPUT: [u8; 4] = [255, 0, 0, 255];
#[test]
fn guest_fixture_frame_reaches_the_caller_through_metal() {
for run in 0..3 {
let mut session = 0;
assert_eq!(
unsafe { xenora_session_create(XENORA_ABI_VERSION, &mut session) },
XENORA_OK
);
let (mut rgba, mut width, mut height) = ([0u8; 64], 0u32, 0u32);
let status = unsafe {
xenora_session_run_trusted_fixture(
session,
rgba.as_mut_ptr(),
64,
&mut width,
&mut height,
)
};
assert_eq!(status, XENORA_OK, "run {run}");
assert_eq!((width, height), (4, 3));
assert_eq!(&rgba[..48], SHADER_OUTPUT.repeat(12).as_slice());
assert!(
rgba[48..].iter().all(|&b| b == 0),
"no write past the frame"
);
assert_eq!(xenora_session_destroy(session), XENORA_OK);
}
}
-1
View File
@@ -17,7 +17,6 @@ VARIANTS = (
("V_ADD_NC_U32", "ENC_VOP3"),
("S_ENDPGM", "ENC_SOPP"),
("S_MOV_B32", "ENC_SOP1"),
("S_CMP_EQ_U32", "ENC_SOPC"),
("S_CBRANCH_SCC0", "ENC_SOPP"),
("S_CBRANCH_EXECZ", "ENC_SOPP"),
("S_CBRANCH_VCCZ", "ENC_SOPP"),
+332 -35
View File
@@ -38,8 +38,63 @@ FORM_KEYS = {
}
TOP_KEYS = {"schema", "architecture", "source_sha256", "documents", "operand_rules", "form"}
OPERATIONS = {"add": "Add", "sub": "Sub", "and": "And", "or": "Or", "xor": "Xor"}
LOGICAL = {"and", "or", "xor"}
OPERATIONS = {
"add": "Add", "sub": "Sub", "and": "And", "or": "Or", "xor": "Xor",
"andn2": "AndNot", "orn2": "OrNot", "nand": "Nand", "nor": "Nor", "xnor": "Xnor",
"lshl": "ShiftLeft", "lshr": "LogicalShiftRight", "ashr": "ArithmeticShiftRight",
"compare": "Compare",
"not": "Not", "brev": "ReverseBits", "bcnt0": "CountZeros", "bcnt1": "CountOnes",
"ff0": "FindFirstZero", "ff1": "FindFirstOne", "flbit": "FindLastBit",
"sext": "SignExtend", "abs": "Absolute",
"min": "Minimum", "max": "Maximum", "cselect": "Select", "bfm": "BitfieldMask",
"mul": "Multiply", "mul_hi": "MultiplyHigh", "bfe": "BitfieldExtract",
"absdiff": "AbsoluteDifference", "lshl_add": "ShiftLeftAdd",
}
# Unary operations read one source; they need an operand rule of the unary kind.
UNARY = {"not", "brev", "bcnt0", "bcnt1", "ff0", "ff1", "flbit", "sext", "abs"}
# Sign extension reads only the low source_bits of S0 (required for sext only).
SOURCE_BITS_KEY = "source_bits"
SOURCE_BITS = {8, 16}
# Compares take a relation (S0 on the left) and set SCC to whether it holds.
RELATION_KEY = "relation"
RELATIONS = {
"eq": "Equal", "lg": "NotEqual", "gt": "Greater", "ge": "GreaterOrEqual",
"lt": "Less", "le": "LessOrEqual",
}
# (relation, signedness) -> primitive. Equality does not depend on signedness,
# so both declared signednesses of EQ and LG share one primitive.
COMPARE_PRIMITIVES = {
("eq", "signed"): "eq_b32", ("eq", "unsigned"): "eq_b32",
("lg", "signed"): "ne_b32", ("lg", "unsigned"): "ne_b32",
("gt", "signed"): "gt_i32", ("gt", "unsigned"): "gt_u32",
("ge", "signed"): "ge_i32", ("ge", "unsigned"): "ge_u32",
("lt", "signed"): "lt_i32", ("lt", "unsigned"): "lt_u32",
("le", "signed"): "le_i32", ("le", "unsigned"): "le_u32",
}
# Logical operations take untyped bits; arithmetic ones never do. Shifts take
# the signedness their primitive names, and their S1 is an unsigned count.
LOGICAL = {
"and", "or", "xor", "andn2", "orn2", "nand", "nor", "xnor",
"not", "brev", "bcnt0", "bcnt1", "ff0", "ff1", "cselect", "bfm",
}
ARITHMETIC = {"add", "sub", "min", "max", "mul", "mul_hi", "bfe", "absdiff", "lshl_add"}
SHIFTS = {"lshl", "lshr", "ashr"}
# Operations whose S1 is an unsigned control word (a shift count or a bit-field
# descriptor), so the XML gives it FMT_NUM_U32 whatever the form's signedness.
CONTROL_S1 = SHIFTS | {"bfe"}
# Operations that always read SCC: the select condition. They need carry_in scc.
SCC_READERS = {"cselect"}
# XML number formats a source may have for each declared signedness.
SOURCE_FORMATS = {
"signed": {"FMT_NUM_I32"},
"unsigned": {"FMT_NUM_U32"},
"bitwise": {"FMT_NUM_U32", "FMT_NUM_B32"},
}
# Optional keys: required exactly when the condition holds.
SHIFT_KEY = "shift_count_bits"
# Shift-and-add declares its fixed S0 shift (required for lshl_add only).
SHIFT_AMOUNT_KEY = "shift_amount"
SHIFT_AMOUNTS = {1, 2, 3, 4}
SIGNEDNESS = {"unsigned": "Unsigned", "signed": "Signed", "bitwise": "Bitwise"}
CARRY_IN = {"none": "None", "scc": "Scc"}
SCC = {
@@ -48,6 +103,8 @@ SCC = {
"borrow": "Borrow",
"signed_overflow": "SignedOverflow",
"nonzero": "Nonzero",
"relation": "Relation",
"selected_src0": "SelectedSrc0",
}
MASK = {"unchanged": "Unchanged"}
WAVE = {"any": "Any", "wave32": "Wave32"}
@@ -86,6 +143,37 @@ PRIMITIVES = {
("and", "bitwise"): ("nonzero", "and_nonzero_b32", False),
("or", "bitwise"): ("nonzero", "or_nonzero_b32", False),
("xor", "bitwise"): ("nonzero", "xor_nonzero_b32", False),
("andn2", "bitwise"): ("nonzero", "andn2_nonzero_b32", False),
("orn2", "bitwise"): ("nonzero", "orn2_nonzero_b32", False),
("nand", "bitwise"): ("nonzero", "nand_nonzero_b32", False),
("nor", "bitwise"): ("nonzero", "nor_nonzero_b32", False),
("xnor", "bitwise"): ("nonzero", "xnor_nonzero_b32", False),
("lshl", "bitwise"): ("nonzero", "lshl_nonzero_b32", False),
("lshr", "unsigned"): ("nonzero", "lshr_nonzero_b32", False),
("ashr", "signed"): ("nonzero", "ashr_nonzero_i32", False),
("not", "bitwise"): ("nonzero", "not_nonzero_b32", False),
("brev", "bitwise"): ("unchanged", "brev_b32", False),
("bcnt0", "bitwise"): ("nonzero", "bcnt0_nonzero_b32", False),
("bcnt1", "bitwise"): ("nonzero", "bcnt1_nonzero_b32", False),
("ff0", "bitwise"): ("unchanged", "ff0_b32", False),
("ff1", "bitwise"): ("unchanged", "ff1_b32", False),
("flbit", "bitwise"): ("unchanged", "flbit_b32", False),
("flbit", "signed"): ("unchanged", "flbit_i32", False),
("sext", "signed"): ("unchanged", "sext_i32", False),
("abs", "signed"): ("nonzero", "abs_nonzero_i32", False),
("min", "signed"): ("selected_src0", "min_i32", False),
("min", "unsigned"): ("selected_src0", "min_u32", False),
("max", "signed"): ("selected_src0", "max_i32", False),
("max", "unsigned"): ("selected_src0", "max_u32", False),
("cselect", "bitwise"): ("unchanged", "cselect_b32", True),
("bfm", "bitwise"): ("unchanged", "bfm_b32", False),
("mul", "signed"): ("unchanged", "mul_lo_i32", False),
("mul_hi", "unsigned"): ("unchanged", "mul_hi_u32", False),
("mul_hi", "signed"): ("unchanged", "mul_hi_i32", False),
("bfe", "unsigned"): ("nonzero", "bfe_nonzero_u32", False),
("bfe", "signed"): ("nonzero", "bfe_nonzero_i32", False),
("absdiff", "signed"): ("nonzero", "absdiff_nonzero_i32", False),
("lshl_add", "unsigned"): ("carry_out", "lshl_add_carry_u32", False),
}
# Operand rules the decoder implements, each exactly once. A registry rule must
@@ -109,6 +197,35 @@ OPERAND_RULES = {
},
# Every one of these is rejected by the decoder's SOP2 operand checks.
"unsupported": UNSUPPORTED_COMBOS,
"kind": "alu",
},
"sopc_scalar": {
"rust": "SopcScalar",
"enum": "ScalarCompareOp",
"shape": {
"family": "SOPC",
"src": [
{"field": "SSRC0", "class": "scalar_source"},
{"field": "SSRC1", "class": "scalar_source"},
],
"max_literals": 1,
},
# SOPC has no destination field; the decoder rejects these sources.
"unsupported": {combo for combo in UNSUPPORTED_COMBOS if not combo.startswith("dst_")},
"kind": "compare",
},
"sop1_sgpr": {
"rust": "Sop1Sgpr",
"enum": "ScalarUnaryOp",
"shape": {
"family": "SOP1",
"dst": {"field": "SDST", "class": "sgpr", "min": 0, "max": 105},
"src": [{"field": "SSRC0", "class": "scalar_source"}],
"max_literals": 1,
},
# One source, so two literals cannot occur; the rest are rejected.
"unsupported": {combo for combo in UNSUPPORTED_COMBOS if combo != "two_literals"},
"kind": "unary",
},
}
@@ -204,18 +321,34 @@ def _check_xml(form, rule, snapshot, errors):
errors.append(f"{label}: scc {form['scc']} contradicts the XML SCC output")
if rule is None:
return
fields = [(rule["dst"]["field"], False)] + [(src["field"], True) for src in rule["src"]]
if not isinstance(rule.get("src"), list) or not all(
isinstance(src, dict) and isinstance(src.get("field"), str) for src in rule["src"]
) or ("dst" in rule and not (isinstance(rule["dst"], dict) and "field" in rule["dst"])):
return # the rule check already reported the malformed shape
fields = [(rule["dst"]["field"], False)] if "dst" in rule else []
fields += [(src["field"], True) for src in rule["src"]]
shift = form["operation"] in CONTROL_S1 and len(rule["src"]) > 1
count_field = rule["src"][1]["field"] if shift else None
for field, is_source in fields:
if field not in operands:
errors.append(f"{label}: XML has no operand {field}")
continue
data_format, size, is_input, is_output = operands[field]
if size != form["width"]:
errors.append(f"{label}: {field} is {size} bits in the XML, declared {form['width']}")
bits = form.get(SOURCE_BITS_KEY) if is_source else None
expected = bits if type(bits) is int else form["width"]
if size != expected:
errors.append(f"{label}: {field} is {size} bits in the XML, declared {expected}")
if (is_input, is_output) != (is_source, not is_source):
errors.append(f"{label}: {field} direction disagrees with the XML")
signed_format = data_format.startswith("FMT_NUM_I")
if is_source and signed_format != (form["signedness"] == "signed"):
if field == count_field:
if data_format != "FMT_NUM_U32":
errors.append(
f"{label}: control operand {field} has XML format {data_format}, not FMT_NUM_U32"
)
elif type(bits) is int:
if data_format != f"FMT_NUM_I{bits}":
errors.append(f"{label}: {field} has XML format {data_format}, not FMT_NUM_I{bits}")
elif is_source and data_format not in SOURCE_FORMATS.get(form["signedness"], ()):
errors.append(
f"{label}: signedness {form['signedness']} contradicts XML format {data_format}"
)
@@ -261,7 +394,9 @@ def validate(registry, snapshot):
for index, form in enumerate(forms):
label = form.get("name", f"form #{index}")
missing = sorted(FORM_KEYS - set(form))
extra = sorted(set(form) - FORM_KEYS)
extra = sorted(
set(form) - FORM_KEYS - {SHIFT_KEY, SHIFT_AMOUNT_KEY, RELATION_KEY, SOURCE_BITS_KEY}
)
if missing:
errors.append(f"{label}: incomplete, missing {missing}")
if extra:
@@ -294,11 +429,51 @@ def validate(registry, snapshot):
if value in seen[key]:
errors.append(f"{label}: duplicate {key} {value}")
seen[key].add(value)
if (form["signedness"] == "bitwise") != (form["operation"] in LOGICAL):
if (form["operation"] in LOGICAL and form["signedness"] != "bitwise") or (
form["operation"] in ARITHMETIC and form["signedness"] == "bitwise"
):
errors.append(
f"{label}: signedness {form['signedness']} contradicts operation {form['operation']}"
)
primitive = PRIMITIVES.get((form["operation"], form["signedness"]))
if form["operation"] in SHIFTS:
bits = form.get(SHIFT_KEY)
if type(bits) is not int or not 0 < bits < 32 or (1 << bits) != form["width"]:
errors.append(
f"{label}: {SHIFT_KEY} must be log2 of the width ({form['width']}), got {bits!r}"
)
elif SHIFT_KEY in form:
errors.append(f"{label}: {SHIFT_KEY} on a non-shift operation")
if form["operation"] == "lshl_add":
amount = form.get(SHIFT_AMOUNT_KEY)
if type(amount) is not int or amount not in SHIFT_AMOUNTS:
errors.append(
f"{label}: {SHIFT_AMOUNT_KEY} must be one of {sorted(SHIFT_AMOUNTS)}, got {amount!r}"
)
elif SHIFT_AMOUNT_KEY in form:
errors.append(f"{label}: {SHIFT_AMOUNT_KEY} on a non-lshl_add operation")
if form["operation"] in SCC_READERS and form["carry_in"] != "scc":
errors.append(f"{label}: operation {form['operation']} reads SCC (requires carry_in scc)")
if form["operation"] == "sext":
bits = form.get(SOURCE_BITS_KEY)
if type(bits) is not int or bits not in SOURCE_BITS:
errors.append(f"{label}: {SOURCE_BITS_KEY} must be one of {sorted(SOURCE_BITS)}, got {bits!r}")
elif SOURCE_BITS_KEY in form:
errors.append(f"{label}: {SOURCE_BITS_KEY} on a non-sext operation")
if form["operation"] == "compare":
relation = form.get(RELATION_KEY)
if not isinstance(relation, str) or relation not in RELATIONS:
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)")
if form["carry_in"] != "none":
errors.append(f"{label}: carry_in {form['carry_in']} contradicts compare")
primitive = ("relation", None, False)
else:
if RELATION_KEY in form:
errors.append(f"{label}: {RELATION_KEY} on a non-compare operation")
primitive = PRIMITIVES.get((form["operation"], form["signedness"]))
if primitive is None:
errors.append(f"{label}: no primitive implements {form['operation']}/{form['signedness']}")
else:
@@ -315,6 +490,11 @@ def validate(registry, snapshot):
errors.append(f"{label}: unknown operand rule {form['operands']!r}")
elif rule.get("family") != form["family"]:
errors.append(f"{label}: operand rule {form['operands']} is for {rule.get('family')}")
elif form["operands"] in OPERAND_RULES and OPERAND_RULES[form["operands"]]["kind"] != (
"compare" if form["operation"] == "compare"
else "unary" if form["operation"] in UNARY else "alu"
):
errors.append(f"{label}: operation {form['operation']} does not fit rule {form['operands']}")
_check_spec(label, form["spec"], documents, errors)
verify = form["verify"]
if not verify:
@@ -360,6 +540,7 @@ def render(registry, snapshot):
" CarryIn, Document, Evidence, FormSemantics, MaskEffect, Operation, OperandRule, SccEffect,",
" Signedness, SpecRef, Wave,",
"};",
"use crate::CompareRelation;",
"",
"/// Registry schema of the generated tables.",
f"pub const GENERATED_SCHEMA: u32 = {registry['schema']};",
@@ -396,6 +577,11 @@ def render(registry, snapshot):
f" signedness: Signedness::{SIGNEDNESS[form['signedness']]},",
f" carry_in: CarryIn::{CARRY_IN[form['carry_in']]},",
f" width: {form['width']},",
f" shift_count_bits: {form.get(SHIFT_KEY, 0)},",
f" shift_amount: {form.get(SHIFT_AMOUNT_KEY, 0)},",
f" source_bits: {form.get(SOURCE_BITS_KEY, form['width'])},",
" relation: "
+ (f"Some(CompareRelation::{RELATIONS[form[RELATION_KEY]]})," if RELATION_KEY in form else "None,"),
f" scc: SccEffect::{SCC[form['scc']]},",
f" vcc: MaskEffect::{MASK[form['vcc']]},",
f" exec: MaskEffect::{MASK[form['exec']]},",
@@ -411,9 +597,21 @@ def render(registry, snapshot):
def _render_enum(rule_name, forms, snapshot, positions):
enum = OPERAND_RULES[rule_name]["enum"]
kind = OPERAND_RULES[rule_name]["kind"]
table = re.sub(r"(?<!^)(?=[A-Z])", "_", enum).upper() + "_BY_OPCODE"
family = forms[0]["family"]
encoding = snapshot["encodings"][_family_encoding(family)]
mask = encoding["identifier_mask"]
(offset, size), = dict((name, ranges) for name, ranges in encoding["fields"])["OP"]
op_mask = ((1 << size) - 1) << offset
fixed_mask = mask & ~op_mask
fixed_bits = encoding["identifiers"][0] & fixed_mask
# Every identifier of the family must share the fixed bits, or the split
# into an encoding test plus an OP match would change which words match.
if any(identifier & fixed_mask != fixed_bits for identifier in encoding["identifiers"]) or (
mask & op_mask != op_mask
):
raise ValueError(f"{family}: identifiers do not split into fixed bits and OP")
out = [
"",
f"/// {family} operations declared in the semantic registry (operand rule `{rule_name}`).",
@@ -422,14 +620,26 @@ 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"]
out += [
f" /// `{form['name'].lower()}` ({family} opcode {form['opcode']}): "
f"{form['signedness']} {form['operation']}{carry}, SCC = {form['scc']}.",
f"{form['signedness']} {what}{carry}, SCC = {form['scc']}.",
f" {form['variant']},",
]
by_opcode = {form["opcode"]: form["variant"] for form in forms}
out += [
"}",
"",
f"/// {enum} by {family} OP field value; `None` for undeclared opcodes.",
f"const {table}: [Option<{enum}>; {1 << size}] = [",
]
out += [
f" Some({enum}::{by_opcode[opcode]})," if opcode in by_opcode else " None,"
for opcode in range(1 << size)
]
out += [
"];",
"",
f"impl {enum} {{",
" /// Every operation, in registry order.",
f" pub const ALL: [Self; {len(forms)}] = [",
@@ -438,15 +648,13 @@ def _render_enum(rule_name, forms, snapshot, positions):
out += [
" ];",
"",
f" /// Selects the operation from a first instruction word (mask 0x{mask:09_x}).",
f" /// Selects the operation from a first instruction word: the {family} encoding",
f" /// bits (mask 0x{fixed_mask:09_x}) and then the OP field (bits {offset}-{offset + size - 1}).",
" pub const fn from_word(word: u32) -> Option<Self> {",
f" match word & 0x{mask:09_x} {{",
]
for form in sorted(forms, key=lambda item: item["opcode"]):
out.append(f" 0x{_identifier(encoding, form['opcode']):09_x} => Some(Self::{form['variant']}),")
out += [
" _ => None,",
f" if word & 0x{fixed_mask:09_x} != 0x{fixed_bits:09_x} {{",
" return None;",
" }",
f" {table}[((word >> {offset}) & 0x{(1 << size) - 1:x}) as usize]",
" }",
"",
" /// Lower-case mnemonic.",
@@ -454,18 +662,6 @@ def _render_enum(rule_name, forms, snapshot, positions):
" match self {",
]
out += [f" Self::{form['variant']} => \"{form['name'].lower()}\"," for form in forms]
out += [
" }",
" }",
"",
" /// Whether the operation reads SCC as a carry-in or borrow-in.",
" pub const fn reads_scc(self) -> bool {",
" match self {",
]
out += [
f" Self::{form['variant']} => {'true' if form['carry_in'] == 'scc' else 'false'},"
for form in forms
]
out += [
" }",
" }",
@@ -478,20 +674,121 @@ def _render_enum(rule_name, forms, snapshot, positions):
out += [
" }]",
" }",
]
if kind == "unary":
out += [
"",
" /// Whether the operation writes SCC.",
" pub const fn writes_scc(self) -> bool {",
" match self {",
]
out += [
f" Self::{form['variant']} => {'false' if form['scc'] == 'unchanged' else 'true'},"
for form in forms
]
out += [
" }",
" }",
"",
" /// The result and, for forms that write it, the new SCC (`None` leaves SCC",
" /// unchanged).",
" pub const fn evaluate(self, src: u32) -> (u32, Option<bool>) {",
" match self {",
]
for form in forms:
_, function, _ = PRIMITIVES[(form["operation"], form["signedness"])]
if form["operation"] == "sext":
value = f"primitive::{function}(src, {form[SOURCE_BITS_KEY]})"
else:
value = f"primitive::{function}(src)"
if form["scc"] == "unchanged":
out.append(f" Self::{form['variant']} => ({value}, None),")
else:
out += [
f" Self::{form['variant']} => {{",
f" let (value, scc) = {value};",
" (value, Some(scc))",
" }",
]
out += [" }", " }", "}"]
return out
if kind == "compare":
out += [
"",
" /// The relation tested, with S0 on the left.",
" pub const fn relation(self) -> CompareRelation {",
" match self {",
]
out += [
f" Self::{form['variant']} => CompareRelation::{RELATIONS[form[RELATION_KEY]]},"
for form in forms
]
out += [
" }",
" }",
"",
" /// The new SCC: whether the relation holds for S0 and S1.",
" pub const fn test(self, src0: u32, src1: u32) -> bool {",
" match self {",
]
for form in forms:
function = COMPARE_PRIMITIVES[(form[RELATION_KEY], form["signedness"])]
out.append(f" Self::{form['variant']} => primitive::{function}(src0, src1),")
out += [" }", " }", "}"]
return out
out += [
"",
" /// The result and the new SCC, with `carry_in` the SCC read by forms that",
" /// consume it (ignored by the others).",
" pub const fn evaluate(self, src0: u32, src1: u32, carry_in: bool) -> (u32, bool) {",
" /// Whether the operation reads SCC (carry-in, borrow-in or select condition).",
" pub const fn reads_scc(self) -> bool {",
" match self {",
]
out += [
f" Self::{form['variant']} => {'true' if form['carry_in'] == 'scc' else 'false'},"
for form in forms
]
out += [
" }",
" }",
"",
" /// Whether the operation writes SCC.",
" pub const fn writes_scc(self) -> bool {",
" match self {",
]
out += [
f" Self::{form['variant']} => {'false' if form['scc'] == 'unchanged' else 'true'},"
for form in forms
]
out += [
" }",
" }",
"",
" /// The result and, for forms that write it, the new SCC (`None` leaves SCC",
" /// unchanged). `scc_in` is the SCC read by forms that consume it (ignored by",
" /// the others).",
" pub const fn evaluate(self, src0: u32, src1: u32, scc_in: bool) -> (u32, Option<bool>) {",
" match self {",
]
for form in forms:
_, function, takes_carry = PRIMITIVES[(form["operation"], form["signedness"])]
if takes_carry:
argument = "carry_in" if form["carry_in"] == "scc" else "false"
argument = "scc_in" if form["carry_in"] == "scc" else "false"
call = f"primitive::{function}(src0, src1, {argument})"
elif form["operation"] in SHIFTS:
mask = (1 << form[SHIFT_KEY]) - 1
call = f"primitive::{function}(src0, src1 & 0x{mask:x})"
elif form["operation"] == "lshl_add":
call = f"primitive::{function}(src0, src1, {form[SHIFT_AMOUNT_KEY]})"
else:
call = f"primitive::{function}(src0, src1)"
out.append(f" Self::{form['variant']} => {call},")
if form["scc"] == "unchanged":
out.append(f" Self::{form['variant']} => ({call}, None),")
else:
out += [
f" Self::{form['variant']} => {{",
f" let (value, scc) = {call};",
" (value, Some(scc))",
" }",
]
out += [" }", " }", "}"]
return out
+959 -3
View File
@@ -49,11 +49,11 @@ unsupported = [
# family encoding family; must match the XML base encoding
# opcode XML opcode; must match
# variant Rust enum variant of the typed op
# operation primitive: add | sub | and | or | xor
# operation primitive (closed vocabulary in generate_semantics.py OPERATIONS)
# signedness unsigned | signed | bitwise (bitwise iff a logical operation)
# carry_in none | scc (scc only for unsigned add/sub)
# carry_in none | scc (scc for unsigned add/sub carry and the cselect condition)
# width operand and result width in bits
# scc carry_out | borrow | signed_overflow | nonzero
# scc unchanged | carry_out | borrow | signed_overflow | nonzero | relation | selected_src0
# vcc, exec unchanged (stated, not implied)
# wave any | wave32
# operands a key of [operand_rules]
@@ -230,3 +230,959 @@ wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 102 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
# ---- Stage C: further SOP2 logical and shift forms (#215) ----
# Shifts use the low shift_count_bits of S1 as the count (guide 12.1 pseudocode).
[[form]]
name = "S_ANDN2_B32"
family = "SOP2"
opcode = 20
variant = "Andn2B32"
operation = "andn2"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 103 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_ORN2_B32"
family = "SOP2"
opcode = 22
variant = "Orn2B32"
operation = "orn2"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 103 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_NAND_B32"
family = "SOP2"
opcode = 24
variant = "NandB32"
operation = "nand"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 104 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_NOR_B32"
family = "SOP2"
opcode = 26
variant = "NorB32"
operation = "nor"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 104 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_XNOR_B32"
family = "SOP2"
opcode = 28
variant = "XnorB32"
operation = "xnor"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 104 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_LSHL_B32"
family = "SOP2"
opcode = 30
variant = "LshlB32"
operation = "lshl"
signedness = "bitwise"
carry_in = "none"
width = 32
shift_count_bits = 5
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 104 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_LSHR_B32"
family = "SOP2"
opcode = 32
variant = "LshrB32"
operation = "lshr"
signedness = "unsigned"
carry_in = "none"
width = 32
shift_count_bits = 5
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 104 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_ASHR_I32"
family = "SOP2"
opcode = 34
variant = "AshrI32"
operation = "ashr"
signedness = "signed"
carry_in = "none"
width = 32
shift_count_bits = 5
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 104 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
# ---- SOP2 32-bit integer arithmetic, select and bit-field forms (#215) ----
# min/max: SCC = S0 chosen by the strict compare (a tie gives S1, SCC 0). cselect
# reads SCC and writes none. bfm, mul, mul_hi write no SCC (Tables 11, 12, 14).
# bfe: offset S1[4:0], width S1[22:16]. lshl_add: SCC = carry of (S0 << N) + S1.
[[form]]
name = "S_MIN_I32"
family = "SOP2"
opcode = 6
variant = "MinI32"
operation = "min"
signedness = "signed"
carry_in = "none"
width = 32
scc = "selected_src0"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [
{ document = "guide", section = "12.1", page = 102 },
{ document = "guide", section = "5.4", page = 34 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_MIN_U32"
family = "SOP2"
opcode = 7
variant = "MinU32"
operation = "min"
signedness = "unsigned"
carry_in = "none"
width = 32
scc = "selected_src0"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [
{ document = "guide", section = "12.1", page = 102 },
{ document = "guide", section = "5.4", page = 34 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_MAX_I32"
family = "SOP2"
opcode = 8
variant = "MaxI32"
operation = "max"
signedness = "signed"
carry_in = "none"
width = 32
scc = "selected_src0"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [
{ document = "guide", section = "12.1", page = 102 },
{ document = "guide", section = "5.4", page = 34 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_MAX_U32"
family = "SOP2"
opcode = 9
variant = "MaxU32"
operation = "max"
signedness = "unsigned"
carry_in = "none"
width = 32
scc = "selected_src0"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [
{ document = "guide", section = "12.1", page = 103 },
{ document = "guide", section = "5.4", page = 34 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_CSELECT_B32"
family = "SOP2"
opcode = 10
variant = "CselectB32"
operation = "cselect"
signedness = "bitwise"
carry_in = "scc"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [
{ document = "guide", section = "12.1", page = 103 },
{ document = "guide", section = "5.5", page = 34 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_BFM_B32"
family = "SOP2"
opcode = 36
variant = "BfmB32"
operation = "bfm"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [
{ document = "guide", section = "12.1", page = 104 },
{ document = "guide", section = "5.7", page = 36 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_MUL_I32"
family = "SOP2"
opcode = 38
variant = "MulI32"
operation = "mul"
signedness = "signed"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [
{ document = "guide", section = "12.1", page = 105 },
{ document = "guide", section = "5.4", page = 34 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_BFE_U32"
family = "SOP2"
opcode = 39
variant = "BfeU32"
operation = "bfe"
signedness = "unsigned"
carry_in = "none"
width = 32
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [
{ document = "guide", section = "12.1", page = 105 },
{ document = "guide", section = "5.7", page = 36 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_BFE_I32"
family = "SOP2"
opcode = 40
variant = "BfeI32"
operation = "bfe"
signedness = "signed"
carry_in = "none"
width = 32
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [
{ document = "guide", section = "12.1", page = 105 },
{ document = "guide", section = "5.7", page = 36 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_ABSDIFF_I32"
family = "SOP2"
opcode = 44
variant = "AbsdiffI32"
operation = "absdiff"
signedness = "signed"
carry_in = "none"
width = 32
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [
{ document = "guide", section = "12.1", page = 105 },
{ document = "guide", section = "5.4", page = 34 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_LSHL1_ADD_U32"
family = "SOP2"
opcode = 46
variant = "Lshl1AddU32"
operation = "lshl_add"
signedness = "unsigned"
carry_in = "none"
width = 32
shift_amount = 1
scc = "carry_out"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 105 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_LSHL2_ADD_U32"
family = "SOP2"
opcode = 47
variant = "Lshl2AddU32"
operation = "lshl_add"
signedness = "unsigned"
carry_in = "none"
width = 32
shift_amount = 2
scc = "carry_out"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 105 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_LSHL3_ADD_U32"
family = "SOP2"
opcode = 48
variant = "Lshl3AddU32"
operation = "lshl_add"
signedness = "unsigned"
carry_in = "none"
width = 32
shift_amount = 3
scc = "carry_out"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 106 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_LSHL4_ADD_U32"
family = "SOP2"
opcode = 49
variant = "Lshl4AddU32"
operation = "lshl_add"
signedness = "unsigned"
carry_in = "none"
width = 32
shift_amount = 4
scc = "carry_out"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 106 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_MUL_HI_U32"
family = "SOP2"
opcode = 53
variant = "MulHiU32"
operation = "mul_hi"
signedness = "unsigned"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 106 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_MUL_HI_I32"
family = "SOP2"
opcode = 54
variant = "MulHiI32"
operation = "mul_hi"
signedness = "signed"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 106 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
# ---- Stage D: SOPC 32-bit integer compares (#215) ----
# Only SCC is written: SCC = relation(S0, S1), S0 = SSRC0 on the left (guide 12.4).
[operand_rules.sopc_scalar]
family = "SOPC"
src = [
{ field = "SSRC0", class = "scalar_source" },
{ field = "SSRC1", class = "scalar_source" },
]
max_literals = 1
unsupported = [
"src_vcc", "src_exec", "src_m0", "src_ttmp", "src_float_inline",
"src_special", "two_literals",
]
[[form]]
name = "S_CMP_EQ_I32"
family = "SOPC"
opcode = 0
variant = "CmpEqI32"
operation = "compare"
relation = "eq"
signedness = "signed"
carry_in = "none"
width = 32
scc = "relation"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sopc_scalar"
spec = [
{ document = "guide", section = "12.4", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_CMP_LG_I32"
family = "SOPC"
opcode = 1
variant = "CmpLgI32"
operation = "compare"
relation = "lg"
signedness = "signed"
carry_in = "none"
width = 32
scc = "relation"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sopc_scalar"
spec = [
{ document = "guide", section = "12.4", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_CMP_GT_I32"
family = "SOPC"
opcode = 2
variant = "CmpGtI32"
operation = "compare"
relation = "gt"
signedness = "signed"
carry_in = "none"
width = 32
scc = "relation"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sopc_scalar"
spec = [
{ document = "guide", section = "12.4", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_CMP_GE_I32"
family = "SOPC"
opcode = 3
variant = "CmpGeI32"
operation = "compare"
relation = "ge"
signedness = "signed"
carry_in = "none"
width = 32
scc = "relation"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sopc_scalar"
spec = [
{ document = "guide", section = "12.4", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_CMP_LT_I32"
family = "SOPC"
opcode = 4
variant = "CmpLtI32"
operation = "compare"
relation = "lt"
signedness = "signed"
carry_in = "none"
width = 32
scc = "relation"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sopc_scalar"
spec = [
{ document = "guide", section = "12.4", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_CMP_LE_I32"
family = "SOPC"
opcode = 5
variant = "CmpLeI32"
operation = "compare"
relation = "le"
signedness = "signed"
carry_in = "none"
width = 32
scc = "relation"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sopc_scalar"
spec = [
{ document = "guide", section = "12.4", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_CMP_EQ_U32"
family = "SOPC"
opcode = 6
variant = "CmpEqU32"
operation = "compare"
relation = "eq"
signedness = "unsigned"
carry_in = "none"
width = 32
scc = "relation"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sopc_scalar"
spec = [
{ document = "guide", section = "12.4", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_CMP_LG_U32"
family = "SOPC"
opcode = 7
variant = "CmpLgU32"
operation = "compare"
relation = "lg"
signedness = "unsigned"
carry_in = "none"
width = 32
scc = "relation"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sopc_scalar"
spec = [
{ document = "guide", section = "12.4", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_CMP_GT_U32"
family = "SOPC"
opcode = 8
variant = "CmpGtU32"
operation = "compare"
relation = "gt"
signedness = "unsigned"
carry_in = "none"
width = 32
scc = "relation"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sopc_scalar"
spec = [
{ document = "guide", section = "12.4", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_CMP_GE_U32"
family = "SOPC"
opcode = 9
variant = "CmpGeU32"
operation = "compare"
relation = "ge"
signedness = "unsigned"
carry_in = "none"
width = 32
scc = "relation"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sopc_scalar"
spec = [
{ document = "guide", section = "12.4", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_CMP_LT_U32"
family = "SOPC"
opcode = 10
variant = "CmpLtU32"
operation = "compare"
relation = "lt"
signedness = "unsigned"
carry_in = "none"
width = 32
scc = "relation"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sopc_scalar"
spec = [
{ document = "guide", section = "12.4", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_CMP_LE_U32"
family = "SOPC"
opcode = 11
variant = "CmpLeU32"
operation = "compare"
relation = "le"
signedness = "unsigned"
carry_in = "none"
width = 32
scc = "relation"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sopc_scalar"
spec = [
{ document = "guide", section = "12.4", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
# ---- SOP1 32-bit unary integer forms (#215) ----
# NOT, BCNT0, BCNT1 and ABS set SCC = (D != 0); the others leave SCC unchanged.
# Searches that find nothing return -1 (guide 12.3).
[operand_rules.sop1_sgpr]
family = "SOP1"
dst = { field = "SDST", class = "sgpr", min = 0, max = 105 }
src = [{ field = "SSRC0", class = "scalar_source" }]
max_literals = 1
unsupported = [
"dst_vcc", "dst_exec", "dst_ttmp", "dst_m0", "dst_null",
"src_vcc", "src_exec", "src_m0", "src_ttmp", "src_float_inline", "src_special",
]
[[form]]
name = "S_NOT_B32"
family = "SOP1"
opcode = 7
variant = "NotB32"
operation = "not"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop1_sgpr"
spec = [
{ document = "guide", section = "12.3", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_BREV_B32"
family = "SOP1"
opcode = 11
variant = "BrevB32"
operation = "brev"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop1_sgpr"
spec = [
{ document = "guide", section = "12.3", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_BCNT0_I32_B32"
family = "SOP1"
opcode = 13
variant = "Bcnt0I32B32"
operation = "bcnt0"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop1_sgpr"
spec = [
{ document = "guide", section = "12.3", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_BCNT1_I32_B32"
family = "SOP1"
opcode = 15
variant = "Bcnt1I32B32"
operation = "bcnt1"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop1_sgpr"
spec = [
{ document = "guide", section = "12.3", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_FF0_I32_B32"
family = "SOP1"
opcode = 17
variant = "Ff0I32B32"
operation = "ff0"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop1_sgpr"
spec = [
{ document = "guide", section = "12.3", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_FF1_I32_B32"
family = "SOP1"
opcode = 19
variant = "Ff1I32B32"
operation = "ff1"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop1_sgpr"
spec = [
{ document = "guide", section = "12.3", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_FLBIT_I32_B32"
family = "SOP1"
opcode = 21
variant = "FlbitI32B32"
operation = "flbit"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop1_sgpr"
spec = [
{ document = "guide", section = "12.3", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_FLBIT_I32"
family = "SOP1"
opcode = 23
variant = "FlbitI32"
operation = "flbit"
signedness = "signed"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop1_sgpr"
spec = [
{ document = "guide", section = "12.3", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_SEXT_I32_I8"
family = "SOP1"
opcode = 25
variant = "SextI32I8"
operation = "sext"
signedness = "signed"
carry_in = "none"
width = 32
source_bits = 8
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop1_sgpr"
spec = [
{ document = "guide", section = "12.3", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_SEXT_I32_I16"
family = "SOP1"
opcode = 26
variant = "SextI32I16"
operation = "sext"
signedness = "signed"
carry_in = "none"
width = 32
source_bits = 16
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop1_sgpr"
spec = [
{ document = "guide", section = "12.3", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_ABS_I32"
family = "SOP1"
opcode = 52
variant = "AbsI32"
operation = "abs"
signedness = "signed"
carry_in = "none"
width = 32
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop1_sgpr"
spec = [
{ document = "guide", section = "12.3", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
+22 -12
View File
@@ -12,13 +12,13 @@ mod rdna2_meta;
mod semantics_gen;
pub use rdna2::{
BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_BRANCH, S_CBRANCH_EXECZ,
S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_CMP_EQ_U32, S_ENDPGM, S_MOV_B32, S_WAITCNT, S_WAITCNT_VSCNT,
V_ADD_F32, V_ADD_NC_U32, V_AND_B32, V_ASHRREV_I32, V_CMP_EQ_I32, V_CMP_EQ_U32, V_CMP_GE_I32,
V_CMP_GE_U32, V_CMP_GT_I32, V_CMP_GT_U32, V_CMP_LE_I32, V_CMP_LE_U32, V_CMP_LT_I32,
V_CMP_LT_U32, V_CMP_NE_I32, V_CMP_NE_U32, V_INTERP_P1_F32, V_INTERP_P2_F32, V_LSHLREV_B32,
V_LSHRREV_B32, V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32,
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,
};
pub use semantics_gen::ScalarAluOp;
pub use semantics_gen::{ScalarAluOp, ScalarCompareOp, ScalarUnaryOp};
/// SGPR index of `vcc_lo`, the Wave32 vector condition code.
pub const VCC_LO: u8 = 106;
@@ -209,15 +209,24 @@ pub enum Instruction {
AddNoCarryU32 { dst: u8, src0: u8, src1: u8 },
/// SOP1 32-bit move to a normal SGPR or an EXEC/VCC half.
ScalarMoveB32 { dst: u8, src: ScalarSource },
/// SOP2 32-bit integer operation writing a normal SGPR (s0-s105) and SCC.
/// SOP1 32-bit unary integer operation writing a normal SGPR (s0-s105) and,
/// for some operations, SCC.
ScalarUnary {
op: ScalarUnaryOp,
dst: u8,
src: ScalarSource,
},
/// SOP2 32-bit integer operation writing a normal SGPR (s0-s105) and, for
/// most operations, SCC; `s_cselect_b32` also reads SCC.
ScalarAlu {
op: ScalarAluOp,
dst: u8,
src0: ScalarSource,
src1: ScalarSource,
},
/// SOPC 32-bit equality comparison writing SCC.
ScalarCompareEqU32 {
/// SOPC 32-bit integer compare writing only SCC.
ScalarCompare {
op: ScalarCompareOp,
src0: ScalarSource,
src1: ScalarSource,
},
@@ -306,8 +315,9 @@ impl Instruction {
Self::MoveB32 { .. } => "v_mov_b32_e32",
Self::AddNoCarryU32 { .. } => "v_add_nc_u32_e64",
Self::ScalarMoveB32 { .. } => "s_mov_b32",
Self::ScalarUnary { op, .. } => op.mnemonic(),
Self::ScalarAlu { op, .. } => op.mnemonic(),
Self::ScalarCompareEqU32 { .. } => "s_cmp_eq_u32",
Self::ScalarCompare { op, .. } => op.mnemonic(),
Self::VectorCompare { op, .. } => op.mnemonic(),
Self::BranchSccZero { .. } => "s_cbranch_scc0",
Self::BranchExecZero { .. } => "s_cbranch_execz",
@@ -370,13 +380,13 @@ impl fmt::Display for Instruction {
| Self::VectorMulF32 { dst, src0, src1 } => {
write!(formatter, " v{dst}, v{src0}, v{src1}")
}
Self::ScalarMoveB32 { dst, src } => {
Self::ScalarMoveB32 { dst, src } | Self::ScalarUnary { dst, src, .. } => {
write!(formatter, " {}, {src}", ScalarDestination(dst))
}
Self::ScalarAlu {
dst, src0, src1, ..
} => write!(formatter, " {}, {src0}, {src1}", ScalarDestination(dst)),
Self::ScalarCompareEqU32 { src0, src1 } => write!(formatter, " {src0}, {src1}"),
Self::ScalarCompare { src0, src1, .. } => write!(formatter, " {src0}, {src1}"),
Self::VectorCompare { src0, src1, .. } => {
write!(formatter, " vcc_lo, {src0}, v{src1}")
}
+267
View File
@@ -49,3 +49,270 @@ pub const fn xor_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
let value = a ^ b;
(value, value != 0)
}
/// Bitwise `a & !b` and whether the result is nonzero.
pub const fn andn2_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
let value = a & !b;
(value, value != 0)
}
/// Bitwise `a | !b` and whether the result is nonzero.
pub const fn orn2_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
let value = a | !b;
(value, value != 0)
}
/// Bitwise `!(a & b)` and whether the result is nonzero.
pub const fn nand_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
let value = !(a & b);
(value, value != 0)
}
/// Bitwise `!(a | b)` and whether the result is nonzero.
pub const fn nor_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
let value = !(a | b);
(value, value != 0)
}
/// Bitwise `!(a ^ b)` and whether the result is nonzero.
pub const fn xnor_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
let value = !(a ^ b);
(value, value != 0)
}
/// `a << count` and whether the result is nonzero. The caller masks the count
/// to the declared count width, so `count` is below 32.
pub const fn lshl_nonzero_b32(a: u32, count: u32) -> (u32, bool) {
let value = a << count;
(value, value != 0)
}
/// Logical `a >> count` (zero fill) and whether the result is nonzero; `count` is below 32.
pub const fn lshr_nonzero_b32(a: u32, count: u32) -> (u32, bool) {
let value = a >> count;
(value, value != 0)
}
/// Arithmetic `a >> count` (sign fill) and whether the result is nonzero; `count` is below 32.
pub const fn ashr_nonzero_i32(a: u32, count: u32) -> (u32, bool) {
let value = ((a as i32) >> count) as u32;
(value, value != 0)
}
/// `a == b` on the raw bits; signedness does not matter for equality.
pub const fn eq_b32(a: u32, b: u32) -> bool {
a == b
}
/// `a != b` on the raw bits (the guide's LG, "less or greater").
pub const fn ne_b32(a: u32, b: u32) -> bool {
a != b
}
/// Two's-complement `a > b`.
pub const fn gt_i32(a: u32, b: u32) -> bool {
(a as i32) > (b as i32)
}
/// Two's-complement `a >= b`.
pub const fn ge_i32(a: u32, b: u32) -> bool {
(a as i32) >= (b as i32)
}
/// Two's-complement `a < b`.
pub const fn lt_i32(a: u32, b: u32) -> bool {
(a as i32) < (b as i32)
}
/// Two's-complement `a <= b`.
pub const fn le_i32(a: u32, b: u32) -> bool {
(a as i32) <= (b as i32)
}
/// Unsigned `a > b`.
pub const fn gt_u32(a: u32, b: u32) -> bool {
a > b
}
/// Unsigned `a >= b`.
pub const fn ge_u32(a: u32, b: u32) -> bool {
a >= b
}
/// Unsigned `a < b`.
pub const fn lt_u32(a: u32, b: u32) -> bool {
a < b
}
/// Unsigned `a <= b`.
pub const fn le_u32(a: u32, b: u32) -> bool {
a <= b
}
/// `!a` and whether the result is nonzero.
pub const fn not_nonzero_b32(a: u32) -> (u32, bool) {
let value = !a;
(value, value != 0)
}
/// `a` with bit `i` moved to bit `31 - i`.
pub const fn brev_b32(a: u32) -> u32 {
a.reverse_bits()
}
/// Number of zero bits and whether that count is nonzero.
pub const fn bcnt0_nonzero_b32(a: u32) -> (u32, bool) {
let value = a.count_zeros();
(value, value != 0)
}
/// Number of one bits and whether that count is nonzero.
pub const fn bcnt1_nonzero_b32(a: u32) -> (u32, bool) {
let value = a.count_ones();
(value, value != 0)
}
/// Index of the lowest zero bit, or `0xffffffff` (-1) when every bit is one.
pub const fn ff0_b32(a: u32) -> u32 {
if a == u32::MAX {
u32::MAX
} else {
a.trailing_ones()
}
}
/// Index of the lowest one bit, or `0xffffffff` (-1) when every bit is zero.
pub const fn ff1_b32(a: u32) -> u32 {
if a == 0 { u32::MAX } else { a.trailing_zeros() }
}
/// Zeros above the highest one bit, or `0xffffffff` (-1) when `a` is zero.
pub const fn flbit_b32(a: u32) -> u32 {
if a == 0 { u32::MAX } else { a.leading_zeros() }
}
/// Bits above the highest bit that differs from the sign bit, or `0xffffffff`
/// (-1) when every bit equals the sign bit (`a` is 0 or -1).
pub const fn flbit_i32(a: u32) -> u32 {
let differing = if a >> 31 == 0 { a } else { !a };
if differing == 0 {
u32::MAX
} else {
differing.leading_zeros()
}
}
/// The low `bits` of `a` sign-extended to 32 bits; `bits` is 8 or 16.
pub const fn sext_i32(a: u32, bits: u32) -> u32 {
let shift = 32 - bits;
(((a << shift) as i32) >> shift) as u32
}
/// Two's-complement absolute value (wrapping, so `0x80000000` stays) and
/// whether the result is nonzero.
pub const fn abs_nonzero_i32(a: u32) -> (u32, bool) {
let value = (a as i32).wrapping_abs() as u32;
(value, value != 0)
}
/// Two's-complement minimum and whether S0 was strictly smaller (so equal
/// operands give S1 and `false`).
pub const fn min_i32(a: u32, b: u32) -> (u32, bool) {
let first = (a as i32) < (b as i32);
(if first { a } else { b }, first)
}
/// Unsigned minimum and whether S0 was strictly smaller.
pub const fn min_u32(a: u32, b: u32) -> (u32, bool) {
let first = a < b;
(if first { a } else { b }, first)
}
/// Two's-complement maximum and whether S0 was strictly greater (so equal
/// operands give S1 and `false`).
pub const fn max_i32(a: u32, b: u32) -> (u32, bool) {
let first = (a as i32) > (b as i32);
(if first { a } else { b }, first)
}
/// Unsigned maximum and whether S0 was strictly greater.
pub const fn max_u32(a: u32, b: u32) -> (u32, bool) {
let first = a > b;
(if first { a } else { b }, first)
}
/// `a` when `condition` (SCC) is set, otherwise `b`.
pub const fn cselect_b32(a: u32, b: u32, condition: bool) -> u32 {
if condition { a } else { b }
}
/// `((1 << a[4:0]) - 1) << b[4:0]`: a mask of `a[4:0]` ones starting at bit `b[4:0]`.
pub const fn bfm_b32(a: u32, b: u32) -> u32 {
((1u32 << (a & 0x1f)) - 1) << (b & 0x1f)
}
/// The low 32 bits of the product (identical for signed and unsigned operands).
pub const fn mul_lo_i32(a: u32, b: u32) -> u32 {
a.wrapping_mul(b)
}
/// The high 32 bits of the unsigned 64-bit product.
pub const fn mul_hi_u32(a: u32, b: u32) -> u32 {
((a as u64 * b as u64) >> 32) as u32
}
/// The high 32 bits of the two's-complement 64-bit product.
pub const fn mul_hi_i32(a: u32, b: u32) -> u32 {
((a as i32 as i64 * b as i32 as i64) >> 32) as u32
}
/// The `bfe` field descriptor: offset `b[4:0]` and width `b[22:16]` (0-127).
const fn bfe_field(b: u32) -> (u32, u32) {
(b & 0x1f, (b >> 16) & 0x7f)
}
/// Unsigned bit-field extract: `(a >> offset) & ((1 << width) - 1)`, where a
/// width of 32 or more keeps every shifted bit; and whether the result is nonzero.
pub const fn bfe_nonzero_u32(a: u32, b: u32) -> (u32, bool) {
let (offset, width) = bfe_field(b);
let shifted = a >> offset;
let value = if width == 0 {
0
} else if width >= 32 {
shifted
} else {
shifted & ((1 << width) - 1)
};
(value, value != 0)
}
/// Signed bit-field extract: `a` shifted arithmetically by the offset, the low
/// `width` bits kept and sign-extended from bit `width - 1` (a width of 32 or
/// more keeps the whole shifted word); and whether the result is nonzero.
pub const fn bfe_nonzero_i32(a: u32, b: u32) -> (u32, bool) {
let (offset, width) = bfe_field(b);
let shifted = ((a as i32) >> offset) as u32;
let value = if width == 0 {
0
} else if width >= 32 {
shifted
} else {
let unused = 32 - width;
(((shifted << unused) as i32) >> unused) as u32
};
(value, value != 0)
}
/// `|a - b|` of the wrapped 32-bit difference (so `0x80000000` stays) and
/// whether the result is nonzero.
pub const fn absdiff_nonzero_i32(a: u32, b: u32) -> (u32, bool) {
let value = (a.wrapping_sub(b) as i32).unsigned_abs();
(value, value != 0)
}
/// `(a << shift) + b` and the carry out of the exact sum, which counts the bits
/// shifted out of `a`; `shift` is 1 to 4.
pub const fn lshl_add_carry_u32(a: u32, b: u32, shift: u32) -> (u32, bool) {
let sum = ((a as u64) << shift) + b as u64;
(sum as u32, sum >> 32 != 0)
}
-5
View File
@@ -45,11 +45,6 @@ pub const S_MOV_B32: Opcode = Opcode {
bits: 0xbe800300,
bytes: 4,
};
pub const S_CMP_EQ_U32: Opcode = Opcode {
mask: 0xffff0000,
bits: 0xbf060000,
bytes: 4,
};
pub const S_CBRANCH_SCC0: Opcode = Opcode {
mask: 0xffff0000,
bits: 0xbf840000,
+79 -5
View File
@@ -9,6 +9,7 @@
//! The reference interpreter (`crates/ref`) and the independent interpreter
//! (`tests/validation/independent_ref.rs`) must not use this module.
use crate::CompareRelation;
use crate::meta::EncodingFamily;
pub use crate::semantics_gen::{FORM_IDS, FORMS, GENERATED_SCHEMA};
@@ -30,6 +31,61 @@ pub enum Operation {
Or,
/// Bitwise exclusive OR.
Xor,
/// Bitwise AND with the complement of S1.
AndNot,
/// Bitwise OR with the complement of S1.
OrNot,
/// Complement of bitwise AND.
Nand,
/// Complement of bitwise OR.
Nor,
/// Complement of bitwise exclusive OR.
Xnor,
/// Shift S0 left by the masked count in S1, filling with zeros.
ShiftLeft,
/// Shift S0 right by the masked count in S1, filling with zeros.
LogicalShiftRight,
/// Shift S0 right by the masked count in S1, filling with its sign bit.
ArithmeticShiftRight,
/// Compare S0 with S1 under the form's relation; writes only SCC.
Compare,
/// Bitwise complement of S0.
Not,
/// S0 with its bit order reversed.
ReverseBits,
/// Number of zero bits in S0.
CountZeros,
/// Number of one bits in S0.
CountOnes,
/// Index of the lowest zero bit of S0, or -1 when there is none.
FindFirstZero,
/// Index of the lowest one bit of S0, or -1 when there is none.
FindFirstOne,
/// Unsigned: count of zeros above the highest one bit; signed: count of bits
/// above the highest bit that differs from the sign bit. -1 when none.
FindLastBit,
/// Sign-extend the low `source_bits` of S0 to 32 bits.
SignExtend,
/// Two's-complement absolute value; the most negative value maps to itself.
Absolute,
/// S0 when it is strictly less than S1, otherwise S1.
Minimum,
/// S0 when it is strictly greater than S1, otherwise S1.
Maximum,
/// S0 when SCC is set, otherwise S1.
Select,
/// `((1 << S0[4:0]) - 1) << S1[4:0]`.
BitfieldMask,
/// Low 32 bits of the product.
Multiply,
/// High 32 bits of the 64-bit product.
MultiplyHigh,
/// The field of S0 at offset S1[4:0] with width S1[22:16]; sign-extended when signed.
BitfieldExtract,
/// Absolute value of the wrapped 32-bit difference S0 - S1.
AbsoluteDifference,
/// `(S0 << shift_amount) + S1`.
ShiftLeftAdd,
}
/// How the operands are interpreted. `Bitwise` exactly when the operation is logical.
@@ -43,12 +99,12 @@ pub enum Signedness {
Bitwise,
}
/// Extra input consumed by the operation.
/// Whether the operation reads SCC.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CarryIn {
/// No carry or borrow input.
/// SCC is not read.
None,
/// SCC as carry-in (add) or borrow-in (sub).
/// SCC as carry-in (add), borrow-in (sub) or the select condition (select).
Scc,
}
@@ -65,6 +121,10 @@ pub enum SccEffect {
SignedOverflow,
/// The result is not zero.
Nonzero,
/// The compare's relation holds for S0 and S1.
Relation,
/// The result is S0 by the strict comparison (min, max): equal operands give 0.
SelectedSrc0,
}
/// What a form writes to VCC or EXEC. Stage A forms leave both unchanged.
@@ -89,6 +149,12 @@ pub enum OperandRule {
/// SOP2: SDST is s0-s105; SSRC0/SSRC1 are s0-s105, inline integers -16..64
/// or one literal word. Everything else is rejected as unsupported.
Sop2Sgpr,
/// SOPC: no destination; SSRC0/SSRC1 as for SOP2 sources (s0-s105, inline
/// integers -16..64 or one literal word). Everything else is rejected.
SopcScalar,
/// 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,
}
/// Evidence a form needs before it counts as verified.
@@ -120,7 +186,7 @@ pub struct SpecRef {
pub document: Document,
/// Section number, for example `"12.1"`.
pub section: &'static str,
/// Page in the document, 0 when not paginated.
/// Page in the document, or 0 when the page has not been recorded.
pub page: u16,
}
@@ -137,10 +203,18 @@ pub struct FormSemantics {
pub operation: Operation,
/// Operand interpretation.
pub signedness: Signedness,
/// Carry or borrow input.
/// SCC input.
pub carry_in: CarryIn,
/// Operand and result width in bits.
pub width: u8,
/// Low bits of S1 used as the shift count by shift operations; 0 otherwise.
pub shift_count_bits: u8,
/// Fixed left shift of S0 for shift-and-add operations (1 to 4); 0 otherwise.
pub shift_amount: u8,
/// Low bits of S0 that the operation reads: `width`, or 8 or 16 for sign extension.
pub source_bits: u8,
/// The relation tested by compares (S0 on the left); `None` otherwise.
pub relation: Option<CompareRelation>,
/// SCC write.
pub scc: SccEffect,
/// VCC write.
File diff suppressed because it is too large. Load diff
+56 -28
View File
@@ -1,8 +1,8 @@
//! Ties the generated semantic registry tables to the independent XML metadata table.
use xenora_isa::ScalarAluOp;
use xenora_isa::meta::{EncodingFamily, FORMS as META_FORMS};
use xenora_isa::semantics::{CarryIn, FORM_IDS, FORMS, GENERATED_SCHEMA, SCHEMA};
use xenora_isa::semantics::{CarryIn, FORM_IDS, FORMS, GENERATED_SCHEMA, SCHEMA, SccEffect};
use xenora_isa::{ScalarAluOp, ScalarCompareOp, ScalarUnaryOp};
#[test]
fn generated_tables_match_the_schema_and_the_metadata_forms() {
@@ -18,43 +18,71 @@ fn generated_tables_match_the_schema_and_the_metadata_forms() {
}
}
#[test]
fn scalar_alu_dispatch_selects_exactly_the_registry_sop2_forms() {
assert_eq!(ScalarAluOp::ALL.len(), FORMS.len());
for op in ScalarAluOp::ALL {
let row = op.semantics();
assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic());
assert_eq!(op.reads_scc(), row.carry_in == CarryIn::Scc);
}
/// Every word of `family` that the XML metadata identifies selects an operation
/// exactly when the registry declares that form, and no 32-bit word of another
/// family selects one.
fn dispatch_selects_exactly(family: EncodingFamily, select: impl Fn(u32) -> Option<&'static str>) {
let declared: Vec<_> = FORMS.iter().filter(|row| row.family == family).collect();
let mut selected = 0;
for meta in META_FORMS
.iter()
.filter(|form| form.family == EncodingFamily::Sop2)
{
let word = meta.bits as u32;
match ScalarAluOp::from_word(word) {
Some(op) => {
assert_eq!(op.semantics().name, meta.name);
for meta in META_FORMS.iter().filter(|form| form.family == family) {
match select(meta.bits as u32) {
Some(name) => {
assert_eq!(name, meta.name);
selected += 1;
}
None => assert!(
FORMS.iter().all(|row| row.name != meta.name),
declared.iter().all(|row| row.name != meta.name),
"{} is declared but not dispatched",
meta.name
),
}
}
assert_eq!(selected, FORMS.len());
// Other encodings never reach the SOP2 dispatch.
assert_eq!(selected, declared.len());
for meta in META_FORMS
.iter()
.filter(|form| form.family != EncodingFamily::Sop2 && form.bytes == 4)
.filter(|form| form.family != family && form.bytes == 4)
{
assert_eq!(
ScalarAluOp::from_word(meta.bits as u32),
None,
"{}",
meta.name
);
assert_eq!(select(meta.bits as u32), None, "{}", meta.name);
}
}
#[test]
fn scalar_alu_dispatch_selects_exactly_the_registry_sop2_forms() {
for op in ScalarAluOp::ALL {
let row = op.semantics();
assert_eq!(row.family, EncodingFamily::Sop2);
assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic());
assert_eq!(op.reads_scc(), row.carry_in == CarryIn::Scc);
assert_eq!(op.writes_scc(), row.scc != SccEffect::Unchanged);
}
dispatch_selects_exactly(EncodingFamily::Sop2, |word| {
ScalarAluOp::from_word(word).map(|op| op.semantics().name)
});
}
#[test]
fn scalar_compare_dispatch_selects_exactly_the_registry_sopc_forms() {
for op in ScalarCompareOp::ALL {
let row = op.semantics();
assert_eq!(row.family, EncodingFamily::Sopc);
assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic());
assert_eq!(row.relation, Some(op.relation()));
}
dispatch_selects_exactly(EncodingFamily::Sopc, |word| {
ScalarCompareOp::from_word(word).map(|op| op.semantics().name)
});
}
#[test]
fn scalar_unary_dispatch_selects_exactly_the_registry_sop1_forms() {
for op in ScalarUnaryOp::ALL {
let row = op.semantics();
assert_eq!(row.family, EncodingFamily::Sop1);
assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic());
assert_eq!(op.writes_scc(), row.scc != SccEffect::Unchanged);
}
// s_mov_b32 (opcode 3) stays hand-written, so it must not be dispatched here.
dispatch_selects_exactly(EncodingFamily::Sop1, |word| {
ScalarUnaryOp::from_word(word).map(|op| op.semantics().name)
});
}
+242 -53
View File
@@ -53,6 +53,27 @@ impl Register {
}
}
/// Instruction prefixes decoded ahead of an opcode.
///
/// The interpreter decodes these once per instruction and passes them to the
/// helpers that need them, so prefix state travels as one typed value instead
/// of a list of independent booleans.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
struct Prefixes {
/// REX.W: 64-bit operand size.
rex_w: bool,
/// REX.R: extends the ModRM `reg` field to R8-R15.
rex_r: bool,
/// REX.X: extends the SIB `index` field to R8-R15.
rex_x: bool,
/// REX.B: extends the ModRM `rm` field to R8-R15.
rex_b: bool,
/// The GS segment override prefix (0x65) is present.
seg_gs: bool,
/// The FS segment override prefix (0x64) is present.
seg_fs: bool,
}
/// RFLAGS status bits tracked during guest execution.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct RFlags {
@@ -153,6 +174,167 @@ mod layout_tests {
}
}
#[cfg(test)]
mod prefix_tests {
use super::{CpuState, ExitReason, Interpreter, Register};
use crate::memory::{GuestMemory, MemoryPermissions};
const CODE_BASE: u64 = 0x1000;
const CODE_SIZE: usize = 0x1000;
const STACK_BASE: u64 = 0x8000_0000;
const STACK_SIZE: usize = 0x10000;
const FS_BASE: u64 = 0x9000;
const GS_BASE: u64 = 0xA000;
/// A guest memory image with executable code, a stack and distinct FS and
/// GS bases.
fn memory_with_code(code: &[u8]) -> GuestMemory {
let mut memory = GuestMemory::new();
memory
.map_region_with_data(
CODE_BASE,
CODE_SIZE,
MemoryPermissions::READ_WRITE_EXECUTE,
code,
)
.expect("code region");
memory
.map_region(STACK_BASE, STACK_SIZE, MemoryPermissions::READ_WRITE)
.expect("stack region");
// The segment bases are distinct so a swapped prefix is visible.
memory
.map_region(FS_BASE, 0x1000, MemoryPermissions::READ_WRITE)
.expect("fs region");
memory
.map_region(GS_BASE, 0x1000, MemoryPermissions::READ_WRITE)
.expect("gs region");
memory
}
/// Run `code` on the interpreter and return the final state and exit reason.
fn run(code: &[u8]) -> (CpuState, ExitReason) {
let mut memory = memory_with_code(code);
let cpu = CpuState::new(CODE_BASE, STACK_BASE + 0x8000);
let mut interp = Interpreter::new(cpu, &mut memory, 64);
let result = interp.run();
(result.final_state, result.exit_reason)
}
/// `mov r8, imm64`: 49 B8 <imm64>.
fn mov_r8_imm64(value: u64) -> Vec<u8> {
let mut code = vec![0x49, 0xB8];
code.extend_from_slice(&value.to_le_bytes());
code
}
/// `mov rbx, imm64`: 48 BB <imm64>.
fn mov_rbx_imm64(value: u64) -> Vec<u8> {
let mut code = vec![0x48, 0xBB];
code.extend_from_slice(&value.to_le_bytes());
code
}
/// `mov rax, imm64`: 48 B8 <imm64>.
fn mov_rax_imm64(value: u64) -> Vec<u8> {
let mut code = vec![0x48, 0xB8];
code.extend_from_slice(&value.to_le_bytes());
code
}
/// REX.B extends the ModRM `rm` field, so `rm=0` selects r8.
///
/// Encoding 49 89 D8 is `mov r8, rbx`.
#[test]
fn rex_b_extends_the_rm_field_to_r8() {
let mut code = mov_rbx_imm64(0x1122_3344_5566_7788);
code.extend_from_slice(&[0x49, 0x89, 0xD8]); // mov r8, rbx
code.push(0xF4); // hlt
let (state, reason) = run(&code);
assert_eq!(reason, ExitReason::Halt);
assert_eq!(state.get(Register::Rbx), 0x1122_3344_5566_7788);
assert_eq!(state.get(Register::R8), 0x1122_3344_5566_7788);
// No prefix in this encoding selects r9.
assert_eq!(state.get(Register::R9), 0);
}
/// REX.R extends the ModRM `reg` field, so `reg=0` selects r8.
///
/// Encoding 4C 89 C3 is `mov rbx, r8`.
#[test]
fn rex_r_extends_the_reg_field_to_r8() {
let mut code = mov_r8_imm64(0x1122_3344_5566_7788);
code.extend_from_slice(&[0x4C, 0x89, 0xC3]); // mov rbx, r8
code.push(0xF4); // hlt
let (state, reason) = run(&code);
assert_eq!(reason, ExitReason::Halt);
assert_eq!(state.get(Register::R8), 0x1122_3344_5566_7788);
assert_eq!(state.get(Register::Rbx), 0x1122_3344_5566_7788);
// No prefix in this encoding selects r9.
assert_eq!(state.get(Register::R9), 0);
}
/// REX.R and REX.B extend independent fields, so the destination r9 and
/// the source r12 are chosen by different prefix bits.
///
/// Encoding 4D 89 E1 is `mov r9, r12`.
#[test]
fn rex_r_and_rex_b_extend_independent_fields() {
let mut code = mov_r8_imm64(0x1122_3344_5566_7788);
code.extend_from_slice(&[0x4D, 0x89, 0xE1]); // mov r9, r12
code.push(0xF4); // hlt
let (state, reason) = run(&code);
assert_eq!(reason, ExitReason::Halt);
// r9 receives r12, which is zero here, and not the value in r8.
assert_eq!(state.get(Register::R9), 0);
assert_eq!(state.get(Register::R12), 0);
assert_eq!(state.get(Register::R8), 0x1122_3344_5566_7788);
}
/// Without REX.W the move is 32-bit wide, so the destination keeps only the
/// low half of the source and its upper half is cleared.
///
/// Encoding 89 D8 is `mov eax, ebx`.
#[test]
fn a_move_without_rex_w_is_32_bit_wide() {
let mut code = mov_rbx_imm64(0x1122_3344_5566_7788);
code.extend_from_slice(&[0x89, 0xD8]); // mov eax, ebx
code.push(0xF4); // hlt
let (state, reason) = run(&code);
assert_eq!(reason, ExitReason::Halt);
// Only the low 32 bits of ebx survive, and rax's upper half is cleared.
assert_eq!(state.get(Register::Rax), 0x5566_7788);
assert_eq!(state.get(Register::Rbx), 0x1122_3344_5566_7788);
}
/// The FS segment override adds the FS base to the effective address.
///
/// Encoding 64 48 89 04 25 08 00 00 00 is `mov fs:[0x8], rax`.
#[test]
fn the_fs_prefix_adds_the_fs_base() {
let mut code = mov_rax_imm64(0x1122_3344_5566_7788);
code.extend_from_slice(&[0x64, 0x48, 0x89, 0x04, 0x25, 0x08, 0x00, 0x00, 0x00]);
code.push(0xF4); // hlt
let mut memory = memory_with_code(&code);
let mut cpu = CpuState::new(CODE_BASE, STACK_BASE + 0x8000);
cpu.fs_base = FS_BASE;
cpu.gs_base = GS_BASE;
let mut interp = Interpreter::new(cpu, &mut memory, 64);
let result = interp.run();
assert_eq!(result.exit_reason, ExitReason::Halt);
assert_eq!(
memory.read_u64(FS_BASE + 0x8).expect("fs read"),
0x1122_3344_5566_7788
);
// The GS base is untouched: the GS-prefixed store did not happen.
assert_eq!(memory.read_u64(GS_BASE + 0x8).expect("gs read"), 0);
}
}
/// Result returned after running guest execution.
#[derive(Debug)]
pub struct ExecutionResult {
@@ -255,29 +437,26 @@ impl<'a> Interpreter<'a> {
}
fn execute_instruction(&mut self) -> Result<Option<ExitReason>, ExitReason> {
let mut rex_w = false;
let mut rex_r = false;
let mut rex_b = false;
let mut seg_gs = false;
let mut seg_fs = false;
let mut prefixes = Prefixes::default();
let mut byte = self.fetch_u8()?;
// Handle legacy segment prefixes: 0x65 (GS), 0x64 (FS)
while byte == 0x65 || byte == 0x64 {
if byte == 0x65 {
seg_gs = true;
prefixes.seg_gs = true;
} else {
seg_fs = true;
prefixes.seg_fs = true;
}
byte = self.fetch_u8()?;
}
// Handle REX prefix (0x40 - 0x4F)
if (byte & 0xF0) == 0x40 {
rex_w = (byte & 0x08) != 0;
rex_r = (byte & 0x04) != 0;
rex_b = (byte & 0x01) != 0;
prefixes.rex_w = (byte & 0x08) != 0;
prefixes.rex_r = (byte & 0x04) != 0;
prefixes.rex_x = (byte & 0x02) != 0;
prefixes.rex_b = (byte & 0x01) != 0;
byte = self.fetch_u8()?;
}
@@ -288,9 +467,9 @@ impl<'a> Interpreter<'a> {
0x0F => match self.fetch_u8()? {
0x05 => Ok(Some(ExitReason::Syscall(self.cpu.get(Register::Rax)))),
op @ 0xC8..=0xCF => {
let reg = Register::from_index((op & 7) | (u8::from(rex_b) << 3));
let reg = Register::from_index((op & 7) | (u8::from(prefixes.rex_b) << 3));
let value = self.cpu.get(reg);
let reversed = if rex_w {
let reversed = if prefixes.rex_w {
value.swap_bytes()
} else {
u64::from((value as u32).swap_bytes())
@@ -303,9 +482,9 @@ impl<'a> Interpreter<'a> {
// MOV r32, imm32 (0xB8 + reg) or MOV r64, imm64 with REX.W
0xB8..=0xBF => {
let reg_idx = (byte - 0xB8) + if rex_b { 8 } else { 0 };
let reg_idx = (byte - 0xB8) + if prefixes.rex_b { 8 } else { 0 };
let reg = Register::from_index(reg_idx);
if rex_w {
if prefixes.rex_w {
let imm = self.fetch_u64()?;
self.cpu.set(reg, imm);
} else {
@@ -318,28 +497,28 @@ impl<'a> Interpreter<'a> {
// XOR r/m, reg (0x31) or XOR reg, r/m (0x33)
0x31 | 0x33 => {
let modrm = self.fetch_u8()?;
let (reg, rm) = self.decode_modrm_reg_reg(modrm, rex_r, rex_b)?;
let (reg, rm) = self.decode_modrm_reg_reg(modrm, &prefixes)?;
let (src, dst) = if byte == 0x31 { (reg, rm) } else { (rm, reg) };
let val1 = self.cpu.get(dst);
let val2 = self.cpu.get(src);
let res = if rex_w {
let res = if prefixes.rex_w {
val1 ^ val2
} else {
(val1 as u32 ^ val2 as u32) as u64
};
self.cpu.set(dst, res);
self.update_flags_logic(res, rex_w);
self.update_flags_logic(res, prefixes.rex_w);
Ok(None)
}
// ADD r/m, reg (0x01) or ADD reg, r/m (0x03)
0x01 | 0x03 => {
let modrm = self.fetch_u8()?;
let (reg, rm) = self.decode_modrm_reg_reg(modrm, rex_r, rex_b)?;
let (reg, rm) = self.decode_modrm_reg_reg(modrm, &prefixes)?;
let (src, dst) = if byte == 0x01 { (reg, rm) } else { (rm, reg) };
let val1 = self.cpu.get(dst);
let val2 = self.cpu.get(src);
let (res, flags) = if rex_w {
let (res, flags) = if prefixes.rex_w {
add64(val1, val2)
} else {
let (r, f) = add32(val1 as u32, val2 as u32);
@@ -353,11 +532,11 @@ impl<'a> Interpreter<'a> {
// SUB r/m, reg (0x29) or SUB reg, r/m (0x2B)
0x29 | 0x2B => {
let modrm = self.fetch_u8()?;
let (reg, rm) = self.decode_modrm_reg_reg(modrm, rex_r, rex_b)?;
let (reg, rm) = self.decode_modrm_reg_reg(modrm, &prefixes)?;
let (src, dst) = if byte == 0x29 { (reg, rm) } else { (rm, reg) };
let val1 = self.cpu.get(dst);
let val2 = self.cpu.get(src);
let (res, flags) = if rex_w {
let (res, flags) = if prefixes.rex_w {
sub64(val1, val2)
} else {
let (r, f) = sub32(val1 as u32, val2 as u32);
@@ -371,13 +550,13 @@ impl<'a> Interpreter<'a> {
// CMP reg, r/m (0x3B) or CMP r/m, reg (0x39)
0x39 | 0x3B => {
let modrm = self.fetch_u8()?;
let (reg, rm) = self.decode_modrm_reg_reg(modrm, rex_r, rex_b)?;
let (reg, rm) = self.decode_modrm_reg_reg(modrm, &prefixes)?;
let (v1, v2) = if byte == 0x39 {
(self.cpu.get(rm), self.cpu.get(reg))
} else {
(self.cpu.get(reg), self.cpu.get(rm))
};
let (_, flags) = if rex_w {
let (_, flags) = if prefixes.rex_w {
sub64(v1, v2)
} else {
let (r, f) = sub32(v1 as u32, v2 as u32);
@@ -391,7 +570,7 @@ impl<'a> Interpreter<'a> {
0x83 => {
let modrm = self.fetch_u8()?;
let op = (modrm >> 3) & 7;
let (reg, rm) = self.decode_modrm_reg_reg(modrm, rex_r, rex_b)?;
let (reg, rm) = self.decode_modrm_reg_reg(modrm, &prefixes)?;
let imm8 = self.fetch_i8()? as i64;
let imm = imm8 as u64;
@@ -399,7 +578,7 @@ impl<'a> Interpreter<'a> {
match op {
0 => {
// ADD
let (res, flags) = if rex_w {
let (res, flags) = if prefixes.rex_w {
add64(val, imm)
} else {
let (r, f) = add32(val as u32, imm as u32);
@@ -410,7 +589,7 @@ impl<'a> Interpreter<'a> {
}
5 => {
// SUB
let (res, flags) = if rex_w {
let (res, flags) = if prefixes.rex_w {
sub64(val, imm)
} else {
let (r, f) = sub32(val as u32, imm as u32);
@@ -421,7 +600,7 @@ impl<'a> Interpreter<'a> {
}
7 => {
// CMP
let (_, flags) = if rex_w {
let (_, flags) = if prefixes.rex_w {
sub64(val, imm)
} else {
let (r, f) = sub32(val as u32, imm as u32);
@@ -438,7 +617,7 @@ impl<'a> Interpreter<'a> {
// MOV r/m, reg (0x89) or MOV reg, r/m (0x8B)
0x89 | 0x8B => {
let modrm = self.fetch_u8()?;
self.execute_mov_rm(modrm, rex_w, rex_r, rex_b, byte == 0x8B, seg_gs, seg_fs)
self.execute_mov_rm(modrm, &prefixes, byte == 0x8B)
}
// JMP rel8 (0xEB)
@@ -492,7 +671,7 @@ impl<'a> Interpreter<'a> {
// PUSH reg (0x50..=0x57)
0x50..=0x57 => {
let reg_idx = (byte - 0x50) + if rex_b { 8 } else { 0 };
let reg_idx = (byte - 0x50) + if prefixes.rex_b { 8 } else { 0 };
let reg = Register::from_index(reg_idx);
let val = self.cpu.get(reg);
self.push_u64(val)?;
@@ -501,7 +680,7 @@ impl<'a> Interpreter<'a> {
// POP reg (0x58..=0x5F)
0x58..=0x5F => {
let reg_idx = (byte - 0x58) + if rex_b { 8 } else { 0 };
let reg_idx = (byte - 0x58) + if prefixes.rex_b { 8 } else { 0 };
let reg = Register::from_index(reg_idx);
let val = self.pop_u64()?;
self.cpu.set(reg, val);
@@ -532,32 +711,26 @@ impl<'a> Interpreter<'a> {
fn decode_modrm_reg_reg(
&self,
modrm: u8,
rex_r: bool,
rex_b: bool,
prefixes: &Prefixes,
) -> Result<(Register, Register), ExitReason> {
let mode = (modrm >> 6) & 3;
if mode != 3 {
return Err(ExitReason::IllegalInstruction(modrm));
}
let reg_idx = ((modrm >> 3) & 7) + if rex_r { 8 } else { 0 };
let rm_idx = (modrm & 7) + if rex_b { 8 } else { 0 };
let reg_idx = ((modrm >> 3) & 7) + if prefixes.rex_r { 8 } else { 0 };
let rm_idx = (modrm & 7) + if prefixes.rex_b { 8 } else { 0 };
Ok((Register::from_index(reg_idx), Register::from_index(rm_idx)))
}
#[allow(clippy::too_many_arguments)]
fn execute_mov_rm(
&mut self,
modrm: u8,
rex_w: bool,
rex_r: bool,
rex_b: bool,
prefixes: &Prefixes,
is_load: bool,
seg_gs: bool,
seg_fs: bool,
) -> Result<Option<ExitReason>, ExitReason> {
let mode = (modrm >> 6) & 3;
let reg_idx = ((modrm >> 3) & 7) + if rex_r { 8 } else { 0 };
let rm_idx = (modrm & 7) + if rex_b { 8 } else { 0 };
let reg_idx = ((modrm >> 3) & 7) + if prefixes.rex_r { 8 } else { 0 };
let rm_idx = (modrm & 7) + if prefixes.rex_b { 8 } else { 0 };
let reg = Register::from_index(reg_idx);
if mode == 3 {
@@ -565,12 +738,24 @@ impl<'a> Interpreter<'a> {
let rm = Register::from_index(rm_idx);
if is_load {
let val = self.cpu.get(rm);
self.cpu
.set(reg, if rex_w { val } else { val as u32 as u64 });
self.cpu.set(
reg,
if prefixes.rex_w {
val
} else {
val as u32 as u64
},
);
} else {
let val = self.cpu.get(reg);
self.cpu
.set(rm, if rex_w { val } else { val as u32 as u64 });
self.cpu.set(
rm,
if prefixes.rex_w {
val
} else {
val as u32 as u64
},
);
}
return Ok(None);
}
@@ -580,8 +765,12 @@ impl<'a> Interpreter<'a> {
// SIB byte follows ModR/M
let sib = self.fetch_u8()?;
let scale_shift = (sib >> 6) & 3;
let index_raw = ((sib >> 3) & 7) + if rex_r { 8 } else { 0 }; // SIB.index can use REX.X; here index_raw
let base_raw = (sib & 7) + if rex_b { 8 } else { 0 };
// REX.X extends the SIB index field; REX.R extends the ModRM reg
// field and must not affect the index. An index field of 100b
// selects r12 when REX.X is set, and means "no index" otherwise.
let index_field = (sib >> 3) & 7;
let index_raw = index_field + if prefixes.rex_x { 8 } else { 0 };
let base_raw = (sib & 7) + if prefixes.rex_b { 8 } else { 0 };
let base_v = if mode == 0 && (sib & 7) == 5 {
// disp32 with no base register
@@ -590,7 +779,7 @@ impl<'a> Interpreter<'a> {
self.cpu.get(Register::from_index(base_raw))
};
let index_v = if (sib >> 3) & 7 == 4 {
let index_v = if index_field == 4 && !prefixes.rex_x {
// index == 4 means no index register (ESP/RSP)
0u64
} else {
@@ -637,15 +826,15 @@ impl<'a> Interpreter<'a> {
(base_val as i64 + disp) as u64
};
if seg_gs {
if prefixes.seg_gs {
effective_addr = effective_addr.wrapping_add(self.cpu.gs_base);
} else if seg_fs {
} else if prefixes.seg_fs {
effective_addr = effective_addr.wrapping_add(self.cpu.fs_base);
}
if is_load {
// Load from memory to reg
if rex_w {
if prefixes.rex_w {
let val = self
.memory
.read_u64(effective_addr)
@@ -661,7 +850,7 @@ impl<'a> Interpreter<'a> {
} else {
// Store from reg to memory
let val = self.cpu.get(reg);
if rex_w {
if prefixes.rex_w {
self.memory
.write_u64(effective_addr, val)
.map_err(ExitReason::MemoryFault)?;
+14
View File
@@ -94,6 +94,9 @@ pub const PE32_PLUS_MAGIC: u16 = 0x020B;
/// PE32+ optional header length up to and including NumberOfRvaAndSizes.
const PE32_PLUS_MIN_OPTIONAL_HEADER: usize = 112;
const SECTION_HEADER_SIZE: usize = 40;
/// Host memory budget for all mapped sections of one image. This is a loader policy
/// limit, not a property of the PE format.
const MAX_MAPPED_IMAGE_BYTES: u64 = 256 * 1024 * 1024;
fn read_u16(bytes: &[u8], at: usize) -> u16 {
u16::from_le_bytes([bytes[at], bytes[at + 1]])
@@ -273,6 +276,17 @@ impl ParsedPe {
}
pub(crate) fn load_at_base(&self, bytes: &[u8], base: u64) -> Result<LoadedImage, PeError> {
// Each section becomes a zero-filled host allocation, so bound the total before
// allocating anything. Sections may not overlap, so the sum is the mapped size.
let mapped: u64 = self
.sections
.iter()
.map(|sec| u64::from(sec.virtual_size.max(sec.raw_data_size)))
.sum();
if mapped > MAX_MAPPED_IMAGE_BYTES {
return Err(PeError::SectionMappingError(MemoryError::AllocationFailed));
}
let mut memory = GuestMemory::new();
for sec in &self.sections {
+174 -1
View File
@@ -3,7 +3,7 @@
//! End-to-end integration tests for Xenora X12: PE32+ loading & x86-64 execution bootstrap.
use xenora_loader::cpu::{CpuState, ExitReason, Interpreter, Register};
use xenora_loader::memory::{MemoryError, MemoryPermissions};
use xenora_loader::memory::{GuestMemory, MemoryError, MemoryPermissions};
use xenora_loader::pe::{
IMAGE_FILE_MACHINE_AMD64, IMAGE_SCN_MEM_EXECUTE, IMAGE_SCN_MEM_READ, PE32_PLUS_MAGIC, ParsedPe,
};
@@ -289,3 +289,176 @@ fn test_sib_addressing_mode() {
assert_eq!(result.exit_reason, ExitReason::Halt);
assert_eq!(result.final_state.get(Register::Rdx), 0x12345678_9abcdef0);
}
/// Base address of the read-write data region used by the SIB tests.
const DATA_BASE: u64 = 0x6000_0000;
/// Base address of the read-write stack region used by the SIB tests.
const STACK_BASE: u64 = 0x5000_0000;
/// Run `code` on the interpreter with a writable stack and a writable data
/// region, and return the final state, the exit reason and the guest memory.
///
/// `DATA_BASE` is mapped read-write so a test can observe where a store
/// landed. `STACK_BASE` holds the stack pointer.
fn run_with_regions(code: &[u8]) -> (CpuState, ExitReason, GuestMemory) {
let pe_bytes = build_synthetic_pe32_plus(code);
let parsed = ParsedPe::parse(&pe_bytes).expect("parse");
let mut loaded = parsed.load_into_memory(&pe_bytes).expect("load");
loaded
.memory
.map_region(STACK_BASE, 0x10000, MemoryPermissions::READ_WRITE)
.expect("stack mapping should succeed");
loaded
.memory
.map_region(DATA_BASE, 0x10000, MemoryPermissions::READ_WRITE)
.expect("data mapping should succeed");
let cpu = CpuState::new(loaded.entry_point, STACK_BASE + 0x8000);
let mut interp = Interpreter::new(cpu, &mut loaded.memory, 100);
let result = interp.run();
(result.final_state, result.exit_reason, loaded.memory)
}
/// `mov rax, DATA_BASE` (48 B8 <imm64>).
fn mov_rax_data_base() -> Vec<u8> {
let mut code = vec![0x48, 0xB8];
code.extend_from_slice(&DATA_BASE.to_le_bytes());
code
}
/// `mov rbx, 0x12345678_9abcdef0` (48 BB <imm64>).
fn mov_rbx_value() -> Vec<u8> {
let mut code = vec![0x48, 0xBB];
code.extend_from_slice(&0x1234_5678_9abc_def0u64.to_le_bytes());
code
}
/// A SIB index register is extended by REX.X, not by REX.R.
///
/// The encoding 4A 89 1C E0 is `mov [rax + r12*8], rbx`. Its REX prefix sets
/// REX.X, so the SIB index field 100b selects r12 and the store lands at
/// `rax + r12*8`. REX.R is clear in this prefix, so the ModRM `reg` field is
/// rbx.
#[test]
fn test_rex_x_extends_the_sib_index_register() {
// mov rax, DATA_BASE (48 b8 <imm64>)
// mov r12, 4 (41 bc 04 00 00 00)
// mov rbx, 0x12345678_9abcdef0 (48 bb <imm64>)
// mov [rax + r12*8], rbx (4a 89 1c e0)
// hlt (f4)
let mut code = mov_rax_data_base();
code.extend_from_slice(&[0x41, 0xBC, 0x04, 0x00, 0x00, 0x00]); // mov r12d, 4
code.extend_from_slice(&mov_rbx_value());
code.extend_from_slice(&[0x4A, 0x89, 0x1C, 0xE0]); // mov [rax + r12*8], rbx
code.push(0xF4); // hlt
let (_state, reason, memory) = run_with_regions(&code);
assert_eq!(reason, ExitReason::Halt);
// r12 holds 4, so the store lands at DATA_BASE + 4*8.
assert_eq!(
memory.read_u64(DATA_BASE + 32).expect("indexed slot"),
0x1234_5678_9abc_def0
);
// The unindexed slot at DATA_BASE must be untouched.
assert_eq!(memory.read_u64(DATA_BASE).expect("base slot"), 0);
}
/// REX.R and REX.X extend independent fields in the same instruction.
///
/// The encoding 4C 89 1C C8 is `mov [rax + rcx*8], r11`. Its REX prefix sets
/// REX.R, so the ModRM `reg` field 011 selects r11. It does not set REX.X, so
/// the SIB index field 001 selects rcx and must not be extended to r9.
#[test]
fn test_rex_r_does_not_extend_the_sib_index_register() {
// mov rax, DATA_BASE (48 b8 <imm64>)
// mov r11, 0x11223344_55667788 (49 bb <imm64>)
// mov ecx, 4 (b9 04 00 00 00)
// mov r9, 8 (41 b9 08 00 00 00)
// mov [rax + rcx*8], r11 (4c 89 1c c8)
// hlt (f4)
let mut code = mov_rax_data_base();
let mut r11 = vec![0x49, 0xBB];
r11.extend_from_slice(&0x1122_3344_5566_7788u64.to_le_bytes());
code.extend_from_slice(&r11);
code.extend_from_slice(&[0xB9, 0x04, 0x00, 0x00, 0x00]); // mov ecx, 4
code.extend_from_slice(&[0x41, 0xB9, 0x08, 0x00, 0x00, 0x00]); // mov r9d, 8
code.extend_from_slice(&[0x4C, 0x89, 0x1C, 0xC8]); // mov [rax + rcx*8], r11
code.push(0xF4); // hlt
let (_state, reason, memory) = run_with_regions(&code);
assert_eq!(reason, ExitReason::Halt);
// rcx holds 4, so the store lands at DATA_BASE + 4*8. A wrongly extended
// index would have selected r9 and landed at DATA_BASE + 8*8.
assert_eq!(
memory.read_u64(DATA_BASE + 32).expect("indexed slot"),
0x1122_3344_5566_7788
);
assert_eq!(memory.read_u64(DATA_BASE + 64).expect("r9 slot"), 0);
}
/// REX.R and REX.X set together extend their own fields independently.
///
/// The encoding 4E 89 1C E0 is `mov [rax + r12*8], r11`. Its REX prefix sets
/// both REX.R and REX.X: the ModRM `reg` field 011 becomes r11 and the SIB
/// index field 100b becomes r12.
#[test]
fn test_rex_r_and_rex_x_set_together_extend_independent_fields() {
// mov rax, DATA_BASE (48 b8 <imm64>)
// mov r11, 0x11223344_55667788 (49 bb <imm64>)
// mov r12, 4 (41 bc 04 00 00 00)
// mov [rax + r12*8], r11 (4e 89 1c e0)
// hlt (f4)
let mut code = mov_rax_data_base();
let mut r11 = vec![0x49, 0xBB];
r11.extend_from_slice(&0x1122_3344_5566_7788u64.to_le_bytes());
code.extend_from_slice(&r11);
code.extend_from_slice(&[0x41, 0xBC, 0x04, 0x00, 0x00, 0x00]); // mov r12d, 4
code.extend_from_slice(&[0x4E, 0x89, 0x1C, 0xE0]); // mov [rax + r12*8], r11
code.push(0xF4); // hlt
let (_state, reason, memory) = run_with_regions(&code);
assert_eq!(reason, ExitReason::Halt);
assert_eq!(
memory.read_u64(DATA_BASE + 32).expect("indexed slot"),
0x1122_3344_5566_7788
);
assert_eq!(memory.read_u64(DATA_BASE).expect("base slot"), 0);
}
/// Without REX.X, a SIB index field of 100b means "no index register" and the
/// address is the base alone.
///
/// The encoding 48 89 1C 24 is `mov [rsp], rbx`: the SIB index field is 100b
/// and REX.X is clear, so no index register contributes to the address.
#[test]
fn test_sib_index_field_100b_without_rex_x_means_no_index() {
// mov rbx, 0x12345678_9abcdef0 (48 bb <imm64>)
// mov r12, 0x1000 (41 bc 00 10 00 00)
// mov [rsp], rbx (48 89 1c 24)
// hlt (f4)
let mut code = mov_rbx_value();
code.extend_from_slice(&[0x41, 0xBC, 0x00, 0x10, 0x00, 0x00]); // mov r12d, 0x1000
code.extend_from_slice(&[0x48, 0x89, 0x1C, 0x24]); // mov [rsp], rbx
code.push(0xF4); // hlt
let pe_bytes = build_synthetic_pe32_plus(&code);
let parsed = ParsedPe::parse(&pe_bytes).expect("parse");
let mut loaded = parsed.load_into_memory(&pe_bytes).expect("load");
loaded
.memory
.map_region(STACK_BASE, 0x10000, MemoryPermissions::READ_WRITE)
.expect("stack mapping should succeed");
let cpu = CpuState::new(loaded.entry_point, STACK_BASE + 0x8000);
let mut interp = Interpreter::new(cpu, &mut loaded.memory, 100);
let result = interp.run();
assert_eq!(result.exit_reason, ExitReason::Halt);
// The index is absent, so the address is the base (rsp) alone.
let stack_top = STACK_BASE + 0x8000;
assert_eq!(
loaded.memory.read_u64(stack_top).expect("base slot"),
0x1234_5678_9abc_def0
);
}
+96
View File
@@ -0,0 +1,96 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! PE image mapping budget tests (#80).
//!
//! A section's mapped size is max(VirtualSize, SizeOfRawData) and the loader
//! backs it with zero-filled host memory, so a small file can request a large
//! allocation. The loader's documented budget is 256 MiB per image.
use xenora_loader::{MemoryError, ParsedPe, PeError};
const BUDGET: u32 = 256 * 1024 * 1024;
/// An original synthetic image: one 0x200-byte code section at RVA 0x1000 followed by
/// uninitialized sections (no raw data) of the given virtual sizes, packed back to back.
fn build(bss_sizes: &[u32]) -> Vec<u8> {
let mut pe = vec![0u8; 0x400];
pe[0..2].copy_from_slice(b"MZ");
pe[0x3C..0x40].copy_from_slice(&0x40u32.to_le_bytes());
pe[0x40..0x44].copy_from_slice(b"PE\0\0");
let coff = 0x44;
pe[coff..coff + 2].copy_from_slice(&0x8664u16.to_le_bytes());
pe[coff + 2..coff + 4].copy_from_slice(&(1 + bss_sizes.len() as u16).to_le_bytes());
pe[coff + 16..coff + 18].copy_from_slice(&112u16.to_le_bytes());
let opt = coff + 20;
pe[opt..opt + 2].copy_from_slice(&0x020Bu16.to_le_bytes());
pe[opt + 16..opt + 20].copy_from_slice(&0x1000u32.to_le_bytes());
pe[opt + 24..opt + 32].copy_from_slice(&0x1_4000_0000u64.to_le_bytes());
let mut section = |i: usize, va: u32, vsize: u32, raw: u32, flags: u32| {
let h = opt + 112 + i * 40;
pe[h + 8..h + 12].copy_from_slice(&vsize.to_le_bytes());
pe[h + 12..h + 16].copy_from_slice(&va.to_le_bytes());
pe[h + 16..h + 20].copy_from_slice(&(if raw == 0 { 0 } else { 0x200u32 }).to_le_bytes());
pe[h + 20..h + 24].copy_from_slice(&raw.to_le_bytes());
pe[h + 36..h + 40].copy_from_slice(&flags.to_le_bytes());
};
section(0, 0x1000, 0x200, 0x200, 0x6000_0020);
let mut va = 0x2000u32;
for (i, &size) in bss_sizes.iter().enumerate() {
section(i + 1, va, size, 0, 0xC000_0080);
va += size;
}
pe
}
fn over_budget() -> PeError {
PeError::SectionMappingError(MemoryError::AllocationFailed)
}
#[test]
fn small_image_loads() {
let bytes = build(&[0x1000]);
let pe = ParsedPe::parse(&bytes).unwrap();
assert!(pe.load_into_memory(&bytes).is_ok());
}
#[test]
fn image_exactly_at_budget_loads() {
let bytes = build(&[BUDGET - 0x200]);
let pe = ParsedPe::parse(&bytes).unwrap();
assert!(pe.load_into_memory(&bytes).is_ok());
}
#[test]
fn one_byte_over_budget_is_rejected() {
let bytes = build(&[BUDGET - 0x1FF]);
let pe = ParsedPe::parse(&bytes).unwrap();
assert_eq!(pe.load_into_memory(&bytes).err(), Some(over_budget()));
}
#[test]
fn budget_counts_all_sections_together() {
// Three 128 MiB sections: each fits alone, the total (384 MiB) does not.
let bytes = build(&[128 << 20; 3]);
let pe = ParsedPe::parse(&bytes).unwrap();
assert_eq!(pe.load_into_memory(&bytes).err(), Some(over_budget()));
}
#[test]
fn near_4_gib_request_from_a_1_kib_file_is_rejected_before_allocation() {
let bytes = build(&[0xF000_0000]);
assert_eq!(bytes.len(), 0x400);
let pe = ParsedPe::parse(&bytes).expect("headers are valid; only the size is excessive");
assert_eq!(pe.load_into_memory(&bytes).err(), Some(over_budget()));
}
#[test]
fn repository_fixture_is_within_budget() {
let path = concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../fixtures/pe/trusted-runner.exe"
);
let bytes = std::fs::read(path).unwrap();
let pe = ParsedPe::parse(&bytes).unwrap();
assert!(pe.load_into_memory(&bytes).is_ok());
}
+290 -23
View File
@@ -51,13 +51,19 @@ pub enum Op {
Move(u8, Source),
Add(u8, u8, u8),
ScalarMove(u8, Source),
/// SOP1 unary operation writing an SGPR (s0-s105), and SCC for some.
ScalarUnary(ScalarUnary, u8, Source),
/// VOP1 move of a normal SGPR or `vcc_lo` (106) into a VGPR.
MoveScalar(u8, u8),
/// VOPC 32-bit integer compare writing the Wave32 mask to `vcc_lo`.
Compare(Comparison, CompareSource, u8),
/// SOP2 operation writing an SGPR and SCC.
Scalar(ScalarAlu, u8, Source, Source),
/// SOPC `s_cmp_eq_{i32,u32}` (opcodes 0 and 6, identical per guide 12.4).
CompareEqual(Source, Source),
/// The other SOPC 32-bit integer compares (opcodes 1-5 and 7-11), writing
/// only SCC: LG, GT, GE, LT, LE, signed for 1-5, unsigned for 7-11.
ScalarCompare(Comparison, Source, Source),
Branch {
target: usize,
condition: BranchCondition,
@@ -129,7 +135,7 @@ pub enum BranchCondition {
///
/// AMD RDNA 2 XML descriptions: additions store the carry-out in SCC,
/// subtractions the borrow; ADDC/SUBB add or subtract SCC; bitwise
/// operations set SCC iff the result is nonzero.
/// operations and shifts set SCC iff the result is nonzero.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ScalarAlu {
Add,
@@ -142,6 +148,79 @@ pub enum ScalarAlu {
And,
Or,
Xor,
/// RDNA 2 ISA guide 12.1: D = S0 & ~S1, SCC = (D != 0).
AndNot,
/// D = S0 | ~S1, SCC = (D != 0).
OrNot,
/// D = ~(S0 & S1), SCC = (D != 0).
Nand,
/// D = ~(S0 | S1), SCC = (D != 0).
Nor,
/// D = ~(S0 ^ S1), SCC = (D != 0).
Xnor,
/// D = S0 << S1[4:0], SCC = (D != 0).
ShiftLeft,
/// D = S0 >> S1[4:0] (logical), SCC = (D != 0).
ShiftRight,
/// D = signext(S0) >> S1[4:0], SCC = (D != 0).
ArithmeticShiftRight,
/// Guide 12.1: D = (S0 < S1) ? S0 : S1, SCC = (S0 < S1); signed or not.
Minimum {
signed: bool,
},
/// D = (S0 > S1) ? S0 : S1, SCC = (S0 > S1).
Maximum {
signed: bool,
},
/// D = SCC ? S0 : S1; reads SCC and leaves it unchanged.
Select,
/// D = ((1 << S0[4:0]) - 1) << S1[4:0]; SCC unchanged.
BitfieldMask,
/// D = low 32 bits of S0 * S1; SCC unchanged.
Multiply,
/// D = (S0 >> S1[4:0]) & ((1 << S1[22:16]) - 1), sign-extended from the
/// field's top bit when signed (S0 then shifts arithmetically);
/// SCC = (D != 0).
BitfieldExtract {
signed: bool,
},
/// D = |S0 - S1| with the 32-bit difference (0x80000000 stays),
/// SCC = (D != 0).
AbsoluteDifference,
/// D = (S0 << N) + S1, SCC = ((S0 << N) + S1 >= 2^32) with N = 1..4.
ShiftLeftAdd(u8),
/// D = high 32 bits of S0 * S1; SCC unchanged.
MultiplyHigh {
signed: bool,
},
}
/// SOP1 unary operations decoded by the reference interpreter (RDNA 2 ISA
/// guide 12.3; SCC per Tables 12 and 14).
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ScalarUnary {
/// D = ~S0, SCC = (D != 0).
Not,
/// D[31:0] = S0[0:31].
ReverseBits,
/// D = number of zero bits, SCC = (D != 0).
CountZeros,
/// D = number of one bits, SCC = (D != 0).
CountOnes,
/// D = index of the lowest zero bit, or -1.
FindFirstZero,
/// D = index of the lowest one bit, or -1.
FindFirstOne,
/// D = number of zeros above the highest one bit, or -1 for 0.
FindLastBit,
/// D = number of leading bits equal to the sign bit, or -1 for 0 and -1.
FindLastSignBit,
/// D = signext(S0[7:0]).
SignExtendByte,
/// D = signext(S0[15:0]).
SignExtendShort,
/// D = |S0| (0x80000000 stays), SCC = (D != 0).
Absolute,
}
/// VOP2 operations decoded by the reference interpreter.
@@ -277,32 +356,90 @@ pub fn decode(code: &[u8]) -> Result<Vec<DecodedInstruction>, ReferenceError> {
let (source, length) = decode_scalar(*source, tail, offset)?;
(Op::ScalarMove(destination & 0x7f, source), length)
}
[left, right, 6, 0xbf, tail @ ..] if (*left, *right) != (255, 255) => {
// SOP1: ENCODING 0b10_1111101 in bits 23-31, SDST in 16-22 (s0-s105
// only), OP in 8-15.
[
source,
op @ (7 | 11 | 13 | 15 | 17 | 19 | 21 | 23 | 25 | 26 | 52),
destination @ 0x80..=0xe9,
0xbe,
tail @ ..,
] => {
let kind = match op {
7 => ScalarUnary::Not,
11 => ScalarUnary::ReverseBits,
13 => ScalarUnary::CountZeros,
15 => ScalarUnary::CountOnes,
17 => ScalarUnary::FindFirstZero,
19 => ScalarUnary::FindFirstOne,
21 => ScalarUnary::FindLastBit,
23 => ScalarUnary::FindLastSignBit,
25 => ScalarUnary::SignExtendByte,
26 => ScalarUnary::SignExtendShort,
_ => ScalarUnary::Absolute,
};
let (source, length) = decode_scalar(*source, tail, offset)?;
(Op::ScalarUnary(kind, destination & 0x7f, source), length)
}
// SOPC: ENCODING 0b10_1111110 in bits 23-31, OP in 16-22 (guide
// 13.1.4); 0-5 signed and 6-11 unsigned EQ, LG, GT, GE, LT, LE.
[left, right, op @ 0..=11, 0xbf, tail @ ..] if (*left, *right) != (255, 255) => {
let (left, left_length) = decode_scalar(*left, tail, offset)?;
let (right, right_length) = decode_scalar(*right, tail, offset)?;
(Op::CompareEqual(left, right), left_length.max(right_length))
// VOPC relation offsets: LT 1, EQ 2, LE 3, GT 4, NE 5, GE 6.
let relation = [2, 5, 4, 6, 1, 3][usize::from(op % 6)];
let comparison = Comparison {
offset: relation,
signed: *op < 6,
};
let op = if relation == 2 {
Op::CompareEqual(left, right)
} else {
Op::ScalarCompare(comparison, left, right)
};
(op, left_length.max(right_length))
}
// SOP2: OP in bits 23-29, SDST in bits 16-22, SSRC1, SSRC0.
[
left,
right,
low,
high @ (0x80..=0x82 | 0x87 | 0x88 | 0x89),
tail @ ..,
] if (*left, *right) != (255, 255)
&& low & 0x7f <= 105
&& (low & 0x80 == 0 || matches!(high, 0x80..=0x82)) =>
[left, right, low, high @ 0x80..=0xbf, tail @ ..]
if (*left, *right) != (255, 255)
&& low & 0x7f <= 105
&& matches!(
(high & 0x3f) << 1 | low >> 7,
0..=10 | 14 | 16 | 18 | 20 | 22 | 24 | 26 | 28 | 30 | 32 | 34
| 36 | 38..=40 | 44 | 46..=49 | 53 | 54
) =>
{
let kind = match (high, low >> 7) {
(0x80, 0) => ScalarAlu::Add,
(0x80, _) => ScalarAlu::Subtract,
(0x81, 0) => ScalarAlu::AddSigned,
(0x81, _) => ScalarAlu::SubtractSigned,
(0x82, 0) => ScalarAlu::AddWithCarry,
(0x82, _) => ScalarAlu::SubtractWithBorrow,
(0x87, _) => ScalarAlu::And,
(0x88, _) => ScalarAlu::Or,
_ => ScalarAlu::Xor,
let kind = match (high & 0x3f) << 1 | low >> 7 {
0 => ScalarAlu::Add,
1 => ScalarAlu::Subtract,
2 => ScalarAlu::AddSigned,
3 => ScalarAlu::SubtractSigned,
4 => ScalarAlu::AddWithCarry,
5 => ScalarAlu::SubtractWithBorrow,
6 => ScalarAlu::Minimum { signed: true },
7 => ScalarAlu::Minimum { signed: false },
8 => ScalarAlu::Maximum { signed: true },
9 => ScalarAlu::Maximum { signed: false },
10 => ScalarAlu::Select,
14 => ScalarAlu::And,
16 => ScalarAlu::Or,
18 => ScalarAlu::Xor,
20 => ScalarAlu::AndNot,
22 => ScalarAlu::OrNot,
24 => ScalarAlu::Nand,
26 => ScalarAlu::Nor,
28 => ScalarAlu::Xnor,
30 => ScalarAlu::ShiftLeft,
32 => ScalarAlu::ShiftRight,
34 => ScalarAlu::ArithmeticShiftRight,
36 => ScalarAlu::BitfieldMask,
38 => ScalarAlu::Multiply,
39 => ScalarAlu::BitfieldExtract { signed: false },
40 => ScalarAlu::BitfieldExtract { signed: true },
44 => ScalarAlu::AbsoluteDifference,
op @ 46..=49 => ScalarAlu::ShiftLeftAdd(op - 45),
53 => ScalarAlu::MultiplyHigh { signed: false },
_ => ScalarAlu::MultiplyHigh { signed: true },
};
let (left, left_length) = decode_scalar(*left, tail, offset)?;
let (right, right_length) = decode_scalar(*right, tail, offset)?;
@@ -652,9 +789,51 @@ fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result<Vec<u32
}
scalars[usize::from(dst)] = Some(value);
}
Op::ScalarUnary(kind, dst, src) => {
if dst < 8 {
return Err(error(offset, "write to a reserved resource SGPR"));
}
let value = read_scalar(src)?;
// -1 (all ones) when no bit is found.
let found = |index: u32| if index == 32 { u32::MAX } else { index };
let result = match kind {
ScalarUnary::Not => !value,
ScalarUnary::ReverseBits => value.reverse_bits(),
ScalarUnary::CountZeros => value.count_zeros(),
ScalarUnary::CountOnes => value.count_ones(),
ScalarUnary::FindFirstZero => found(value.trailing_ones()),
ScalarUnary::FindFirstOne => found(value.trailing_zeros()),
ScalarUnary::FindLastBit => found(value.leading_zeros()),
ScalarUnary::FindLastSignBit => {
let same = if value >> 31 == 1 {
value.leading_ones()
} else {
value.leading_zeros()
};
found(same)
}
ScalarUnary::SignExtendByte => value as u8 as i8 as i32 as u32,
ScalarUnary::SignExtendShort => value as u16 as i16 as i32 as u32,
ScalarUnary::Absolute => (value as i32).wrapping_abs() as u32,
};
scalars[usize::from(dst)] = Some(result);
if matches!(
kind,
ScalarUnary::Not
| ScalarUnary::CountZeros
| ScalarUnary::CountOnes
| ScalarUnary::Absolute
) {
scc = Some(result != 0);
}
}
Op::CompareEqual(lhs, rhs) => {
scc = Some(read_scalar(lhs)? == read_scalar(rhs)?);
}
// Guide 12.4: SCC = (S0 <relation> S1); no SGPR is written.
Op::ScalarCompare(comparison, lhs, rhs) => {
scc = Some(comparison.holds(read_scalar(lhs)?, read_scalar(rhs)?));
}
Op::Scalar(kind, dst, lhs, rhs) => {
if dst < 8 {
return Err(error(offset, "write to a reserved resource SGPR"));
@@ -664,8 +843,13 @@ fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result<Vec<u32
ScalarAlu::AddWithCarry | ScalarAlu::SubtractWithBorrow => i64::from(
scc.ok_or_else(|| error(offset, "carry-in from uninitialized SCC"))?,
),
ScalarAlu::Select => {
i64::from(scc.ok_or_else(|| error(offset, "select on uninitialized SCC"))?)
}
_ => 0,
};
let (signed_lhs, signed_rhs) =
(i64::from(lhs as u32 as i32), i64::from(rhs as u32 as i32));
// Exact integer arithmetic, then reduction modulo 2^32.
let (exact, flag) = match kind {
ScalarAlu::Add | ScalarAlu::AddWithCarry => {
@@ -694,10 +878,93 @@ fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result<Vec<u32
};
(bits, bits != 0)
}
// Guide 12.1: strict comparisons, so equal operands give
// S1 (the same value) and SCC = 0.
ScalarAlu::Minimum { signed } | ScalarAlu::Maximum { signed } => {
let (a, b) = if signed {
(signed_lhs, signed_rhs)
} else {
(lhs, rhs)
};
let first = if matches!(kind, ScalarAlu::Minimum { .. }) {
a < b
} else {
a > b
};
(if first { lhs } else { rhs }, first)
}
// The SCC-less forms; `flag` is unused for them below.
ScalarAlu::Select => (if carry == 1 { lhs } else { rhs }, false),
ScalarAlu::BitfieldMask => (((1 << (lhs & 0x1f)) - 1) << (rhs & 0x1f), false),
ScalarAlu::Multiply => (signed_lhs * signed_rhs, false),
ScalarAlu::MultiplyHigh { signed } => {
// The unsigned product fits only in u64.
let high = if signed {
(signed_lhs * signed_rhs) >> 32
} else {
((lhs as u64 * rhs as u64) >> 32) as i64
};
(high, false)
}
// Offset S1[4:0], width S1[22:16] (0-127). A width of 32 or
// more keeps every bit of the shifted word.
ScalarAlu::BitfieldExtract { signed } => {
let (shift, width) = (rhs & 0x1f, (rhs >> 16) & 0x7f);
let data = if signed { signed_lhs } else { lhs };
let shifted = data >> shift;
let value = if width == 0 {
0
} else if width >= 32 {
shifted
} else {
let field = shifted & ((1 << width) - 1);
if signed && field >> (width - 1) == 1 {
field - (1 << width)
} else {
field
}
};
(value, value.rem_euclid(1 << 32) != 0)
}
// The 32-bit difference first (guide examples), then |D|.
ScalarAlu::AbsoluteDifference => {
let difference = (signed_lhs - signed_rhs) as u32 as i32;
let value = difference.unsigned_abs();
(i64::from(value), value != 0)
}
// The carry out of the exact (S0 << N) + S1.
ScalarAlu::ShiftLeftAdd(n) => {
let sum = (lhs << n) + rhs;
(sum, sum >= 1 << 32)
}
// Guide 12.1: shifts use only S1[4:0]; all set SCC = (D != 0).
_ => {
let (a, b) = (lhs as u32, rhs as u32);
let bits = match kind {
ScalarAlu::AndNot => a & !b,
ScalarAlu::OrNot => a | !b,
ScalarAlu::Nand => !(a & b),
ScalarAlu::Nor => !(a | b),
ScalarAlu::Xnor => !(a ^ b),
ScalarAlu::ShiftLeft => a << (b & 0x1f),
ScalarAlu::ShiftRight => a >> (b & 0x1f),
_ => ((a as i32) >> (b & 0x1f)) as u32,
};
(i64::from(bits), bits != 0)
}
};
let value = exact.rem_euclid(1 << 32) as u32;
scalars[usize::from(dst)] = Some(value);
scc = Some(flag);
// Guide 12.1 and Tables 11, 12, 14: these forms leave SCC unchanged.
if !matches!(
kind,
ScalarAlu::Select
| ScalarAlu::BitfieldMask
| ScalarAlu::Multiply
| ScalarAlu::MultiplyHigh { .. }
) {
scc = Some(flag);
}
}
// RDNA 2 ISA section 3.9: VCC[n] = EXEC[n] & test(n), fully written.
Op::Compare(comparison, src0, src1) => {
+23 -6
View File
@@ -809,6 +809,21 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
*slot = Some(value);
continue;
}
Instruction::ScalarUnary { op, dst, src } => {
let src = read_scalar(src)?;
if dst < 8 {
return Err(error("scalar unary would modify a resource descriptor"));
}
let (value, flag) = op.evaluate(src);
let slot = scalars
.get_mut(usize::from(dst))
.ok_or_else(|| error("scalar destination exceeds the fixture register file"))?;
*slot = Some(value);
if let Some(flag) = flag {
scc = Some(flag);
}
continue;
}
Instruction::ScalarAlu {
op,
dst,
@@ -816,24 +831,26 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
src1,
} => {
let (src0, src1) = (read_scalar(src0)?, read_scalar(src1)?);
let carry_in = if op.reads_scc() {
scc.ok_or_else(|| error("carry-in or borrow-in reads uninitialized SCC"))?
let scc_in = if op.reads_scc() {
scc.ok_or_else(|| error("SOP2 SCC input reads uninitialized SCC"))?
} else {
false
};
if dst < 8 {
return Err(error("scalar ALU would modify a resource descriptor"));
}
let (value, flag) = op.evaluate(src0, src1, carry_in);
let (value, flag) = op.evaluate(src0, src1, scc_in);
let slot = scalars
.get_mut(usize::from(dst))
.ok_or_else(|| error("scalar destination exceeds the fixture register file"))?;
*slot = Some(value);
scc = Some(flag);
if let Some(flag) = flag {
scc = Some(flag);
}
continue;
}
Instruction::ScalarCompareEqU32 { src0, src1 } => {
scc = Some(read_scalar(src0)? == read_scalar(src1)?);
Instruction::ScalarCompare { op, src0, src1 } => {
scc = Some(op.test(read_scalar(src0)?, read_scalar(src1)?));
continue;
}
// docs/shaders/vector-compare.md sections 3 and 5.
+56
View File
@@ -280,6 +280,62 @@ fn scalar_alu_results_reach_the_kernel_as_constants() {
);
}
#[test]
fn scalar_logic_results_reach_the_kernel_as_constants() {
let code = include_bytes!("../../../fixtures/rdna2/scalar-logic.bin");
let compiled = compile(Architecture::Gfx1030, code).unwrap();
assert_eq!(
compiled.ir,
include_str!("../../../fixtures/golden/scalar-logic.ir")
);
assert_eq!(
compiled.msl,
include_str!("../../../fixtures/golden/scalar-logic.metal")
);
}
#[test]
fn scalar_compare_results_resolve_every_branch() {
let code = include_bytes!("../../../fixtures/rdna2/scalar-compare.bin");
let compiled = compile(Architecture::Gfx1030, code).unwrap();
assert_eq!(
compiled.ir,
include_str!("../../../fixtures/golden/scalar-compare.ir")
);
assert_eq!(
compiled.msl,
include_str!("../../../fixtures/golden/scalar-compare.metal")
);
}
#[test]
fn scalar_unary_results_reach_the_kernel_as_constants() {
let code = include_bytes!("../../../fixtures/rdna2/scalar-unary.bin");
let compiled = compile(Architecture::Gfx1030, code).unwrap();
assert_eq!(
compiled.ir,
include_str!("../../../fixtures/golden/scalar-unary.ir")
);
assert_eq!(
compiled.msl,
include_str!("../../../fixtures/golden/scalar-unary.metal")
);
}
#[test]
fn scalar_arith_results_reach_the_kernel_as_constants() {
let code = include_bytes!("../../../fixtures/rdna2/scalar-arith.bin");
let compiled = compile(Architecture::Gfx1030, code).unwrap();
assert_eq!(
compiled.ir,
include_str!("../../../fixtures/golden/scalar-arith.ir")
);
assert_eq!(
compiled.msl,
include_str!("../../../fixtures/golden/scalar-arith.metal")
);
}
#[test]
fn vector_compares_lower_to_per_thread_wave_masks_and_selects() {
let code = include_bytes!("../../../fixtures/rdna2/vector-compare.bin");
+4 -4
View File
@@ -1,17 +1,17 @@
<svg xmlns="http://www.w3.org/2000/svg" width="530" height="185" viewBox="0 0 530 185" role="img" aria-labelledby="title description">
<title id="title">Xenora · recorded progress</title>
<desc id="description">Decoded gfx1030 forms: 42 of 42. Accepted Metal forms · Apple M5: 18 of 42. Accepted guest milestones · X1–X4: 4 of 4</desc>
<desc id="description">Decoded gfx1030 forms: 88 of 88. Accepted Metal forms · Apple M5: 18 of 88. Accepted guest milestones · X1–X4: 4 of 4</desc>
<rect x="1" y="1" width="528" height="183" rx="10" fill="#18212a" stroke="#516171"/>
<g font-family="system-ui,sans-serif" fill="#eaf0f5">
<text x="20" y="29" font-size="13" font-weight="700">RECORDED FIXTURE PROGRESS</text>
<text x="20" y="58" font-size="13">Decoded gfx1030 forms</text>
<text x="510" y="58" font-size="13" text-anchor="end">42 / 42</text>
<text x="510" y="58" font-size="13" text-anchor="end">88 / 88</text>
<rect x="20" y="65" width="490" height="4" rx="2" fill="#3c4a58"/>
<rect x="20" y="65" width="490.00" height="4" rx="2" fill="#88c6bd"/>
<text x="20" y="96" font-size="13">Accepted Metal forms · Apple M5</text>
<text x="510" y="96" font-size="13" text-anchor="end">18 / 42</text>
<text x="510" y="96" font-size="13" text-anchor="end">18 / 88</text>
<rect x="20" y="103" width="490" height="4" rx="2" fill="#3c4a58"/>
<rect x="20" y="103" width="210.00" height="4" rx="2" fill="#88c6bd"/>
<rect x="20" y="103" width="100.23" height="4" rx="2" fill="#88c6bd"/>
<text x="20" y="134" font-size="13">Accepted guest milestones · X1–X4</text>
<text x="510" y="134" font-size="13" text-anchor="end">4 / 4</text>
<rect x="20" y="141" width="490" height="4" rx="2" fill="#3c4a58"/>

Before

Width:  |  Height:  |  Size: 1.5 KiB

After

Width:  |  Height:  |  Size: 1.5 KiB

+46
View File
@@ -21,7 +21,29 @@ The wider LLVM operand matrix exercises decoding only. ABI means application bin
| `s_waitcnt_vscnt null, 0` | SOPK, exact null source and zero immediate | 4 B | yes | yes | three-way passed | verified store wait | implemented | fixture verified | fixture verified |
| `s_endpgm` | SOPP, zero immediate | 4 B | yes | yes | three-way passed | verified termination | implemented | fixture verified | fixture verified |
| `s_mov_b32` | Normal SGPR or EXEC/VCC half destination and normal SGPR, inline integer or literal source | `BE880387` | yes | yes | three-way passed | resolved scalar state | implemented | fixture verified | fixture verified |
| `s_not_b32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = ~S0; SCC = D != 0 | `BE890708` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_brev_b32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = S0 bit-reversed; SCC unchanged | `BE8A0B08` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_bcnt0_i32_b32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = count of zero bits; SCC = D != 0 | `BE8C0D08` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_bcnt1_i32_b32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = count of one bits; SCC = D != 0 | `BE8B0F08` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_ff0_i32_b32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = index of the lowest zero bit, or -1; SCC unchanged | `BE8E11FF 0000FFFF` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_ff1_i32_b32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = index of the lowest one bit, or -1; SCC unchanged | `BE8D13FF 00400000` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_flbit_i32_b32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = zeros above the highest one bit, or -1; SCC unchanged | `BE8F1508` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_flbit_i32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = bits above the highest bit differing from the sign, or -1; SCC unchanged | `BE9017FF FFF00000` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_sext_i32_i8` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = S0[7:0] sign-extended; SCC unchanged | `BE911908` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_sext_i32_i16` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = S0[15:0] sign-extended; SCC unchanged | `BE921AFF 00018000` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_abs_i32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = \|S0\| (0x80000000 stays); SCC = D != 0 | `BE933412` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_cmp_eq_u32` | Normal SGPR or integer operands, with at most one source selecting a literal | `BF068708` | yes | yes | three-way passed | resolved SCC | implemented | fixture verified | fixture verified |
| `s_cmp_eq_i32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 == S1 (signed) | `BF00C108` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_cmp_lg_i32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 != S1 (signed) | `BF010908` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_cmp_gt_i32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 > S1 (signed) | `BF020908` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_cmp_ge_i32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 >= S1 (signed) | `BF030909` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_cmp_lt_i32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 < S1 (signed) | `BF040908` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_cmp_le_i32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 <= S1 (signed) | `BF050809` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_cmp_lg_u32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 != S1 (unsigned) | `BF07FF0A 89ABCDEF` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_cmp_gt_u32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 > S1 (unsigned) | `BF080908` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_cmp_ge_u32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 >= S1 (unsigned) | `BF090809` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_cmp_lt_u32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 < S1 (unsigned) | `BF0A0809` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_cmp_le_u32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 <= S1 (unsigned) | `BF0BC009` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_add_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = carry-out | `80088308` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_sub_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = borrow | `808A8180` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_add_i32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = signed overflow | `8110C109` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
@@ -31,6 +53,30 @@ The wider LLVM operand matrix exercises decoding only. ABI means application bin
| `s_and_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = result != 0 | `870D090C` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_or_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = result != 0 | `880ED00D` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_xor_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = result != 0 | `890C0A0B` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_andn2_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 & ~S1; SCC = result != 0 | `8A09FF08 FF00FF00` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_orn2_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 \| ~S1; SCC = result != 0 | `8B0AC109` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_nand_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = ~(S0 & S1); SCC = result != 0 | `8C0B0808` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_nor_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = ~(S0 \| S1); SCC = result != 0 | `8D0C090B` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_xnor_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = ~(S0 ^ S1); SCC = result != 0 | `8E0D080C` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_lshl_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 << S1[4:0]; SCC = result != 0 | `8F0EA40D` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_lshr_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 >> S1[4:0], zero fill; SCC = result != 0 | `900FFF0E FFFFFFE1` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_ashr_i32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 >> S1[4:0], sign fill; SCC = result != 0 | `91109F0E` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_min_i32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 if S0 < S1 (signed) else S1; SCC = S0 < S1 | `830A0908` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_min_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 if S0 < S1 (unsigned) else S1; SCC = S0 < S1 | `83988509` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_max_i32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 if S0 > S1 (signed) else S1; SCC = S0 > S1 | `84170908` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_max_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 if S0 > S1 (unsigned) else S1; SCC = S0 > S1 | `848C0908` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_cselect_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = SCC ? S0 : S1; reads SCC, SCC unchanged | `850B0809` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_bfm_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = ((1 << S0[4:0]) - 1) << S1[4:0]; SCC unchanged | `920D848C` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_mul_i32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = low 32 bits of S0 * S1; SCC unchanged | `930F0908` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_bfe_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 >> S1[4:0] masked to S1[22:16] bits; SCC = D != 0 | `9390FF08 00080004` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_bfe_i32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 >> S1[4:0] (sign fill) masked to S1[22:16] bits, sign-extended; SCC = D != 0 | `9411FF08 00080004` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_absdiff_i32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = \|S0 - S1\| of the 32-bit difference (0x80000000 stays); SCC = D != 0 | `96120809` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_lshl1_add_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = (S0 << 1) + S1; SCC = carry out of the exact sum | `970E0908` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_lshl2_add_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = (S0 << 2) + S1; SCC = carry out of the exact sum | `97990909` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_lshl3_add_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = (S0 << 3) + S1; SCC = carry out of the exact sum | `98130808` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_lshl4_add_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = (S0 << 4) + S1; SCC = carry out of the exact sum | `9894D009` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_mul_hi_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = high 32 bits of the unsigned product; SCC unchanged | `9A950808` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_mul_hi_i32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = high 32 bits of the signed product; SCC unchanged | `9B160808` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_cmp_lt_i32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (signed S0 < S1), fully written | `7D020701` | 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_eq_i32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (signed S0 == S1), fully written | `7D040280` | 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_le_i32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (signed S0 <= S1), fully written | `7D060208` | 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 |
+4 -2
View File
@@ -8,8 +8,10 @@
| SOPP `S_WAITCNT`, SOPK `S_WAITCNT_VSCNT` | A zero vector-load or vector-store threshold completes the associated transfer. The model permits one pending operation per counter (CLAIM-RDNA2-TRANSFER-WAITS). |
| VOP1 `V_MOV_B32` | Read a register, inline integer or literal. Copy all 32 bits. |
| VOP3 `V_ADD_NC_U32` | Read two vector registers and add modulo 2^32. No implicit carry or flag update. |
| SOP1 `S_MOV_B32`, SOPC `S_CMP_EQ_U32` | Copy 32 bits into a scalar register or compare two operands and set 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` | Exact integer result reduced modulo 2^32; SCC is the carry-out, the borrow, signed overflow (the exact signed result does not fit in i32), or a nonzero bitwise result, and ADDC/SUBB consume SCC ([SOP2 scalar ALU](scalar-alu.md)). Descriptor SGPRs are reserved. |
| SOP2 `S_MIN_{I32,U32}`, `S_MAX_{I32,U32}`, `S_CSELECT_B32`, `S_BFM_B32`, `S_MUL_I32`, `S_MUL_HI_{U32,I32}`, `S_BFE_{U32,I32}`, `S_ABSDIFF_I32`, `S_LSHL{1,2,3,4}_ADD_U32` | The guide's section 12.1 result, computed exactly and reduced modulo 2^32. Min and max compare strictly (a tie gives S1, SCC = 0); CSELECT reads SCC and refuses it unset; BFM, MUL, MUL_HI and CSELECT leave SCC unchanged; BFE uses offset S1[4:0] and width S1[22:16] (32 or more keeps every shifted bit); ABSDIFF negates the wrapped difference; LSHLn_ADD sets SCC to the carry of the exact sum. Descriptor SGPRs are reserved. |
| 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)). |
| 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. |
+109 -7
View File
@@ -1,7 +1,9 @@
# SOP2 scalar ALU subset
Xenora decodes and executes nine gfx1030 SOP2 forms. Each takes 32-bit
operands, writes a normal SGPR (s0-s105) and sets SCC.
Xenora decodes and executes thirty-three gfx1030 SOP2 forms. Each takes 32-bit
operands and writes a normal SGPR (s0-s105). The seventeen below set SCC; the
sixteen in [Arithmetic, select and bit-field forms](#arithmetic-select-and-bit-field-forms)
set it or leave it as the guide says.
| Form | D | SCC |
| --- | --- | --- |
@@ -14,10 +16,23 @@ operands, writes a normal SGPR (s0-s105) and sets SCC.
| `s_and_b32` | S0 & S1 | D != 0 |
| `s_or_b32` | S0 \| S1 | D != 0 |
| `s_xor_b32` | S0 ^ S1 | D != 0 |
| `s_andn2_b32` | S0 & ~S1 | D != 0 |
| `s_orn2_b32` | S0 \| ~S1 | D != 0 |
| `s_nand_b32` | ~(S0 & S1) | D != 0 |
| `s_nor_b32` | ~(S0 \| S1) | D != 0 |
| `s_xnor_b32` | ~(S0 ^ S1) | D != 0 |
| `s_lshl_b32` | S0 << S1[4:0] | D != 0 |
| `s_lshr_b32` | S0 >> S1[4:0], zero fill | D != 0 |
| `s_ashr_i32` | S0 >> S1[4:0], sign fill | D != 0 |
The last eight were added through the semantic registry alone: one TOML entry
each, with no hand-written Rust per form. Shifts use only the low five bits of
S1 as the count, as the guide's pseudocode states (section 12.1); higher bits are
ignored.
Sources are normal SGPRs, inline integers (-16 to 64) or one literal word.
These nine forms are declared as data in the semantic registry,
These forms are declared as data in the semantic registry,
`crates/isa/semantics/rdna2.toml`: opcode, operation, signedness, carry-in,
SCC effect, operand rule and guide references. `crates/isa/generate_semantics.py`
checks each declaration against the pinned AMD XML snapshot and rejects
@@ -55,17 +70,17 @@ the registry.
## Not supported
- Every other SOP2 form, including the 64-bit bitwise forms.
- Every other SOP2 form, including the 64-bit bitwise forms and `s_cselect_b64`.
- Destinations other than s0-s105 (VCC, EXEC, TTMP and M0).
- Sources other than normal SGPRs, inline integers and one literal.
- Both sources selecting a literal.
- ADDC or SUBB before SCC is set.
- ADDC, SUBB or CSELECT before SCC is set.
- Writes to the fixture's resource descriptors s0-s7.
## How it runs
Scalar state in a compute fixture is wave-uniform and known while the code is
translated. As with `s_mov_b32` and `s_cmp_eq_u32`, the translator evaluates
translated. As with `s_mov_b32` and the SOPC compares, the translator evaluates
SOP2 forms itself. It resolves SCC-dependent branches and emits SGPR values
read by `v_mov_b32_e32` as constants (`fixtures/golden/scalar-alu.ir`). So the
IR and MSL contain the results, not scalar instructions.
@@ -85,7 +100,7 @@ literal operands, bitwise results that set and clear SCC, and an
Its expected output, input ^ 0x0000000e,
was derived by hand.
`tests/validation/known_answers.rs` runs every supported form over 10 boundary
`tests/validation/known_answers.rs` runs the first nine forms over 10 boundary
operands squared, with SCC clear and set. That is 1,800 programs. The same file
covers aliasing, inline and literal operands, and rejected forms. Expected
values come from exact integer definitions in the test. Three implementations
@@ -94,7 +109,94 @@ must agree with them:
- the reference interpreter (exact integers, reduced modulo 2^32);
- the independent interpreter (a bit-serial ripple-carry adder).
The eight logical and shift forms added through the registry have their own
suite, `tests/validation/tests/sop2_stage_c.rs`: 6,896 cases whose expected
values were derived from the guide separately from the registry, checked on
both CPU interpreters and, through the translator, on native Metal. The
LLVM-assembled `fixtures/rdna2/scalar-logic.s` (expected input ^ 0x887f00f8)
runs on all three and on native Metal.
`scalar_alu_native_metal_known_answers` runs the fixture, the 1,800 programs
and the aliasing and immediate cases on native Metal with API and shader
validation. `scripts/test-gpu.sh` runs it. This is local evidence from one
Apple M5 Pro; independent acceptance is pending.
## Arithmetic, select and bit-field forms
Sixteen more 32-bit SOP2 forms are declared in the registry with the same
operand rule (`sop2_sgpr`), each one TOML entry over a shared primitive:
| Form | D | SCC |
| --- | --- | --- |
| `s_min_i32`, `s_min_u32` | S0 if S0 < S1 (signed or unsigned), else S1 | S0 < S1 |
| `s_max_i32`, `s_max_u32` | S0 if S0 > S1, else S1 | S0 > S1 |
| `s_cselect_b32` | SCC ? S0 : S1 | read, not written |
| `s_bfm_b32` | ((1 << S0[4:0]) - 1) << S1[4:0] | unchanged |
| `s_mul_i32` | low 32 bits of S0 * S1 | unchanged |
| `s_mul_hi_u32`, `s_mul_hi_i32` | high 32 bits of the unsigned or signed 64-bit product | unchanged |
| `s_bfe_u32` | (S0 >> S1[4:0]) masked to S1[22:16] bits | D != 0 |
| `s_bfe_i32` | (S0 >> S1[4:0], sign fill) masked to S1[22:16] bits, sign-extended from the field's top bit | D != 0 |
| `s_absdiff_i32` | \|S0 - S1\| of the wrapped 32-bit difference (0x80000000 stays) | D != 0 |
| `s_lshl1_add_u32` to `s_lshl4_add_u32` | (S0 << N) + S1, N = 1 to 4 | carry out of the exact sum, counting bits shifted out of S0 |
These follow the guide's 12.1 pseudocode and Tables 11, 12 and 14 (pages
34-36). Min and max compare strictly, so equal operands give S1 and SCC = 0.
The guide leaves two C-like operators open; Xenora reads them as exact
arithmetic: a BFE width of 32 to 127 keeps every shifted bit, and a width of 0
gives 0. These are guide readings, not hardware evidence. CSELECT is refused
when SCC has not been set, as ADDC and SUBB are.
The registry gained the vocabulary for them: the operations above, a
`selected_src0` SCC effect for min and max, `carry_in = "scc"` for the select
condition, and a declared `shift_amount` (1 to 4) for the shift-and-add forms.
The generated `ScalarAluOp::evaluate` now returns `(u32, Option<bool>)`, with
`None` for forms that leave SCC unchanged.
`tests/validation/tests/sop2_arith.rs` checks 21,070 cases, with expected values
derived from the guide (including its ABSDIFF examples) separately from the
registry, on both CPU interpreters and, through the translator, on native
Metal; its 597 rejected programs are checked on the CPU interpreters and the
compiler. `fixtures/rdna2/scalar-arith.s` (LLVM-assembled, expected input ^
0x81157dfe) chains all sixteen, including a min tie and CSELECT on both SCC
values, and shows SCC surviving the forms that do not write it.
## SOPC compares
The twelve 32-bit SOPC integer compares `s_cmp_{eq,lg,gt,ge,lt,le}_{i32,u32}`
are declared in the same registry (operand rule `sopc_scalar`). Each sets only
SCC, to whether the relation holds with SSRC0 on the left; LG means not equal.
EQ and LG give the same result for `_i32` and `_u32`; GT, GE, LT and LE compare
two's-complement values for `_i32` and unsigned values for `_u32` (guide section
12.4). Sources follow the SOP2 rule: normal SGPRs, inline integers or one
literal. Both sources selecting the literal encoding (255) is rejected for SOPC
as for SOP2; whether the guide allows one shared literal there was not settled.
`tests/validation/tests/sopc_stage_d.rs` checks 7,824 cases, with expected
values derived from the guide separately from the registry, on both CPU
interpreters and, through the translator, on native Metal (compiled per case
and read back from nine distinct generated kernels). Its 348 rejected programs
are checked on both CPU interpreters and against the compiler, which rejects
them before any Metal dispatch. `fixtures/rdna2/scalar-compare.s` (LLVM-assembled, expected input ^
0x00000d5b) records every compare's SCC through an `s_cbranch_scc0` per form.
## SOP1 unary forms
Eleven 32-bit SOP1 forms are declared in the registry (operand rule
`sop1_sgpr`): `s_not_b32`, `s_brev_b32`, `s_bcnt0_i32_b32`, `s_bcnt1_i32_b32`,
`s_ff0_i32_b32`, `s_ff1_i32_b32`, `s_flbit_i32_b32`, `s_flbit_i32`,
`s_sext_i32_i8`, `s_sext_i32_i16` and `s_abs_i32`. Following the guide (section
12.3): a find-first or find-last search that finds nothing returns -1
(0xffffffff); `s_flbit_i32` returns -1 for both 0 and -1; sign extension reads
S0[7:0] or S0[15:0]; `s_abs_i32` of 0x80000000 is 0x80000000. Only NOT, BCNT0,
BCNT1 and ABS write SCC, as D != 0; the other seven leave it unchanged.
`s_mov_b32` stays hand-written, because it also accepts EXEC and VCC halves as
destinations. As for SOP2, destinations s0-s7 are refused when a fixture runs
(they hold its buffer descriptors), and float inline constants are rejected.
`tests/validation/tests/sop1_unary.rs` checks 4,126 cases, with expected values
derived from the guide (including its worked examples) separately from the
registry, on both CPU interpreters and, through the translator, on native
Metal; its 231 rejected programs are checked on the CPU interpreters and the
compiler. `fixtures/rdna2/scalar-unary.s` (LLVM-assembled, expected input ^
0x0f0080f5) chains all eleven and shows SCC surviving the forms that do not
write it.
+6 -4
View File
@@ -24,9 +24,9 @@ acceptance remain outside the verified count. All results concern synthetic fixt
| MUBUF | 75 | 2 | 0 | 2 | 2 | 2 | 2 | 2 | 0 |
| SCRATCH | 22 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| SMEM | 14 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| SOP1 | 65 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 |
| SOP2 | 51 | 9 | 9 | 9 | 9 | 9 | 0 | 0 | 12 |
| SOPC | 18 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 |
| SOP1 | 65 | 12 | 11 | 12 | 12 | 12 | 1 | 1 | 11 |
| SOP2 | 51 | 33 | 33 | 33 | 33 | 33 | 0 | 0 | 12 |
| SOPC | 18 | 12 | 12 | 12 | 12 | 12 | 1 | 1 | 7 |
| SOPK | 27 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 |
| SOPP | 36 | 6 | 0 | 6 | 6 | 6 | 4 | 4 | 0 |
| VINTRP | 3 | 0 | 0 | 2 | 0 | 0 | 0 | 0 | 0 |
@@ -36,7 +36,7 @@ acceptance remain outside the verified count. All results concern synthetic fixt
| VOP3P | 29 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| VOP3SDST | 10 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| VOPC | 190 | 12 | 0 | 12 | 12 | 12 | 0 | 0 | 0 |
| **Total** | 1465 | 42 | 9 | 46 | 42 | 42 | 18 | 18 | 12 |
| **Total** | 1465 | 88 | 56 | 92 | 88 | 88 | 18 | 18 | 30 |
## Unsupported operand variants
@@ -44,4 +44,6 @@ The table counts distinct variant names per family across registry operand rules
| Family | Operand rule | Unsupported variants |
| --- | --- | --- |
| SOP1 | `sop1_sgpr` | `dst_exec`, `dst_m0`, `dst_null`, `dst_ttmp`, `dst_vcc`, `src_exec`, `src_float_inline`, `src_m0`, `src_special`, `src_ttmp`, `src_vcc` |
| 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` |
+32 -6
View File
@@ -51,11 +51,15 @@ error.
| `family` | Encoding family; must match the XML base encoding | e.g. `SOP2` |
| `opcode` | Opcode; must match the XML | non-negative integer |
| `variant` | Rust enum variant of the typed operation | CamelCase, e.g. `AddU32` |
| `operation` | The primitive the form uses | `add`, `sub`, `and`, `or`, `xor` |
| `signedness` | How operands are read | `unsigned`, `signed`, `bitwise` (`bitwise` exactly for `and`, `or`, `xor`) |
| `carry_in` | Whether the form reads SCC as carry-in or borrow-in | `none`, `scc` (`scc` only for unsigned `add` and `sub`) |
| `operation` | The primitive the form uses | `add`, `sub`, `and`, `or`, `xor`, `andn2`, `orn2`, `nand`, `nor`, `xnor`, `lshl`, `lshr`, `ashr`, `min`, `max`, `cselect`, `bfm`, `mul`, `mul_hi`, `bfe`, `absdiff`, `lshl_add`, `compare` and the SOP1 unaries |
| `signedness` | How operands are read | `unsigned`, `signed`, `bitwise` (always `bitwise` for the logical operations, `cselect` and `bfm`; never for the arithmetic ones, `add`, `sub`, `min`, `max`, `mul`, `mul_hi`, `bfe`, `absdiff` and `lshl_add`; shifts take their primitive's signedness) |
| `carry_in` | Whether the form reads SCC: carry-in, borrow-in or the select condition | `none`, `scc` (`scc` only for unsigned `add` and `sub`, and required for `cselect`) |
| `width` | Operand and result width in bits | `32` |
| `scc` | What the form writes to SCC | `carry_out`, `borrow`, `signed_overflow`, `nonzero`, `unchanged` |
| `source_bits` | Sign extension only: the low bits of S0 that are read. The XML must list S0 with that size and format (`FMT_NUM_I8` or `FMT_NUM_I16`) | `8`, `16`; required for `sext`, rejected elsewhere |
| `relation` | Compares only: the relation tested with S0 on the left | `eq`, `lg` (not equal), `gt`, `ge`, `lt`, `le`; required for `compare`, rejected elsewhere |
| `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) |
| `operands` | Name of an `[operand_rules]` entry for the same family | e.g. `sop2_sgpr` |
@@ -71,7 +75,28 @@ fixes the `scc` value:
| `sub` / `unsigned` | `borrow` | `sub_borrow_u32` | allowed |
| `add` / `signed` | `signed_overflow` | `add_overflow_i32` | no |
| `sub` / `signed` | `signed_overflow` | `sub_overflow_i32` | no |
| `and`, `or`, `xor` / `bitwise` | `nonzero` | `and_nonzero_b32`, `or_nonzero_b32`, `xor_nonzero_b32` | no |
| `and`, `or`, `xor`, `andn2`, `orn2`, `nand`, `nor`, `xnor` / `bitwise` | `nonzero` | `and_nonzero_b32`, `or_nonzero_b32`, `xor_nonzero_b32`, `andn2_nonzero_b32`, `orn2_nonzero_b32`, `nand_nonzero_b32`, `nor_nonzero_b32`, `xnor_nonzero_b32` | no |
| `lshl` / `bitwise` | `nonzero` | `lshl_nonzero_b32` | no |
| `lshr` / `unsigned` | `nonzero` | `lshr_nonzero_b32` | no |
| `ashr` / `signed` | `nonzero` | `ashr_nonzero_i32` | no |
| `not`, `bcnt0`, `bcnt1` / `bitwise` | `nonzero` | `not_nonzero_b32`, `bcnt0_nonzero_b32`, `bcnt1_nonzero_b32` | no |
| `brev`, `ff0`, `ff1`, `flbit` / `bitwise` | `unchanged` | `brev_b32`, `ff0_b32`, `ff1_b32`, `flbit_b32` | no |
| `flbit`, `sext` / `signed` | `unchanged` | `flbit_i32`, `sext_i32` | no |
| `abs` / `signed` | `nonzero` | `abs_nonzero_i32` | no |
| `min`, `max` / `signed` or `unsigned` | `selected_src0` | `min_i32`/`min_u32`, `max_i32`/`max_u32` | no |
| `cselect` / `bitwise` | `unchanged` | `cselect_b32` | required |
| `bfm` / `bitwise` | `unchanged` | `bfm_b32` | no |
| `mul` / `signed` | `unchanged` | `mul_lo_i32` | no |
| `mul_hi` / `unsigned` or `signed` | `unchanged` | `mul_hi_u32`, `mul_hi_i32` | no |
| `bfe` / `unsigned` or `signed` | `nonzero` | `bfe_nonzero_u32`, `bfe_nonzero_i32` | no |
| `absdiff` / `signed` | `nonzero` | `absdiff_nonzero_i32` | no |
| `lshl_add` / `unsigned` | `carry_out` | `lshl_add_carry_u32` (with `shift_amount`) | no |
| `compare` / `signed` or `unsigned` | `relation` | `eq_b32`, `ne_b32` (for both signednesses), `gt_i32`/`gt_u32`, `ge_*`, `lt_*`, `le_*` | no |
A 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`.
Behaviour is chosen only from these declared fields, never from the mnemonic.
@@ -87,7 +112,8 @@ vocabularies above, it rejects:
- XML disagreements: a family with no XML encoding, a form with no default XML
variant, a different opcode, an SCC input or output the XML does not show (or
that the declaration omits), an operand width other than `width`, a signed
declaration on unsigned XML formats or the reverse, an operand direction that
declaration on unsigned XML formats or the reverse (a shift count or the `bfe`
field descriptor in S1 must be `FMT_NUM_U32` whatever the signedness), an operand direction that
differs, and XML operands the operand rule does not cover;
- references: a spec citing an undeclared document, a bad section or page, or
no guide page at all;
+552
View File
@@ -135,6 +135,138 @@ recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_not_b32"
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = ~S0; SCC = D != 0"
representation = "`BE890708`"
lowering = "resolved scalar state and SCC"
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_brev_b32"
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = S0 bit-reversed; SCC unchanged"
representation = "`BE8A0B08`"
lowering = "resolved scalar state and SCC"
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_bcnt0_i32_b32"
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = count of zero bits; SCC = D != 0"
representation = "`BE8C0D08`"
lowering = "resolved scalar state and SCC"
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_bcnt1_i32_b32"
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = count of one bits; SCC = D != 0"
representation = "`BE8B0F08`"
lowering = "resolved scalar state and SCC"
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_ff0_i32_b32"
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = index of the lowest zero bit, or -1; SCC unchanged"
representation = "`BE8E11FF 0000FFFF`"
lowering = "resolved scalar state and SCC"
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_ff1_i32_b32"
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = index of the lowest one bit, or -1; SCC unchanged"
representation = "`BE8D13FF 00400000`"
lowering = "resolved scalar state and SCC"
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_flbit_i32_b32"
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = zeros above the highest one bit, or -1; SCC unchanged"
representation = "`BE8F1508`"
lowering = "resolved scalar state and SCC"
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_flbit_i32"
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = bits above the highest bit differing from the sign, or -1; SCC unchanged"
representation = "`BE9017FF FFF00000`"
lowering = "resolved scalar state and SCC"
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_sext_i32_i8"
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = S0[7:0] sign-extended; SCC unchanged"
representation = "`BE911908`"
lowering = "resolved scalar state and SCC"
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_sext_i32_i16"
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = S0[15:0] sign-extended; SCC unchanged"
representation = "`BE921AFF 00018000`"
lowering = "resolved scalar state and SCC"
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_abs_i32"
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = |S0| (0x80000000 stays); SCC = D != 0"
representation = "`BE933412`"
lowering = "resolved scalar state and SCC"
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_cmp_eq_u32"
encoding = "Normal SGPR or integer operands, with at most one source selecting a literal"
@@ -147,6 +279,138 @@ recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_cmp_eq_i32"
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 == S1 (signed)"
representation = "`BF00C108`"
lowering = "resolved SCC"
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_cmp_lg_i32"
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 != S1 (signed)"
representation = "`BF010908`"
lowering = "resolved SCC"
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_cmp_gt_i32"
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 > S1 (signed)"
representation = "`BF020908`"
lowering = "resolved SCC"
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_cmp_ge_i32"
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 >= S1 (signed)"
representation = "`BF030909`"
lowering = "resolved SCC"
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_cmp_lt_i32"
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 < S1 (signed)"
representation = "`BF040908`"
lowering = "resolved SCC"
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_cmp_le_i32"
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 <= S1 (signed)"
representation = "`BF050809`"
lowering = "resolved SCC"
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_cmp_lg_u32"
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 != S1 (unsigned)"
representation = "`BF07FF0A 89ABCDEF`"
lowering = "resolved SCC"
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_cmp_gt_u32"
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 > S1 (unsigned)"
representation = "`BF080908`"
lowering = "resolved SCC"
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_cmp_ge_u32"
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 >= S1 (unsigned)"
representation = "`BF090809`"
lowering = "resolved SCC"
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_cmp_lt_u32"
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 < S1 (unsigned)"
representation = "`BF0A0809`"
lowering = "resolved SCC"
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_cmp_le_u32"
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 <= S1 (unsigned)"
representation = "`BF0BC009`"
lowering = "resolved SCC"
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_add_u32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = carry-out"
@@ -255,6 +519,294 @@ recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_andn2_b32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 & ~S1; SCC = result != 0"
representation = "`8A09FF08 FF00FF00`"
lowering = "resolved scalar state and SCC"
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_orn2_b32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 | ~S1; SCC = result != 0"
representation = "`8B0AC109`"
lowering = "resolved scalar state and SCC"
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_nand_b32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = ~(S0 & S1); SCC = result != 0"
representation = "`8C0B0808`"
lowering = "resolved scalar state and SCC"
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_nor_b32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = ~(S0 | S1); SCC = result != 0"
representation = "`8D0C090B`"
lowering = "resolved scalar state and SCC"
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_xnor_b32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = ~(S0 ^ S1); SCC = result != 0"
representation = "`8E0D080C`"
lowering = "resolved scalar state and SCC"
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_lshl_b32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 << S1[4:0]; SCC = result != 0"
representation = "`8F0EA40D`"
lowering = "resolved scalar state and SCC"
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_lshr_b32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 >> S1[4:0], zero fill; SCC = result != 0"
representation = "`900FFF0E FFFFFFE1`"
lowering = "resolved scalar state and SCC"
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_ashr_i32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 >> S1[4:0], sign fill; SCC = result != 0"
representation = "`91109F0E`"
lowering = "resolved scalar state and SCC"
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_min_i32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 if S0 < S1 (signed) else S1; SCC = S0 < S1"
representation = "`830A0908`"
lowering = "resolved scalar state and SCC"
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_min_u32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 if S0 < S1 (unsigned) else S1; SCC = S0 < S1"
representation = "`83988509`"
lowering = "resolved scalar state and SCC"
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_max_i32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 if S0 > S1 (signed) else S1; SCC = S0 > S1"
representation = "`84170908`"
lowering = "resolved scalar state and SCC"
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_max_u32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 if S0 > S1 (unsigned) else S1; SCC = S0 > S1"
representation = "`848C0908`"
lowering = "resolved scalar state and SCC"
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_cselect_b32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = SCC ? S0 : S1; reads SCC, SCC unchanged"
representation = "`850B0809`"
lowering = "resolved scalar state and SCC"
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_bfm_b32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = ((1 << S0[4:0]) - 1) << S1[4:0]; SCC unchanged"
representation = "`920D848C`"
lowering = "resolved scalar state and SCC"
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_mul_i32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = low 32 bits of S0 * S1; SCC unchanged"
representation = "`930F0908`"
lowering = "resolved scalar state and SCC"
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_bfe_u32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 >> S1[4:0] masked to S1[22:16] bits; SCC = D != 0"
representation = "`9390FF08 00080004`"
lowering = "resolved scalar state and SCC"
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_bfe_i32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 >> S1[4:0] (sign fill) masked to S1[22:16] bits, sign-extended; SCC = D != 0"
representation = "`9411FF08 00080004`"
lowering = "resolved scalar state and SCC"
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_absdiff_i32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = |S0 - S1| of the 32-bit difference (0x80000000 stays); SCC = D != 0"
representation = "`96120809`"
lowering = "resolved scalar state and SCC"
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_lshl1_add_u32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = (S0 << 1) + S1; SCC = carry out of the exact sum"
representation = "`970E0908`"
lowering = "resolved scalar state and SCC"
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_lshl2_add_u32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = (S0 << 2) + S1; SCC = carry out of the exact sum"
representation = "`97990909`"
lowering = "resolved scalar state and SCC"
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_lshl3_add_u32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = (S0 << 3) + S1; SCC = carry out of the exact sum"
representation = "`98130808`"
lowering = "resolved scalar state and SCC"
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_lshl4_add_u32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = (S0 << 4) + S1; SCC = carry out of the exact sum"
representation = "`9894D009`"
lowering = "resolved scalar state and SCC"
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_mul_hi_u32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = high 32 bits of the unsigned product; SCC unchanged"
representation = "`9A950808`"
lowering = "resolved scalar state and SCC"
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_mul_hi_i32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = high 32 bits of the signed product; SCC unchanged"
representation = "`9B160808`"
lowering = "resolved scalar state and SCC"
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_lt_i32_e32"
encoding = "VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (signed S0 < S1), fully written"
+39
View File
@@ -0,0 +1,39 @@
0000: t0 = load.u32 input[index]
0068: branch.uniform 0x0074 taken=true
0074: t2 = const.u32 0x89abcdef
0078: t3 = const.u32 0x00000005
007c: t4 = xor.b32 t2, t3
0080: t5 = const.u32 0x89abcdef
0084: t6 = xor.b32 t4, t5
0088: t7 = const.u32 0x0000fff0
008c: t8 = xor.b32 t6, t7
0090: t9 = const.u32 0x13579be3
0094: t10 = xor.b32 t8, t9
0098: t11 = const.u32 0xb05b05ab
009c: t12 = xor.b32 t10, t11
00a0: t13 = const.u32 0x000000de
00a4: t14 = xor.b32 t12, t13
00a8: t15 = const.u32 0xffffffde
00ac: t16 = xor.b32 t14, t15
00b0: t17 = const.u32 0x76543216
00b4: t18 = xor.b32 t16, t17
00b8: t19 = const.u32 0xd70a3d67
00bc: t20 = xor.b32 t18, t19
00c0: t21 = const.u32 0x00000040
00c4: t22 = xor.b32 t20, t21
00c8: t23 = const.u32 0x4a0955b6
00cc: t24 = xor.b32 t22, t23
00d0: t25 = const.u32 0x36b1b9d8
00d4: t26 = xor.b32 t24, t25
00d8: t27 = const.u32 0x00000005
00dc: t28 = xor.b32 t26, t27
00e0: t29 = const.u32 0x00000005
00e4: t30 = xor.b32 t28, t29
00e8: t31 = const.u32 0x00000019
00ec: t32 = xor.b32 t30, t31
00f0: t33 = const.u32 0x00000005
00f4: t34 = xor.b32 t32, t33
00f8: t35 = const.u32 0x00000000
00fc: t36 = xor.b32 t34, t35
0100: t37 = xor.b32 t0, t36
0104: store.u32 output[index], t37
+45
View File
@@ -0,0 +1,45 @@
#include <metal_stdlib>
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 t0 = input[index];
uint t2 = 0x89abcdefu;
uint t3 = 0x00000005u;
uint t4 = t2 ^ t3;
uint t5 = 0x89abcdefu;
uint t6 = t4 ^ t5;
uint t7 = 0x0000fff0u;
uint t8 = t6 ^ t7;
uint t9 = 0x13579be3u;
uint t10 = t8 ^ t9;
uint t11 = 0xb05b05abu;
uint t12 = t10 ^ t11;
uint t13 = 0x000000deu;
uint t14 = t12 ^ t13;
uint t15 = 0xffffffdeu;
uint t16 = t14 ^ t15;
uint t17 = 0x76543216u;
uint t18 = t16 ^ t17;
uint t19 = 0xd70a3d67u;
uint t20 = t18 ^ t19;
uint t21 = 0x00000040u;
uint t22 = t20 ^ t21;
uint t23 = 0x4a0955b6u;
uint t24 = t22 ^ t23;
uint t25 = 0x36b1b9d8u;
uint t26 = t24 ^ t25;
uint t27 = 0x00000005u;
uint t28 = t26 ^ t27;
uint t29 = 0x00000005u;
uint t30 = t28 ^ t29;
uint t31 = 0x00000019u;
uint t32 = t30 ^ t31;
uint t33 = 0x00000005u;
uint t34 = t32 ^ t33;
uint t35 = 0x00000000u;
uint t36 = t34 ^ t35;
uint t37 = t0 ^ t36;
output[index] = t37;
}
+16
View File
@@ -0,0 +1,16 @@
0000: t0 = load.u32 input[index]
001c: branch.uniform 0x0024 taken=false
0028: branch.uniform 0x0030 taken=false
0034: branch.uniform 0x003c taken=true
0040: branch.uniform 0x0048 taken=false
004c: branch.uniform 0x0054 taken=false
0058: branch.uniform 0x0060 taken=true
0064: branch.uniform 0x006c taken=false
007c: branch.uniform 0x0088 taken=true
008c: branch.uniform 0x0098 taken=false
009c: branch.uniform 0x00a8 taken=true
00ac: branch.uniform 0x00b8 taken=false
00bc: branch.uniform 0x00c8 taken=false
00c8: t13 = const.u32 0x00000d5b
00cc: t14 = xor.b32 t0, t13
00d0: store.u32 output[index], t14
+11
View File
@@ -0,0 +1,11 @@
#include <metal_stdlib>
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 t0 = input[index];
uint t13 = 0x00000d5bu;
uint t14 = t0 ^ t13;
output[index] = t14;
}
+13
View File
@@ -0,0 +1,13 @@
0000: t0 = load.u32 input[index]
0040: branch.uniform 0x004c taken=true
004c: t2 = const.u32 0xff0fffff
0050: t3 = const.u32 0x787ffff8
0054: t4 = xor.b32 t2, t3
0058: t5 = const.u32 0xffffffff
005c: t6 = xor.b32 t4, t5
0060: t7 = const.u32 0x00f00000
0064: t8 = xor.b32 t6, t7
0068: t9 = const.u32 0xf000ff00
006c: t10 = xor.b32 t8, t9
0070: t11 = xor.b32 t0, t10
0074: store.u32 output[index], t11
+19
View File
@@ -0,0 +1,19 @@
#include <metal_stdlib>
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 t0 = input[index];
uint t2 = 0xff0fffffu;
uint t3 = 0x787ffff8u;
uint t4 = t2 ^ t3;
uint t5 = 0xffffffffu;
uint t6 = t4 ^ t5;
uint t7 = 0x00f00000u;
uint t8 = t6 ^ t7;
uint t9 = 0xf000ff00u;
uint t10 = t8 ^ t9;
uint t11 = t0 ^ t10;
output[index] = t11;
}
+29
View File
@@ -0,0 +1,29 @@
0000: t0 = load.u32 input[index]
0060: branch.uniform 0x006c taken=true
006c: t2 = const.u32 0xffffff0f
0070: t3 = const.u32 0x0f000000
0074: t4 = xor.b32 t2, t3
0078: t5 = const.u32 0x00000004
007c: t6 = xor.b32 t4, t5
0080: t7 = const.u32 0x0000001c
0084: t8 = xor.b32 t6, t7
0088: t9 = const.u32 0x00000016
008c: t10 = xor.b32 t8, t9
0090: t11 = const.u32 0x00000010
0094: t12 = xor.b32 t10, t11
0098: t13 = const.u32 0x00000018
009c: t14 = xor.b32 t12, t13
00a0: t15 = const.u32 0x0000000c
00a4: t16 = xor.b32 t14, t15
00a8: t17 = const.u32 0xfffffff0
00ac: t18 = xor.b32 t16, t17
00b0: t19 = const.u32 0xffff8000
00b4: t20 = xor.b32 t18, t19
00b8: t21 = const.u32 0x00008000
00bc: t22 = xor.b32 t20, t21
00c0: t23 = const.u32 0x00007fff
00c4: t24 = xor.b32 t22, t23
00c8: t25 = const.u32 0xffffffff
00cc: t26 = xor.b32 t24, t25
00d0: t27 = xor.b32 t0, t26
00d4: store.u32 output[index], t27
+35
View File
@@ -0,0 +1,35 @@
#include <metal_stdlib>
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 t0 = input[index];
uint t2 = 0xffffff0fu;
uint t3 = 0x0f000000u;
uint t4 = t2 ^ t3;
uint t5 = 0x00000004u;
uint t6 = t4 ^ t5;
uint t7 = 0x0000001cu;
uint t8 = t6 ^ t7;
uint t9 = 0x00000016u;
uint t10 = t8 ^ t9;
uint t11 = 0x00000010u;
uint t12 = t10 ^ t11;
uint t13 = 0x00000018u;
uint t14 = t12 ^ t13;
uint t15 = 0x0000000cu;
uint t16 = t14 ^ t15;
uint t17 = 0xfffffff0u;
uint t18 = t16 ^ t17;
uint t19 = 0xffff8000u;
uint t20 = t18 ^ t19;
uint t21 = 0x00008000u;
uint t22 = t20 ^ t21;
uint t23 = 0x00007fffu;
uint t24 = t22 ^ t23;
uint t25 = 0xffffffffu;
uint t26 = t24 ^ t25;
uint t27 = t0 ^ t26;
output[index] = t27;
}
Binary file not shown.
+69
View File
@@ -0,0 +1,69 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Generate the original PE32+ frame-loop fixture without an x86 toolchain.
The guest calls xenora.dll!frame_submit(index) with index = 0, 1, 2, ... and
stops when the import returns 0, then halts. Frame order is guest state (RBX).
"""
import argparse
from pathlib import Path
from struct import pack, pack_into
def fixture():
base = 0x140000000
entry, imports = 0x1000, 0x2000
iat, lookup, module, symbol = (imports + x for x in (0x40, 0x50, 0x60, 0x80))
data = bytearray(0x800)
data[:2] = b"MZ"
pack_into("<I", data, 0x3C, 0x80)
data[0x80:0x84] = b"PE\0\0"
pack_into("<HHIIIHH", data, 0x84, 0x8664, 2, 0, 0, 0, 240, 0x22)
opt = 0x98
pack_into("<H", data, opt, 0x20B)
pack_into("<III", data, opt + 4, 0x200, 0x200, 0)
pack_into("<IIQII", data, opt + 16, entry, entry, base, 0x1000, 0x200)
pack_into("<II", data, opt + 56, 0x3000, 0x400)
pack_into("<HH", data, opt + 68, 3, 0x160)
pack_into("<QQQQII", data, opt + 72, 0x10000, 0x1000, 0x10000, 0x1000, 0, 16)
for index, rva, size in ((1, imports, 40), (12, iat, 16)):
pack_into("<II", data, opt + 112 + index * 8, rva, size)
for index, (name, rva, permissions) in enumerate(
((b".text", entry, 0x60000020), (b".rdata", imports, 0x40000040))
):
pack_into(
"<8sIIIIIIHHI", data, opt + 240 + 40 * index, name, 0x200, rva,
0x200, 0x400 + 0x200 * index, 0, 0, 0, 0, permissions,
)
loop = entry + 6
code = b"\x48\x83\xec\x28" # sub rsp, 0x28 (Win64 home area)
code += b"\x31\xdb" # xor ebx, ebx (frame index)
code += b"\x48\x89\xd9" # loop: mov rcx, rbx
code += b"\xff\x15" + pack("<i", iat - (loop + 9)) # call [rip -> IAT]
code += b"\x48\xff\xc3" # inc rbx
code += b"\x48\x85\xc0" # test rax, rax
code += b"\x75" + pack("<b", loop - (loop + 17)) # jnz loop
code += b"\x48\x83\xc4\x28\xf4" # add rsp, 0x28; hlt
data[0x400:0x400 + len(code)] = code
pack_into("<IIIII", data, 0x600, lookup, 0, 0, module, iat)
pack_into("<Q", data, 0x640, symbol)
pack_into("<Q", data, 0x650, symbol)
data[0x660:0x66B] = b"xenora.dll\0"
data[0x682:0x68E] = b"frame_submit"
return data
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--check", action="store_true")
args = parser.parse_args()
path = Path(__file__).with_suffix(".exe")
if args.check:
if path.read_bytes() != fixture():
parser.exit(1, f"fixture bytes differ from generator: {path}\n")
else:
path.write_bytes(fixture())
Binary file not shown.
+77
View File
@@ -0,0 +1,77 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Original SOP2 vectors for the registry-declared arithmetic, select and
// bit-field forms: signed and unsigned min/max (including a tie, which gives S1
// and SCC = 0), select on both SCC values, bit-field mask, low and high
// multiplies, both bit-field extracts, absolute difference and the four
// shift-and-add forms. BFM, MUL, MUL_HI and CSELECT leave SCC unchanged; the
// last SCC writer (LSHL2_ADD, no carry) clears it for the s_cbranch_scc0.
// Values from the guide's 12.1 pseudocode, with s8 = 0x89abcdef (negative as
// i32) and s9 = 5.
// Expected: input ^ 0x81157dfe (the XOR of s10-s27 below).
.text
buffer_load_dword v1, v0, s[0:3], 0 idxen
s_waitcnt vmcnt(0)
s_mov_b32 s8, 0x89abcdef
s_mov_b32 s9, 5
s_min_i32 s10, s8, s9 // s10 = 0x89abcdef, SCC = 1 (S0 < S1 signed)
s_cselect_b32 s11, s9, s8 // s11 = 5 (SCC = 1 picks S0), SCC unchanged
s_max_u32 s12, s8, s9 // s12 = 0x89abcdef, SCC = 1
s_bfm_b32 s13, 12, 4 // s13 = 0xfff << 4 = 0xfff0, SCC unchanged
s_lshl1_add_u32 s14, s8, s9 // (s8 << 1) + 5 = 0x1_13579be3: s14 = 0x13579be3, SCC = 1
s_mul_i32 s15, s8, s9 // 5 * s8 = 0x2_b05b05ab: s15 = 0xb05b05ab
s_bfe_u32 s16, s8, 0x80004 // offset 4, width 8: s16 = 0xde, SCC = 1
s_bfe_i32 s17, s8, 0x80004 // 0xde sign-extended from bit 7: s17 = 0xffffffde, SCC = 1
s_absdiff_i32 s18, s9, s8 // 5 - (-0x76543211) = 0x76543216: s18, SCC = 1
s_lshl3_add_u32 s19, s8, s8 // 9 * s8 = 0x4_d70a3d67: s19 = 0xd70a3d67, SCC = 1
s_lshl4_add_u32 s20, s9, -16 // 80 + 0xfffffff0 = 0x1_00000040: s20 = 0x40, SCC = 1
s_mul_hi_u32 s21, s8, s8 // high word of s8 * s8 (unsigned): s21 = 0x4a0955b6
s_mul_hi_i32 s22, s8, s8 // high word of 0x76543211^2: s22 = 0x36b1b9d8
s_max_i32 s23, s8, s9 // s23 = 5, SCC = 0 (S0 not greater)
s_min_u32 s24, s9, 5 // tie: s24 = 5 (S1), SCC = 0
s_lshl2_add_u32 s25, s9, s9 // 20 + 5: s25 = 25, SCC = 0 (no carry)
s_cselect_b32 s26, s8, s9 // s26 = 5 (SCC = 0 picks S1), SCC unchanged
s_mul_hi_u32 s27, s9, s9 // s27 = 0, SCC unchanged (0)
s_cbranch_scc0 .Lzero
v_mov_b32_e32 v2, 0
s_branch .Ldone
.Lzero:
v_mov_b32_e32 v2, s10
v_mov_b32_e32 v3, s11
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v3, s12
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v3, s13
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v3, s14
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v3, s15
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v3, s16
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v3, s17
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v3, s18
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v3, s19
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v3, s20
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v3, s21
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v3, s22
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v3, s23
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v3, s24
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v3, s25
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v3, s26
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v3, s27
v_xor_b32_e32 v2, v2, v3
v_xor_b32_e32 v2, v1, v2 // v2 = input ^ 0x81157dfe
.Ldone:
buffer_store_dword v2, v0, s[4:7], 0 idxen
s_waitcnt_vscnt null, 0
s_endpgm
Binary file not shown.
+66
View File
@@ -0,0 +1,66 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Original SOPC vectors: each of the twelve 32-bit integer compares sets SCC,
// and an s_cbranch_scc0 skips setting that compare's bit in s20, so s20
// records every result. -1 and 1 separate signed from unsigned ordering;
// inline and literal operands appear in the second position.
// Expected: input ^ 0x00000d5b (bits worked out by hand below).
.text
buffer_load_dword v1, v0, s[0:3], 0 idxen
s_waitcnt vmcnt(0)
s_mov_b32 s8, -1
s_mov_b32 s9, 1
s_mov_b32 s20, 0
s_cmp_eq_i32 s8, -1 // -1 == -1: SCC = 1
s_cbranch_scc0 .Lskip0
s_or_b32 s20, s20, 1
.Lskip0:
s_cmp_lg_i32 s8, s9 // -1 != 1: SCC = 1
s_cbranch_scc0 .Lskip1
s_or_b32 s20, s20, 2
.Lskip1:
s_cmp_gt_i32 s8, s9 // -1 > 1: SCC = 0
s_cbranch_scc0 .Lskip2
s_or_b32 s20, s20, 4
.Lskip2:
s_cmp_ge_i32 s9, s9 // 1 >= 1: SCC = 1
s_cbranch_scc0 .Lskip3
s_or_b32 s20, s20, 8
.Lskip3:
s_cmp_lt_i32 s8, s9 // -1 < 1: SCC = 1
s_cbranch_scc0 .Lskip4
s_or_b32 s20, s20, 16
.Lskip4:
s_cmp_le_i32 s9, s8 // 1 <= -1: SCC = 0
s_cbranch_scc0 .Lskip5
s_or_b32 s20, s20, 32
.Lskip5:
s_cmp_eq_u32 s9, 1 // 1 == 1: SCC = 1
s_cbranch_scc0 .Lskip6
s_or_b32 s20, s20, 64
.Lskip6:
s_mov_b32 s10, 0x89abcdef
s_cmp_lg_u32 s10, 0x89abcdef // 0x89abcdef != 0x89abcdef: SCC = 0 (literal)
s_cbranch_scc0 .Lskip7
s_or_b32 s20, s20, 0x80
.Lskip7:
s_cmp_gt_u32 s8, s9 // 0xffffffff > 1: SCC = 1
s_cbranch_scc0 .Lskip8
s_or_b32 s20, s20, 0x100
.Lskip8:
s_cmp_ge_u32 s9, s8 // 1 >= 0xffffffff: SCC = 0
s_cbranch_scc0 .Lskip9
s_or_b32 s20, s20, 0x200
.Lskip9:
s_cmp_lt_u32 s9, s8 // 1 < 0xffffffff: SCC = 1
s_cbranch_scc0 .Lskip10
s_or_b32 s20, s20, 0x400
.Lskip10:
s_cmp_le_u32 s9, 64 // 1 <= 64: SCC = 1
s_cbranch_scc0 .Lskip11
s_or_b32 s20, s20, 0x800
.Lskip11:
v_mov_b32_e32 v2, s20
v_xor_b32_e32 v2, v1, v2 // s20 = 0x00000d5b
buffer_store_dword v2, v0, s[4:7], 0 idxen
s_waitcnt_vscnt null, 0
s_endpgm
Binary file not shown.
+38
View File
@@ -0,0 +1,38 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Original SOP2 vectors for the registry-declared logical and shift forms:
// ANDN2/ORN2 with a literal and an inline -1, NAND with aliased sources,
// NOR/XNOR chains, shift counts that use only S1[4:0] (36 -> 4, a literal
// 0xffffffe1 -> 1, 31), an arithmetic shift of a negative and a positive value,
// and an SCC branch on a zero shift result. SGPR results are moved into VGPRs.
// Expected: input ^ 0x887f00f8 (worked out by hand below).
.text
buffer_load_dword v1, v0, s[0:3], 0 idxen
s_waitcnt vmcnt(0)
s_mov_b32 s8, 0xf0f0ff00
s_andn2_b32 s9, s8, 0xff00ff00 // s9 = 0x00f00000, SCC = 1
s_orn2_b32 s10, s9, -1 // s10 = 0x00f00000, SCC = 1
s_nand_b32 s11, s8, s8 // s11 = 0x0f0f00ff, SCC = 1
s_nor_b32 s12, s11, s9 // s12 = 0xf000ff00, SCC = 1
s_xnor_b32 s13, s12, s8 // s13 = 0xff0fffff, SCC = 1
s_lshl_b32 s14, s13, 36 // s14 = 0xf0fffff0 (count 4), SCC = 1
s_lshr_b32 s15, s14, 0xffffffe1 // s15 = 0x787ffff8 (count 1), SCC = 1
s_ashr_i32 s16, s14, 31 // s16 = 0xffffffff, SCC = 1
s_ashr_i32 s17, s15, 31 // s17 = 0, SCC = 0
s_cbranch_scc0 .Lzero
v_mov_b32_e32 v2, 0
s_branch .Ldone
.Lzero:
v_mov_b32_e32 v2, s13
v_mov_b32_e32 v3, s15
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v4, s16
v_xor_b32_e32 v2, v2, v4
v_mov_b32_e32 v5, s10
v_xor_b32_e32 v2, v2, v5
v_mov_b32_e32 v6, s12
v_xor_b32_e32 v2, v2, v6 // 0xff0fffff ^ 0x787ffff8 ^ 0xffffffff ^ 0x00f00000 ^ 0xf000ff00
v_xor_b32_e32 v2, v1, v2
.Ldone:
buffer_store_dword v2, v0, s[4:7], 0 idxen
s_waitcnt_vscnt null, 0
s_endpgm
Binary file not shown.
+59
View File
@@ -0,0 +1,59 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Original SOP1 vectors for the registry-declared unary forms: complement, bit
// reverse, both bit counts, both find-first searches (one finding nothing, which
// gives -1), both find-last-bit forms, sign extension from 8 and 16 bits, and
// absolute value. SCC is set by NOT/BCNT/ABS only: an ABS of zero clears it, and
// the following SEXT and FF1 leave it clear for the s_cbranch_scc0.
// Expected: input ^ 0x0f0080f5 (worked out by hand below).
.text
buffer_load_dword v1, v0, s[0:3], 0 idxen
s_waitcnt vmcnt(0)
s_mov_b32 s8, 0xf0
s_not_b32 s9, s8 // s9 = 0xffffff0f, SCC = 1
s_brev_b32 s10, s8 // s10 = 0x0f000000
s_bcnt1_i32_b32 s11, s8 // s11 = 4, SCC = 1
s_bcnt0_i32_b32 s12, s8 // s12 = 28, SCC = 1
s_ff1_i32_b32 s13, 0x400000 // s13 = 22
s_ff0_i32_b32 s14, 0xffff // s14 = 16
s_flbit_i32_b32 s15, s8 // s15 = 24
s_flbit_i32 s16, 0xfff00000 // s16 = 12 (bits equal to the sign above bit 19)
s_sext_i32_i8 s17, s8 // s17 = 0xfffffff0
s_sext_i32_i16 s18, 0x18000 // s18 = 0xffff8000
s_abs_i32 s19, s18 // s19 = 0x8000, SCC = 1
s_abs_i32 s20, 0 // s20 = 0, SCC = 0
s_sext_i32_i16 s21, 0x7fff // s21 = 0x7fff, SCC unchanged (0)
s_ff1_i32_b32 s22, 0 // s22 = 0xffffffff (none found), SCC unchanged (0)
s_cbranch_scc0 .Lzero
v_mov_b32_e32 v2, 0
s_branch .Ldone
.Lzero:
v_mov_b32_e32 v2, s9
v_mov_b32_e32 v3, s10
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v3, s11
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v3, s12
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v3, s13
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v3, s14
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v3, s15
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v3, s16
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v3, s17
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v3, s18
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v3, s19
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v3, s21
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v3, s22
v_xor_b32_e32 v2, v2, v3
v_xor_b32_e32 v2, v1, v2 // v2 = input ^ 0x0f0080f5
.Ldone:
buffer_store_dword v2, v0, s[4:7], 0 idxen
s_waitcnt_vscnt null, 0
s_endpgm
+1 -1
View File
@@ -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; 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; 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"
+58
View File
@@ -0,0 +1,58 @@
#!/bin/sh
# SPDX-License-Identifier: GPL-3.0-or-later
# Build Xenora.app (native ARM64) into build/Xenora.app and run its smoke check.
# Requires: macOS on Apple Silicon, Rust 1.100 (aarch64-apple-darwin), Swift 6 toolchain.
set -eu
cd "$(dirname "$0")/.."
root=$(pwd)
fail() { echo "build-app: $*" >&2; exit 1; }
[ "$(uname -s)" = Darwin ] || fail "macOS is required"
[ "$(uname -m)" = arm64 ] || fail "a native arm64 host is required"
[ "$(sysctl -n sysctl.proc_translated 2>/dev/null || echo 0)" = 0 ] || fail "running under Rosetta is not supported"
command -v cargo >/dev/null || fail "cargo not found; install Rust 1.100"
command -v swift >/dev/null || fail "swift not found; install the Xcode command line tools"
target=aarch64-apple-darwin
# Match the app's LSMinimumSystemVersion so the static library links cleanly.
MACOSX_DEPLOYMENT_TARGET=14.0 cargo build --locked --release -p xenora-ffi --target "$target"
swift build --package-path app -c release --arch arm64 \
-Xlinker -L -Xlinker "$root/target/$target/release"
bundle="$root/build/Xenora.app"
rm -rf "$bundle"
mkdir -p "$bundle/Contents/MacOS"
cp "$(swift build --package-path app -c release --arch arm64 --show-bin-path)/Xenora" "$bundle/Contents/MacOS/Xenora"
cat > "$bundle/Contents/Info.plist" <<PLIST
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleExecutable</key><string>Xenora</string>
<key>CFBundleIdentifier</key><string>local.xenora.Xenora</string>
<key>CFBundleName</key><string>Xenora</string>
<key>CFBundlePackageType</key><string>APPL</string>
<key>CFBundleShortVersionString</key><string>0.1.0</string>
<key>LSMinimumSystemVersion</key><string>14.0</string>
<key>NSHighResolutionCapable</key><true/>
<key>CFBundleDocumentTypes</key>
<array>
<dict>
<key>CFBundleTypeName</key><string>Windows Executable</string>
<key>CFBundleTypeRole</key><string>Viewer</string>
<key>LSHandlerRank</key><string>Alternate</string>
<key>LSItemContentTypes</key>
<array><string>com.microsoft.windows-executable</string></array>
</dict>
</array>
</dict>
</plist>
PLIST
# Ad-hoc signature for local development only. No entitlements are requested:
# this build executes no guest code, so it needs no JIT entitlement.
codesign --force --sign - "$bundle"
binary="$bundle/Contents/MacOS/Xenora"
[ "$(lipo -archs "$binary")" = arm64 ] || fail "executable is not arm64-only: $(lipo -archs "$binary")"
"$binary" --smoke
echo "build-app: built $bundle"
+10
View File
@@ -25,6 +25,16 @@ cargo test --locked -p xenora-loader --features gpu-tests --test graphics_d3d12
timeout 30s cargo test --locked -p xenora-loader --features gpu-tests --test graphics_d3d12 -- \
--nocapture --test-threads=1
# The native app interface runs the trusted fixture's guest draw on Metal.
cargo test --locked -p xenora-ffi --features gpu-tests --test native_frame --no-run
timeout 30s cargo test --locked -p xenora-ffi --features gpu-tests --test native_frame -- \
--nocapture --test-threads=1
# The persistent frame loop runs the guest on its own thread and renders on Metal.
cargo test --locked -p xenora-ffi --features gpu-tests --test frame_loop --no-run
timeout 30s cargo test --locked -p xenora-ffi --features gpu-tests --test frame_loop -- \
--nocapture --test-threads=1
# Native Metal known answers of the independent semantic review, including SOP2 scalar ALU
# and VOPC compares.
cargo test --locked -p xenora-semantic-review --no-run
@@ -32,13 +32,14 @@ U32 = "FMT_NUM_U32"
I32 = "FMT_NUM_I32"
def _operands(data_format, scc_in=False):
def _operands(data_format, scc_in=False, src1_format=None, scc_out=True):
rows = [
["SDST", data_format, "OPR_SDST", 32, False, True, False, True],
["SSRC0", data_format, "OPR_SSRC_NOLDS", 32, True, False, False, True],
["SSRC1", data_format, "OPR_SSRC_NOLDS", 32, True, False, False, True],
["", "FMT_NUM_B1", "OPR_SSRC_SPECIAL_SCC", 1, False, True, True, True],
["SSRC1", src1_format or data_format, "OPR_SSRC_NOLDS", 32, True, False, False, True],
]
if scc_out:
rows.append(["", "FMT_NUM_B1", "OPR_SSRC_SPECIAL_SCC", 1, False, True, True, True])
if scc_in:
rows.append(["", "FMT_NUM_B1", "OPR_SSRC_SPECIAL_SCC", 1, True, False, True, True])
return rows
@@ -54,7 +55,9 @@ def snapshot():
["OP", [[23, 7]]], ["ENCODING", [[30, 2]]],
],
"identifier_mask": 0xFF800000,
"identifiers": [sop2_base | (op << 23) for op in (0, 2, 4, 14)],
"identifiers": [
sop2_base | (op << 23) for op in (0, 2, 4, 6, 10, 14, 34, 38, 40, 47, 53)
],
}
variants = {}
for name, opcode, operands in (
@@ -62,11 +65,65 @@ def snapshot():
("S_ADD_I32", 2, _operands(I32)),
("S_ADDC_U32", 4, _operands(U32, scc_in=True)),
("S_AND_B32", 14, _operands(U32)),
# The XML gives S_ASHR_I32 a signed S0 and an unsigned shift count.
("S_ASHR_I32", 34, _operands(I32, src1_format=U32)),
# Values copied from the AMD XML snapshot for the arithmetic fixture.
("S_MIN_I32", 6, _operands(I32)),
("S_CSELECT_B32", 10, _operands("FMT_NUM_B32", scc_in=True, scc_out=False)),
("S_MUL_I32", 38, _operands(I32, scc_out=False)),
("S_BFE_I32", 40, _operands(I32, src1_format=U32)),
("S_LSHL2_ADD_U32", 47, _operands(U32)),
("S_MUL_HI_U32", 53, _operands(U32, scc_out=False)),
):
variants[(name, "ENC_SOP2")] = {
"instruction": name, "encoding": "ENC_SOP2", "opcode": opcode, "operands": operands,
}
return {"source": {"sha256": SHA}, "encodings": {"ENC_SOP2": encoding}, "variants": variants}
sopc = {
"name": "ENC_SOPC",
"bits": 32,
"fields": [
["SSRC0", [[0, 8]]], ["SSRC1", [[8, 8]]], ["OP", [[16, 7]]], ["ENCODING", [[23, 9]]],
],
"identifier_mask": 0xFFFF0000,
"identifiers": [0xBF000000 | (op << 16) for op in (4, 10)],
}
for name, opcode, data_format in (("S_CMP_LT_I32", 4, I32), ("S_CMP_LT_U32", 10, U32)):
variants[(name, "ENC_SOPC")] = {
"instruction": name, "encoding": "ENC_SOPC", "opcode": opcode,
"operands": _operands(data_format)[1:],
}
sop1 = {
"name": "ENC_SOP1",
"bits": 32,
"fields": [
["SSRC0", [[0, 8]]], ["OP", [[8, 8]]], ["SDST", [[16, 7]]], ["ENCODING", [[23, 9]]],
],
"identifier_mask": 0xFF80FF00,
"identifiers": [0xBE800000 | (op << 8) for op in (7, 11, 25)],
}
def unary(dst, src, size, scc):
rows = [
["SDST", dst, "OPR_SDST", 32, False, True, False, True],
["SSRC0", src, "OPR_SSRC_NOLDS", size, True, False, False, True],
]
if scc:
rows.append(["", "FMT_NUM_B1", "OPR_SSRC_SPECIAL_SCC", 1, False, True, True, True])
return rows
for name, opcode, operands in (
("S_NOT_B32", 7, unary(U32, U32, 32, True)),
("S_BREV_B32", 11, unary(U32, U32, 32, False)),
("S_SEXT_I32_I8", 25, unary(I32, "FMT_NUM_I8", 8, False)),
):
variants[(name, "ENC_SOP1")] = {
"instruction": name, "encoding": "ENC_SOP1", "opcode": opcode, "operands": operands,
}
return {
"source": {"sha256": SHA},
"encodings": {"ENC_SOP2": encoding, "ENC_SOPC": sopc, "ENC_SOP1": sop1},
"variants": variants,
}
def _form(name, opcode, variant, operation, signedness, scc, carry_in="none"):
@@ -80,20 +137,76 @@ def _form(name, opcode, variant, operation, signedness, scc, carry_in="none"):
}
def unaries():
reg = registry()
rule = copy.deepcopy(gen.OPERAND_RULES["sop1_sgpr"]["shape"])
rule["unsupported"] = sorted(gen.OPERAND_RULES["sop1_sgpr"]["unsupported"])
reg["operand_rules"]["sop1_sgpr"] = rule
def unary(name, opcode, variant, operation, signedness, scc, **extra):
form = _form(name, opcode, variant, operation, signedness, scc)
form.update(family="SOP1", operands="sop1_sgpr", **extra)
return form
reg["form"] += [
unary("S_NOT_B32", 7, "NotB32", "not", "bitwise", "nonzero"),
unary("S_BREV_B32", 11, "BrevB32", "brev", "bitwise", "unchanged"),
unary("S_SEXT_I32_I8", 25, "SextI32I8", "sext", "signed", "unchanged", source_bits=8),
]
return reg
def ariths():
reg = registry()
reg["form"] += [
_form("S_MIN_I32", 6, "MinI32", "min", "signed", "selected_src0"),
_form("S_CSELECT_B32", 10, "CselectB32", "cselect", "bitwise", "unchanged", carry_in="scc"),
_form("S_MUL_I32", 38, "MulI32", "mul", "signed", "unchanged"),
_form("S_BFE_I32", 40, "BfeI32", "bfe", "signed", "nonzero"),
dict(
_form("S_LSHL2_ADD_U32", 47, "Lshl2AddU32", "lshl_add", "unsigned", "carry_out"),
shift_amount=2,
),
_form("S_MUL_HI_U32", 53, "MulHiU32", "mul_hi", "unsigned", "unchanged"),
]
return reg
def compares():
reg = registry()
reg["form"] += [
_compare("S_CMP_LT_I32", 4, "CmpLtI32", "lt", "signed"),
_compare("S_CMP_LT_U32", 10, "CmpLtU32", "lt", "unsigned"),
]
return reg
def _compare(name, opcode, variant, relation, signedness):
form = _form(name, opcode, variant, "compare", signedness, "relation")
form.update(family="SOPC", relation=relation, operands="sopc_scalar")
return form
def registry():
rule = copy.deepcopy(gen.OPERAND_RULES["sop2_sgpr"]["shape"])
rule["unsupported"] = sorted(gen.UNSUPPORTED_COMBOS)
compare_rule = copy.deepcopy(gen.OPERAND_RULES["sopc_scalar"]["shape"])
compare_rule["unsupported"] = sorted(gen.OPERAND_RULES["sopc_scalar"]["unsupported"])
return {
"schema": 1,
"architecture": "gfx1030",
"source_sha256": SHA,
"documents": copy.deepcopy(gen.PINNED_DOCUMENTS),
"operand_rules": {"sop2_sgpr": rule},
"operand_rules": {"sop2_sgpr": rule, "sopc_scalar": compare_rule},
"form": [
_form("S_ADD_U32", 0, "AddU32", "add", "unsigned", "carry_out"),
_form("S_ADD_I32", 2, "AddI32", "add", "signed", "signed_overflow"),
_form("S_ADDC_U32", 4, "AddcU32", "add", "unsigned", "carry_out", carry_in="scc"),
_form("S_AND_B32", 14, "AndB32", "and", "bitwise", "nonzero"),
dict(
_form("S_ASHR_I32", 34, "AshrI32", "ashr", "signed", "nonzero"),
shift_count_bits=5,
),
],
}
@@ -159,8 +272,8 @@ class Validate(unittest.TestCase):
def test_rejects_unknown_operation(self):
reg = registry()
form(reg, "S_ADD_U32")["operation"] = "mul"
self.rejects(reg, "S_ADD_U32: unknown operation 'mul'")
form(reg, "S_ADD_U32")["operation"] = "fma"
self.rejects(reg, "S_ADD_U32: unknown operation 'fma'")
def test_rejects_unknown_scc_effect(self):
reg = registry()
@@ -233,12 +346,14 @@ class Validate(unittest.TestCase):
reg = registry()
form(reg, "S_ADD_U32")["family"] = "SOPC"
self.rejects(reg, "S_ADD_U32: operand rule sop2_sgpr is for SOP2")
self.rejects(reg, "S_ADD_U32: family SOPC has no XML encoding ENC_SOPC")
self.rejects(reg, "S_ADD_U32: no default ENC_SOPC variant in the XML snapshot")
form(reg, "S_ADD_U32")["family"] = "SOPK"
self.rejects(reg, "S_ADD_U32: family SOPK has no XML encoding ENC_SOPK")
def test_rejects_form_absent_from_the_xml(self):
reg = registry()
reg["form"].append(_form("S_MUL_I32", 38, "MulI32", "add", "signed", "signed_overflow"))
self.rejects(reg, "S_MUL_I32: no default ENC_SOP2 variant in the XML snapshot")
reg["form"].append(_form("S_ABSDIFF_I32", 44, "AbsdiffI32", "absdiff", "signed", "nonzero"))
self.rejects(reg, "S_ABSDIFF_I32: no default ENC_SOP2 variant in the XML snapshot")
# ---- duplicates ----
@@ -288,6 +403,219 @@ class Validate(unittest.TestCase):
reg["operand_rules"]["sop2_sgpr"]["max_literals"] = 2
self.rejects(reg, "operand rule sop2_sgpr: declaration differs")
def test_rejects_a_shift_without_a_count_width(self):
reg = registry()
del reg["form"][-1]["shift_count_bits"]
self.rejects(reg, "S_ASHR_I32: shift_count_bits must be log2 of the width (32), got None")
def test_rejects_a_wrong_count_width(self):
reg = registry()
reg["form"][-1]["shift_count_bits"] = 6
self.rejects(reg, "S_ASHR_I32: shift_count_bits must be log2 of the width (32), got 6")
def test_rejects_a_count_width_on_a_non_shift(self):
reg = registry()
reg["form"][0]["shift_count_bits"] = 5
self.rejects(reg, "S_ADD_U32: shift_count_bits on a non-shift operation")
def test_rejects_a_signed_shift_count_in_the_xml(self):
snap = snapshot()
snap["variants"][("S_ASHR_I32", "ENC_SOP2")]["operands"] = _operands(I32)
self.rejects(registry(), "S_ASHR_I32: control operand SSRC1 has XML format FMT_NUM_I32", snap)
def test_rejects_a_float_shift_count_in_the_xml(self):
snap = snapshot()
snap["variants"][("S_ASHR_I32", "ENC_SOP2")]["operands"] = _operands(
I32, src1_format="FMT_NUM_F32"
)
self.rejects(registry(), "S_ASHR_I32: control operand SSRC1 has XML format FMT_NUM_F32", snap)
def test_rejects_a_float_source_format(self):
snap = snapshot()
snap["variants"][("S_AND_B32", "ENC_SOP2")]["operands"] = _operands("FMT_NUM_F32")
self.rejects(registry(), "S_AND_B32: signedness bitwise contradicts XML format FMT_NUM_F32", snap)
def test_rejects_a_negative_count_width(self):
reg = registry()
reg["form"][-1]["shift_count_bits"] = -1
self.rejects(reg, "S_ASHR_I32: shift_count_bits must be log2 of the width (32), got -1")
def test_rejects_an_unsigned_arithmetic_shift(self):
reg = registry()
reg["form"][-1]["signedness"] = "unsigned"
self.rejects(reg, "S_ASHR_I32: no primitive implements ashr/unsigned")
def test_renders_the_declared_count_mask(self):
self.assertIn(
"let (value, scc) = primitive::ashr_nonzero_i32(src0, src1 & 0x1f);",
gen.render(registry(), snapshot()),
)
def test_accepts_unaries(self):
self.assertEqual(self.errors(unaries()), [])
def test_rejects_a_sext_without_source_bits(self):
reg = unaries()
del reg["form"][-1]["source_bits"]
self.rejects(reg, "S_SEXT_I32_I8: source_bits must be one of [8, 16], got None")
def test_rejects_a_sext_whose_source_bits_contradict_the_xml(self):
reg = unaries()
reg["form"][-1]["source_bits"] = 16
self.rejects(reg, "S_SEXT_I32_I8: SSRC0 is 8 bits in the XML, declared 16")
self.rejects(reg, "S_SEXT_I32_I8: SSRC0 has XML format FMT_NUM_I8, not FMT_NUM_I16")
def test_rejects_source_bits_on_another_operation(self):
reg = unaries()
reg["form"][-2]["source_bits"] = 8
self.rejects(reg, "S_BREV_B32: source_bits on a non-sext operation")
def test_rejects_an_scc_write_the_xml_does_not_show(self):
reg = unaries()
reg["form"][-2]["operation"] = "not"
reg["form"][-2]["scc"] = "nonzero"
self.rejects(reg, "S_BREV_B32: scc nonzero contradicts the XML SCC output")
def test_rejects_a_unary_operation_under_a_binary_rule(self):
reg = unaries()
reg["form"][0]["operation"] = "not"
reg["form"][0]["scc"] = "nonzero"
self.rejects(reg, "S_ADD_U32: operation not does not fit rule sop2_sgpr")
def test_renders_unary_scc_as_optional(self):
text = gen.render(unaries(), snapshot())
self.assertIn("Self::BrevB32 => (primitive::brev_b32(src), None),", text)
self.assertIn("Self::SextI32I8 => (primitive::sext_i32(src, 8), None),", text)
self.assertIn("let (value, scc) = primitive::not_nonzero_b32(src);", text)
def test_accepts_ariths(self):
self.assertEqual(self.errors(ariths()), [])
def test_rejects_min_with_a_nonzero_scc(self):
reg = ariths()
form(reg, "S_MIN_I32")["scc"] = "nonzero"
self.rejects(reg, "S_MIN_I32: scc nonzero contradicts min/signed (requires selected_src0)")
def test_rejects_a_select_that_does_not_read_scc(self):
reg = ariths()
form(reg, "S_CSELECT_B32")["carry_in"] = "none"
self.rejects(reg, "S_CSELECT_B32: operation cselect reads SCC (requires carry_in scc)")
self.rejects(reg, "S_CSELECT_B32: carry_in none contradicts the XML SCC input")
def test_rejects_a_select_that_writes_scc(self):
reg = ariths()
form(reg, "S_CSELECT_B32")["scc"] = "nonzero"
self.rejects(reg, "S_CSELECT_B32: scc nonzero contradicts cselect/bitwise (requires unchanged)")
self.rejects(reg, "S_CSELECT_B32: scc nonzero contradicts the XML SCC output")
def test_rejects_a_typed_select(self):
reg = ariths()
form(reg, "S_CSELECT_B32")["signedness"] = "unsigned"
self.rejects(reg, "S_CSELECT_B32: signedness unsigned contradicts operation cselect")
def test_rejects_a_multiply_that_writes_scc(self):
reg = ariths()
form(reg, "S_MUL_I32")["scc"] = "signed_overflow"
self.rejects(reg, "S_MUL_I32: scc signed_overflow contradicts mul/signed (requires unchanged)")
def test_rejects_a_bitwise_multiply(self):
reg = ariths()
form(reg, "S_MUL_HI_U32")["signedness"] = "bitwise"
self.rejects(reg, "S_MUL_HI_U32: signedness bitwise contradicts operation mul_hi")
def test_rejects_a_signed_bfe_descriptor_in_the_xml(self):
snap = snapshot()
snap["variants"][("S_BFE_I32", "ENC_SOP2")]["operands"] = _operands(I32)
self.rejects(ariths(), "S_BFE_I32: control operand SSRC1 has XML format FMT_NUM_I32", snap)
def test_rejects_a_signed_bfe_data_operand_in_the_xml(self):
snap = snapshot()
snap["variants"][("S_BFE_I32", "ENC_SOP2")]["operands"] = _operands(U32)
self.rejects(ariths(), "S_BFE_I32: signedness signed contradicts XML format FMT_NUM_U32", snap)
def test_rejects_shift_add_without_or_with_a_wrong_amount(self):
for amount, shown in ((None, "None"), (0, "0"), (5, "5"), (True, "True"), ("2", "'2'")):
with self.subTest(amount=amount):
reg = ariths()
if amount is None:
del form(reg, "S_LSHL2_ADD_U32")["shift_amount"]
else:
form(reg, "S_LSHL2_ADD_U32")["shift_amount"] = amount
self.rejects(reg, f"S_LSHL2_ADD_U32: shift_amount must be one of [1, 2, 3, 4], got {shown}")
def test_rejects_a_shift_amount_on_another_operation(self):
reg = ariths()
form(reg, "S_MIN_I32")["shift_amount"] = 1
self.rejects(reg, "S_MIN_I32: shift_amount on a non-lshl_add operation")
def test_renders_alu_scc_as_optional_and_the_declared_data(self):
text = gen.render(ariths(), snapshot())
self.assertIn("Self::CselectB32 => (primitive::cselect_b32(src0, src1, scc_in), None),", text)
self.assertIn("Self::MulHiU32 => (primitive::mul_hi_u32(src0, src1), None),", text)
self.assertIn("let (value, scc) = primitive::lshl_add_carry_u32(src0, src1, 2);", text)
self.assertIn("let (value, scc) = primitive::min_i32(src0, src1);", text)
self.assertIn("Self::CselectB32 => true,", text.split("fn reads_scc", 1)[1].split("}", 1)[0])
self.assertIn("Self::CselectB32 => false,", text.split("fn writes_scc", 1)[1].split("}", 1)[0])
self.assertIn("shift_amount: 2,", text)
self.assertIn("scc: SccEffect::SelectedSrc0,", text)
def test_accepts_compares(self):
self.assertEqual(self.errors(compares()), [])
def test_rejects_a_compare_without_a_relation(self):
reg = compares()
del reg["form"][-1]["relation"]
self.rejects(reg, "S_CMP_LT_U32: unknown or missing relation None")
def test_rejects_an_unknown_relation(self):
reg = compares()
reg["form"][-1]["relation"] = "ne"
self.rejects(reg, "S_CMP_LT_U32: unknown or missing relation 'ne'")
def test_rejects_a_non_string_relation(self):
reg = compares()
reg["form"][-1]["relation"] = ["lt"]
self.rejects(reg, "S_CMP_LT_U32: unknown or missing relation ['lt']")
def test_rejects_a_rule_without_sources(self):
reg = compares()
del reg["operand_rules"]["sopc_scalar"]["src"]
self.rejects(reg, "operand rule sopc_scalar: declaration differs from the decoder's implemented rule")
def test_rejects_a_relation_on_a_non_compare(self):
reg = compares()
reg["form"][0]["relation"] = "lt"
self.rejects(reg, "S_ADD_U32: relation on a non-compare operation")
def test_rejects_a_compare_with_another_scc_effect(self):
reg = compares()
reg["form"][-1]["scc"] = "nonzero"
self.rejects(reg, "S_CMP_LT_U32: scc nonzero contradicts compare (requires relation)")
def test_rejects_a_bitwise_compare(self):
reg = compares()
reg["form"][-1]["signedness"] = "bitwise"
self.rejects(reg, "S_CMP_LT_U32: no primitive implements lt/bitwise")
def test_rejects_a_compare_whose_signedness_contradicts_the_xml(self):
reg = compares()
reg["form"][-1]["signedness"] = "signed"
self.rejects(reg, "S_CMP_LT_U32: signedness signed contradicts XML format FMT_NUM_U32")
def test_rejects_a_compare_under_an_alu_rule(self):
reg = compares()
reg["form"][0]["operation"] = "compare"
reg["form"][0]["relation"] = "lt"
reg["form"][0]["scc"] = "relation"
self.rejects(reg, "S_ADD_U32: operation compare does not fit rule sop2_sgpr")
def test_renders_compare_dispatch_and_relation(self):
text = gen.render(compares(), snapshot())
self.assertIn("if word & 0xff80_0000 != 0xbf00_0000 {", text)
self.assertIn("Self::CmpLtI32 => primitive::lt_i32(src0, src1),", text)
self.assertIn("Self::CmpLtU32 => primitive::lt_u32(src0, src1),", text)
self.assertIn("relation: Some(CompareRelation::Less),", text)
def test_rejects_an_incomplete_unsupported_list(self):
reg = registry()
reg["operand_rules"]["sop2_sgpr"]["unsupported"].remove("two_literals")
@@ -424,14 +752,24 @@ class Render(unittest.TestCase):
self.assertNotEqual(list(reg["form"][0]), list(reordered["form"][0]))
self.assertEqual(gen.render(reg, snapshot()), gen.render(reordered, snapshot()))
def test_dispatch_is_sorted_by_opcode(self):
def test_dispatch_table_is_indexed_by_opcode(self):
reg = registry()
reg["form"].reverse()
text = gen.render(reg, snapshot())
body = text.split("match word & ", 1)[1].split("_ => None", 1)[0]
words = [line.split(" => ")[0].strip() for line in body.splitlines()[1:] if "=>" in line]
self.assertEqual(words, sorted(words))
self.assertEqual(len(words), 4)
body = text.split("const SCALAR_ALU_OP_BY_OPCODE: [Option<ScalarAluOp>; 128] = [", 1)[1].split("];", 1)[0]
rows = [line.strip() for line in body.splitlines() if line.strip()]
self.assertEqual(len(rows), 128)
declared = {index: row for index, row in enumerate(rows) if row != "None,"}
self.assertEqual(sorted(declared), [0, 2, 4, 14, 34])
self.assertEqual(declared[34], "Some(ScalarAluOp::AshrI32),")
self.assertIn("if word & 0xc000_0000 != 0x8000_0000 {", text)
self.assertIn("SCALAR_ALU_OP_BY_OPCODE[((word >> 23) & 0x7f) as usize]", text)
def test_rejects_identifiers_that_do_not_share_the_encoding_bits(self):
snap = snapshot()
snap["encodings"]["ENC_SOP2"]["identifiers"].append(0x40000000)
with self.assertRaisesRegex(ValueError, "do not split into fixed bits and OP"):
gen.render(registry(), snap)
def test_real_registry_renders_the_committed_file(self):
text = gen.render(gen.load_registry(), gen.load_snapshot())
+231 -11
View File
@@ -8,9 +8,13 @@
//! field layout and executes them with an explicit program-counter machine, so
//! a defect in the production decoder or reference cannot cancel out here.
//!
//! Scope matches the demo fixtures: scalar move/compare/branch, SOP2 unsigned
//! Scope matches the demo fixtures: scalar move, eleven SOP1 unary forms
//! (NOT, BREV, BCNT0/1, FF0/1, FLBIT, FLBIT_I32, SEXT_I8/I16, ABS), the twelve SOPC 32-bit integer
//! compares, branch, SOP2 unsigned
//! and signed add and subtract, add-with-carry, subtract-with-borrow, AND, OR
//! and XOR, VOP1 move
//! and XOR, the stage C forms ANDN2, ORN2, NAND, NOR, XNOR, LSHL, LSHR and
//! ASHR (32-bit), the 32-bit integer forms MIN/MAX (I32, U32), CSELECT, BFM,
//! MUL_I32, BFE (U32, I32), ABSDIFF, LSHL1-4_ADD and MUL_HI (U32, I32), VOP1 move
//! (including from an SGPR),
//! VOP2 bitwise, shift, arithmetic-shift and float, VOP3 add-no-carry, MUBUF
//! load/store and the two waits plus `s_endpgm`. Anything else is a controlled
@@ -50,9 +54,13 @@ enum CmpSrc {
#[derive(Clone, Copy, Debug)]
enum Insn {
SMov(u8, Src),
/// SOP2 opcode 0-5, 14, 16 or 18.
/// SOP1 unary opcode 7, 11, 13, 15, 17, 19, 21, 23, 25, 26 or 52.
SUnary(u32, u8, Src),
/// SOP2 opcode 0-10, 14, 16, 18, an even opcode 20-36, 38-40, 44, 46-49,
/// 53 or 54.
SAlu(u32, u8, Src, Src),
SCmpEq(Src, Src),
/// SOPC opcode 0-11: `s_cmp_{eq,lg,gt,ge,lt,le}_i32` then `_u32`.
SCmp(u32, Src, Src),
BranchScc0(usize),
BranchMaskZero {
target: usize,
@@ -205,6 +213,20 @@ fn run_wave(program: &[(usize, Insn)], wave: &[u32]) -> Result<Vec<u32>, String>
None
})
}
Insn::SUnary(opcode, dst, src) => {
if dst < 8 {
Err(format!("{offset:#x}: write to a resource SGPR"))
} else {
read_s(&sgpr, src).map(|value| {
let (result, flag) = scalar_unary(opcode, value);
sgpr[dst as usize] = Some(result);
if let Some(flag) = flag {
scc = Some(flag);
}
None
})
}
}
Insn::SMov(dst, src) => {
if dst < 8 {
Err(format!("{offset:#x}: write to a resource SGPR"))
@@ -218,9 +240,9 @@ fn run_wave(program: &[(usize, Insn)], wave: &[u32]) -> Result<Vec<u32>, String>
})
}
}
Insn::SCmpEq(a, b) => read_s(&sgpr, a).and_then(|a| {
Insn::SCmp(opcode, a, b) => read_s(&sgpr, a).and_then(|a| {
read_s(&sgpr, b).map(|b| {
scc = Some(a == b);
scc = Some(scalar_compare(opcode, a, b));
None
})
}),
@@ -298,8 +320,87 @@ fn scalar_alu(
};
let (a, b) = (read(a)?, read(b)?);
let carry_in = || scc.ok_or_else(|| format!("{offset:#x}: uninitialized SCC"));
let bit = |word: u32, i: u32| (word >> i) & 1 == 1;
let (value, flag) = match opcode {
0 => ripple(a, b, false),
// RDNA 2 ISA guide 12.1: MIN/MAX pick S0 iff S0 < S1 (> for MAX), the
// order a borrow out of S0 - S1 (or S1 - S0) shows; signed forms flip
// both sign bits first. SCC = whether S0 was picked (0 on a tie).
6..=9 => {
let flip = if opcode % 2 == 0 { 0x8000_0000 } else { 0 };
let (x, y) = (a ^ flip, b ^ flip);
let (p, q) = if opcode < 8 { (x, y) } else { (y, x) };
let first = !ripple(p, !q, true).1;
(if first { a } else { b }, first)
}
// CSELECT: D = SCC ? S0 : S1.
10 => {
let pick_first = carry_in()?;
(if pick_first { a } else { b }, false)
}
// BFM: bit i of D is set iff S1[4:0] <= i < S1[4:0] + S0[4:0].
36 => {
let (size, start) = (a % 32, b % 32);
let value = (0..32)
.filter(|&i| i >= start && i < start + size)
.fold(0, |d, i| d | 1 << i);
(value, false)
}
// MUL_I32 and MUL_HI: the 64-bit unsigned product by shift and add;
// the signed high word subtracts S1 when S0 < 0 and S0 when S1 < 0
// (two's complement correction).
38 | 53 | 54 => {
let product = (0..32)
.filter(|&i| bit(b, i))
.fold(0_u64, |sum, i| sum + (u64::from(a) << i));
let (low, mut high) = (product as u32, (product >> 32) as u32);
if opcode == 54 {
if bit(a, 31) {
high = ripple(high, !b, true).0;
}
if bit(b, 31) {
high = ripple(high, !a, true).0;
}
}
(if opcode == 38 { low } else { high }, false)
}
// BFE: D[i] = S0[offset + i] for i < width (offset S1[4:0], width
// S1[22:16]); positions past bit 31 read 0 (U32) or S0[31] (I32), and
// I32 copies D[width - 1] into the bits at and above width. SCC = D != 0.
39 | 40 => {
let (start, width) = (b % 32, (b >> 16) % 128);
let source = |i: u32| match start + i {
at @ 0..=31 => bit(a, at),
_ => opcode == 40 && bit(a, 31),
};
let value = (0..32).fold(0, |d, i| {
let set = if i < width {
source(i)
} else {
opcode == 40 && width > 0 && source(width - 1)
};
d | u32::from(set) << i
});
(value, value != 0)
}
// ABSDIFF: the 32-bit S0 - S1, negated when bit 31 is set
// (0x80000000 stays). SCC = D != 0.
44 => {
let difference = ripple(a, !b, true).0;
let value = if bit(difference, 31) {
ripple(!difference, 0, true).0
} else {
difference
};
(value, value != 0)
}
// LSHLn_ADD, n = 1-4: D = (S0 << n) + S1; SCC = 1 iff the exact sum
// reaches 2^32, i.e. bits shifted out of S0 or a carry out of the add.
46..=49 => {
let n = opcode - 45;
let (value, carry) = ripple(a << n, b, false);
(value, carry || a >> (32 - n) != 0)
}
// RDNA 2 ISA guide 12.1: signed overflow from the sign bits,
// add: S0[31] == S1[31] != D[31]; subtract: S0[31] != S1[31] != D[31].
2 | 3 => {
@@ -320,6 +421,18 @@ fn scalar_alu(
let (value, carry) = ripple(a, !b, !borrow);
(value, !carry)
}
// RDNA 2 ISA guide 12.1: the shifts use only S1[4:0], taken here as
// the remainder modulo 32, and scale by a power of two in exact
// arithmetic; ASHR is floor division of the signed S0. SCC = D != 0.
30 | 32 | 34 => {
let scale = 1_i64 << (b % 32);
let value = match opcode {
30 => (i64::from(a) * scale).rem_euclid(1 << 32),
32 => i64::from(a) / scale,
_ => i64::from(a as i32).div_euclid(scale).rem_euclid(1 << 32),
} as u32;
(value, value != 0)
}
_ => {
let mut value = 0;
for bit in 0..32 {
@@ -327,7 +440,12 @@ fn scalar_alu(
let set = match opcode {
14 => x && y,
16 => x || y,
_ => x != y,
18 => x != y,
20 => x && !y,
22 => x || !y,
24 => !(x && y),
26 => !(x || y),
_ => x == y,
};
value |= u32::from(set) << bit;
}
@@ -335,10 +453,77 @@ fn scalar_alu(
}
};
sgpr[dst as usize] = Some(value);
*scc = Some(flag);
// CSELECT, BFM, MUL_I32 and MUL_HI have no SCC line in guide 12.1 ("n" in
// Tables 11, 12 and 14): SCC stays as it was, possibly unset.
if !matches!(opcode, 10 | 36 | 38 | 53 | 54) {
*scc = Some(flag);
}
Ok(())
}
/// RDNA 2 ISA guide 12.4: SCC = (S0 <relation> S1). Signed operands (opcodes
/// 0-5) are ordered by flipping both sign bits and comparing unsigned.
fn scalar_compare(opcode: u32, a: u32, b: u32) -> bool {
let (a, b) = if opcode < 6 {
(a ^ 0x8000_0000, b ^ 0x8000_0000)
} else {
(a, b)
};
match opcode % 6 {
0 => a == b,
1 => a != b,
2 => a > b,
3 => a >= b,
4 => a < b,
_ => a <= b,
}
}
/// RDNA 2 ISA guide 12.3, evaluated with arithmetic on the value (no host bit
/// intrinsics): D and, for NOT, BCNT0, BCNT1 and ABS, SCC = (D != 0).
fn scalar_unary(opcode: u32, value: u32) -> (u32, Option<bool>) {
// The bits from the LSB, as repeated halving produces them.
let mut bits = [false; 32];
let mut rest = u64::from(value);
for slot in &mut bits {
*slot = rest % 2 == 1;
rest /= 2;
}
let word = |bits: &dyn Fn(usize) -> bool| {
(0..32).rev().fold(0u64, |w, i| w * 2 + u64::from(bits(i))) as u32
};
let position = |found: Option<usize>| found.map_or(u32::MAX, |i| i as u32);
let ones = bits.iter().filter(|&&b| b).count() as u32;
let result = match opcode {
7 => 0xffff_ffff - value,
11 => word(&|i| bits[31 - i]),
13 => 32 - ones,
15 => ones,
17 => position(bits.iter().position(|&b| !b)),
19 => position(bits.iter().position(|&b| b)),
21 => position(bits.iter().rev().position(|&b| b)),
23 => position(
bits.iter()
.rev()
.skip(1)
.position(|&b| b != bits[31])
.map(|i| i + 1),
),
// signext of the low 8 or 16 bits: subtract 2^n when the value mod 2^n
// is at least 2^(n-1).
25 | 26 => {
let span = if opcode == 25 { 256 } else { 65_536 };
let low = i64::from(value) % span;
let signed = if low >= span / 2 { low - span } else { low };
signed.rem_euclid(1 << 32) as u32
}
// |S0| modulo 2^32, so INT_MIN stays 0x80000000.
_ => i64::from(value as i32).abs().rem_euclid(1 << 32) as u32,
};
let flag = matches!(opcode, 7 | 13 | 15 | 52).then_some(result != 0);
(result, flag)
}
fn read_vgpr(lane: &Lane, reg: u8, offset: usize) -> Result<u32, String> {
if reg == 0 {
return Err(format!("{offset:#x}: v0 is the resource index"));
@@ -786,6 +971,18 @@ fn decode_one(code: &[u8], offset: usize) -> Result<(Insn, usize), String> {
}
return Ok((Insn::VAddNc(first as u8, src0 as u8, src1 as u8), 8));
}
// SOP1: ENCODING 0b10_1111101 in bits 23-31, SDST 16-22, OP 8-15.
let sop1_op = (first >> 8) & 0xff;
if first >> 23 == 0b1_0111_1101
&& matches!(sop1_op, 7 | 11 | 13 | 15 | 17 | 19 | 21 | 23 | 25 | 26 | 52)
{
let dst = ((first >> 16) & 0x7f) as u8;
if dst > 105 {
return Err(fail("unsupported SOP1 destination"));
}
let (src, len) = scalar_source(code, offset, first as u8)?;
return Ok((Insn::SUnary(sop1_op, dst, src), len));
}
if first & 0xff80_ff00 == 0xbe80_0300 {
let dst = ((first >> 16) & 0x7f) as u8;
if dst > 107 && dst < 126 {
@@ -795,7 +992,29 @@ fn decode_one(code: &[u8], offset: usize) -> Result<(Insn, usize), String> {
return Ok((Insn::SMov(dst, src), len));
}
// SOP2: ENCODING 0b10 in bits 30-31, OP in bits 23-29, SDST in 16-22.
if first >> 30 == 0b10 && matches!((first >> 23) & 0x7f, 0..=5 | 14 | 16 | 18) {
if first >> 30 == 0b10
&& matches!(
(first >> 23) & 0x7f,
0..=10
| 14
| 16
| 18
| 20
| 22
| 24
| 26
| 28
| 30
| 32
| 34
| 36
| 38..=40
| 44
| 46..=49
| 53
| 54
)
{
let dst = ((first >> 16) & 0x7f) as u8;
if dst > 105 {
return Err(fail("unsupported SOP2 destination"));
@@ -808,7 +1027,8 @@ fn decode_one(code: &[u8], offset: usize) -> Result<(Insn, usize), String> {
let (sb, lb) = scalar_source(code, offset, b)?;
return Ok((Insn::SAlu((first >> 23) & 0x7f, dst, sa, sb), la.max(lb)));
}
if first & 0xffff_0000 == 0xbf06_0000 {
// SOPC: ENCODING 0b10_1111110 in bits 23-31, OP in 16-22.
if first >> 23 == 0b1_0111_1110 && (first >> 16) & 0x7f <= 11 {
let a = first as u8;
let b = (first >> 8) as u8;
if a == 255 && b == 255 {
@@ -816,7 +1036,7 @@ fn decode_one(code: &[u8], offset: usize) -> Result<(Insn, usize), String> {
}
let (sa, la) = scalar_source(code, offset, a)?;
let (sb, lb) = scalar_source(code, offset, b)?;
return Ok((Insn::SCmpEq(sa, sb), la.max(lb)));
return Ok((Insn::SCmp((first >> 16) & 0x7f, sa, sb), la.max(lb)));
}
if first & 0xffff_0000 == 0xbf82_0000 {
return Ok((Insn::Branch(branch_target(first, offset)?), 4));
+87 -3
View File
@@ -768,6 +768,18 @@ mod review {
}
const SCALAR_ALU_FIXTURE: &[u8] = include_bytes!("../../fixtures/rdna2/scalar-alu.bin");
const SCALAR_LOGIC_FIXTURE: &[u8] = include_bytes!("../../fixtures/rdna2/scalar-logic.bin");
// Hand-derived in fixtures/rdna2/scalar-logic.s from the guide's 12.1 pseudocode.
const SCALAR_LOGIC_KEY: u32 = 0x887f_00f8;
const SCALAR_COMPARE_FIXTURE: &[u8] = include_bytes!("../../fixtures/rdna2/scalar-compare.bin");
// Hand-derived in fixtures/rdna2/scalar-compare.s from the guide's 12.4 pseudocode.
const SCALAR_COMPARE_KEY: u32 = 0x0000_0d5b;
const SCALAR_UNARY_FIXTURE: &[u8] = include_bytes!("../../fixtures/rdna2/scalar-unary.bin");
// Hand-derived in fixtures/rdna2/scalar-unary.s from the guide's 12.3 pseudocode.
const SCALAR_UNARY_KEY: u32 = 0x0f00_80f5;
const SCALAR_ARITH_FIXTURE: &[u8] = include_bytes!("../../fixtures/rdna2/scalar-arith.bin");
// Hand-derived in fixtures/rdna2/scalar-arith.s from the guide's 12.1 pseudocode.
const SCALAR_ARITH_KEY: u32 = 0x8115_7dfe;
// SOP2 opcodes of the supported subset (RDNA 2 XML opcode table).
const SOP2_OPCODES: [u32; 9] = [0, 1, 2, 3, 4, 5, 14, 16, 18];
const SCALAR_VALUES: [u32; 10] = [
@@ -869,6 +881,70 @@ mod review {
verify(&nonzero, &input, Some(&[0; 5]));
}
#[test]
fn scalar_logic_fixture_chains_registry_logical_and_shift_forms() {
let input = [0, 1, u32::MAX, SCALAR_LOGIC_KEY, 0x1234_5678];
let expected: Vec<_> = input.iter().map(|word| word ^ SCALAR_LOGIC_KEY).collect();
verify(SCALAR_LOGIC_FIXTURE, &input, Some(&expected));
let compiled = compile(Architecture::Gfx1030, SCALAR_LOGIC_FIXTURE).unwrap();
assert!(compiled.disassembly.contains("s_ashr_i32 s17, s15, 31"));
// The SCC-zero edge is observable: with a shift count of 30 instead of
// 31, s17 = 0x787ffff8 >> 30 = 1, SCC = 1, and v2 = 0.
let mut nonzero = SCALAR_LOGIC_FIXTURE.to_vec();
let at = nonzero
.windows(4)
.position(|word| word == [0x0f, 0x9f, 0x11, 0x91])
.unwrap();
nonzero[at + 1] = 0x9e;
verify(&nonzero, &input, Some(&[0; 5]));
}
#[test]
fn scalar_compare_fixture_records_every_registry_compare() {
let input = [0, 1, u32::MAX, SCALAR_COMPARE_KEY, 0x1234_5678];
let expected: Vec<_> = input.iter().map(|word| word ^ SCALAR_COMPARE_KEY).collect();
verify(SCALAR_COMPARE_FIXTURE, &input, Some(&expected));
let compiled = compile(Architecture::Gfx1030, SCALAR_COMPARE_FIXTURE).unwrap();
assert!(compiled.disassembly.contains("s_cmp_le_u32 s9, 64"));
}
#[test]
fn scalar_unary_fixture_chains_registry_unary_forms() {
let input = [0, 1, u32::MAX, SCALAR_UNARY_KEY, 0x1234_5678];
let expected: Vec<_> = input.iter().map(|word| word ^ SCALAR_UNARY_KEY).collect();
verify(SCALAR_UNARY_FIXTURE, &input, Some(&expected));
let compiled = compile(Architecture::Gfx1030, SCALAR_UNARY_FIXTURE).unwrap();
assert!(compiled.disassembly.contains("s_abs_i32 s20, 0"));
// SCC stays clear across the SEXT and FF1 that follow s_abs_i32 s20, 0:
// with s_abs_i32 s20, 1 instead, SCC = 1 and v2 = 0.
let mut set = SCALAR_UNARY_FIXTURE.to_vec();
let at = set
.windows(4)
.position(|word| word == [0x80, 0x34, 0x94, 0xbe])
.unwrap();
set[at] = 0x81;
verify(&set, &input, Some(&[0; 5]));
}
#[test]
fn scalar_arith_fixture_chains_registry_arithmetic_forms() {
let input = [0, 1, u32::MAX, SCALAR_ARITH_KEY, 0x1234_5678];
let expected: Vec<_> = input.iter().map(|word| word ^ SCALAR_ARITH_KEY).collect();
verify(SCALAR_ARITH_FIXTURE, &input, Some(&expected));
let compiled = compile(Architecture::Gfx1030, SCALAR_ARITH_FIXTURE).unwrap();
assert!(compiled.disassembly.contains("s_lshl2_add_u32 s25, s9, s9"));
// SCC stays clear across the CSELECT and MUL_HI that follow
// s_lshl2_add_u32 s25, s9, s9: with s_lshl2_add_u32 s25, s9, -1 instead,
// 20 + 0xffffffff carries, SCC = 1 and v2 = 0.
let mut set = SCALAR_ARITH_FIXTURE.to_vec();
let at = set
.windows(4)
.position(|word| word == [0x09, 0x09, 0x99, 0x97])
.unwrap();
set[at + 1] = 0xc1;
verify(&set, &input, Some(&[0; 5]));
}
/// The translator's own folding: v2 = D as a constant, and the SCC-zero edge
/// is taken exactly when SCC is clear.
fn assert_translated(code: &[u8], expected: &[u32; 2]) {
@@ -1020,8 +1096,8 @@ mod review {
#[test]
fn scalar_alu_rejects_forms_outside_the_subset() {
// load 8, wait 4, two literal moves 8 each, s_cmp 4: the SOP2 word is at 0x20.
for opcode in [6, 15, 17, 19] {
// s_min_i32 and the 64-bit bitwise forms.
for opcode in [11, 15, 17, 19] {
// s_cselect_b64 and the 64-bit bitwise forms.
rejected_at(
&sop2_program(&[sop2(opcode, 10, 8, 9)], 10, 1, 2, Some(false)),
0x20,
@@ -1089,6 +1165,14 @@ mod review {
let input: Vec<u32> = (0..64).map(|lane| lane * 0x0101_0101).collect();
let expected: Vec<_> = input.iter().map(|word| word ^ 0x0000_000e).collect();
assert_eq!(run(SCALAR_ALU_FIXTURE, &input), expected);
let logic: Vec<_> = input.iter().map(|word| word ^ SCALAR_LOGIC_KEY).collect();
assert_eq!(run(SCALAR_LOGIC_FIXTURE, &input), logic);
let compares: Vec<_> = input.iter().map(|word| word ^ SCALAR_COMPARE_KEY).collect();
assert_eq!(run(SCALAR_COMPARE_FIXTURE, &input), compares);
let unary: Vec<_> = input.iter().map(|word| word ^ SCALAR_UNARY_KEY).collect();
assert_eq!(run(SCALAR_UNARY_FIXTURE, &input), unary);
let arith: Vec<_> = input.iter().map(|word| word ^ SCALAR_ARITH_KEY).collect();
assert_eq!(run(SCALAR_ARITH_FIXTURE, &input), arith);
let mut vectors = sop2_vectors();
vectors.extend(sop2_operand_cases());
vectors.extend(signed_immediate_overflows());
@@ -1097,7 +1181,7 @@ mod review {
}
eprintln!(
"{} SOP2 programs matched on native Metal",
vectors.len() + 1
vectors.len() + 5
);
}
+524
View File
@@ -0,0 +1,524 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Independent expected values for eleven 32-bit SOP1 unary forms (#215):
//! `s_not_b32`, `s_brev_b32`, `s_bcnt0_i32_b32`, `s_bcnt1_i32_b32`,
//! `s_ff0_i32_b32`, `s_ff1_i32_b32`, `s_flbit_i32_b32`, `s_flbit_i32`,
//! `s_sext_i32_i8`, `s_sext_i32_i16` and `s_abs_i32`.
//!
//! The expectations are written below from the public AMD "RDNA 2" Instruction
//! Set Architecture Reference Guide only: section 12.3 "SOP1 Instructions"
//! (pseudocode and functional examples), Tables 12 and 14 in section 5 (which
//! forms set SCC), section 13.1.3 for the SOP1 word and the scalar operand
//! table for inline integer constants. 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.
#[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 eleven forms with their ENC_SOP1 opcodes (guide 12.3).
#[derive(Clone, Copy, Debug, PartialEq)]
enum Form {
Not = 7,
Brev = 11,
Bcnt0 = 13,
Bcnt1 = 15,
Ff0 = 17,
Ff1 = 19,
FlbitB32 = 21,
FlbitI32 = 23,
SextI8 = 25,
SextI16 = 26,
Abs = 52,
}
const FORMS: [(Form, &str); 11] = [
(Form::Not, "s_not_b32"),
(Form::Brev, "s_brev_b32"),
(Form::Bcnt0, "s_bcnt0_i32_b32"),
(Form::Bcnt1, "s_bcnt1_i32_b32"),
(Form::Ff0, "s_ff0_i32_b32"),
(Form::Ff1, "s_ff1_i32_b32"),
(Form::FlbitB32, "s_flbit_i32_b32"),
(Form::FlbitI32, "s_flbit_i32"),
(Form::SextI8, "s_sext_i32_i8"),
(Form::SextI16, "s_sext_i32_i16"),
(Form::Abs, "s_abs_i32"),
];
fn bit(value: u32, i: u32) -> bool {
(value >> i) & 1 == 1
}
/// The guide's D for `form` with S0 = `s0`, and the SCC after it: `Some` for
/// the forms that write SCC, `None` for those that leave it unchanged. No form
/// reads SCC.
fn expect(form: Form, s0: u32) -> (u32, Option<bool>) {
// Tables 12 and 14: NOT, BCNT0, BCNT1 and ABS set SCC ("SCC = (D != 0)",
// "SCC=result not zero"); BREV, FF0, FF1, FLBIT and SEXT have "n".
let not_zero = |d: u32| (d, Some(d != 0));
match form {
// 7 S_NOT_B32: D = ~S0; SCC = (D != 0).
Form::Not => not_zero(!s0),
// 11 S_BREV_B32: D.u[31:0] = S0.u[0:31].
Form::Brev => (
(0..32).fold(0, |d, i| d | u32::from(bit(s0, 31 - i)) << i),
None,
),
// 13 S_BCNT0_I32_B32: D = 0; for i in 0..31: D += (S0[i] == 0 ? 1 : 0);
// SCC = (D != 0).
Form::Bcnt0 => not_zero((0..32).filter(|&i| !bit(s0, i)).count() as u32),
// 15 S_BCNT1_I32_B32: D += (S0[i] == 1 ? 1 : 0); SCC = (D != 0).
Form::Bcnt1 => not_zero((0..32).filter(|&i| bit(s0, i)).count() as u32),
// 17 S_FF0_I32_B32: D.i = -1; for i in 0..31 (from the LSB): if
// S0[i] == 0 then D.i = i; break.
Form::Ff0 => ((0..32).find(|&i| !bit(s0, i)).unwrap_or(u32::MAX), None),
// 19 S_FF1_I32_B32: D.i = -1; for i in 0..31: if S0[i] == 1 then
// D.i = i; break.
Form::Ff1 => ((0..32).find(|&i| bit(s0, i)).unwrap_or(u32::MAX), None),
// 21 S_FLBIT_I32_B32: D.i = -1; for i in 0..31: if S0[31 - i] == 1
// then D.i = i; break. (Zeros before the first one from the MSB.)
Form::FlbitB32 => ((0..32).find(|&i| bit(s0, 31 - i)).unwrap_or(u32::MAX), None),
// 23 S_FLBIT_I32: D.i = -1; for i in 1..31: if S0[31 - i] != S0[31]
// then D.i = i; break. Table 14: -1 if the input is 0 or -1.
Form::FlbitI32 => (
(1..32)
.find(|&i| bit(s0, 31 - i) != bit(s0, 31))
.unwrap_or(u32::MAX),
None,
),
// 25 S_SEXT_I32_I8: D.i = signext(S0.i[7:0]), i.e. { 24{S0[7]}, S0[7:0] }.
Form::SextI8 => (
if bit(s0, 7) {
s0 | 0xffff_ff00
} else {
s0 & 0xff
},
None,
),
// 26 S_SEXT_I32_I16: D.i = signext(S0.i[15:0]), i.e. { 16{S0[15]}, S0[15:0] }.
Form::SextI16 => (
if bit(s0, 15) {
s0 | 0xffff_0000
} else {
s0 & 0xffff
},
None,
),
// 52 S_ABS_I32: D.i = (S.i < 0 ? -S.i : S.i); SCC = (D.i != 0). The
// guide's example keeps 0x80000000 ("Note this is negative!").
Form::Abs => not_zero(if bit(s0, 31) {
(!s0).wrapping_add(1)
} else {
s0
}),
}
}
/// The functional examples printed in guide 12.3, with D only; the final five
/// are derived from the pseudocode, as their comment says.
const GUIDE_EXAMPLES: [(Form, u32, u32); 39] = [
(Form::Bcnt0, 0x0000_0000, 32),
(Form::Bcnt0, 0xcccc_cccc, 16),
(Form::Bcnt0, 0xffff_ffff, 0),
(Form::Bcnt1, 0x0000_0000, 0),
(Form::Bcnt1, 0xcccc_cccc, 16),
(Form::Bcnt1, 0xffff_ffff, 32),
(Form::Ff0, 0xaaaa_aaaa, 0),
(Form::Ff0, 0x5555_5555, 1),
(Form::Ff0, 0x0000_0000, 0),
(Form::Ff0, 0xffff_ffff, 0xffff_ffff),
(Form::Ff0, 0xfffe_ffff, 16),
(Form::Ff1, 0xaaaa_aaaa, 1),
(Form::Ff1, 0x5555_5555, 0),
(Form::Ff1, 0x0000_0000, 0xffff_ffff),
(Form::Ff1, 0xffff_ffff, 0),
(Form::Ff1, 0x0001_0000, 16),
(Form::FlbitB32, 0x0000_0000, 0xffff_ffff),
(Form::FlbitB32, 0x0000_cccc, 16),
(Form::FlbitB32, 0xffff_3333, 0),
(Form::FlbitB32, 0x7fff_ffff, 1),
(Form::FlbitB32, 0x8000_0000, 0),
(Form::FlbitB32, 0xffff_ffff, 0),
(Form::FlbitI32, 0x0000_0000, 0xffff_ffff),
(Form::FlbitI32, 0x0000_cccc, 16),
(Form::FlbitI32, 0xffff_3333, 16),
(Form::FlbitI32, 0x7fff_ffff, 1),
(Form::FlbitI32, 0x8000_0000, 1),
(Form::FlbitI32, 0xffff_ffff, 0xffff_ffff),
(Form::Abs, 0x0000_0001, 0x0000_0001),
(Form::Abs, 0x7fff_ffff, 0x7fff_ffff),
(Form::Abs, 0x8000_0000, 0x8000_0000),
(Form::Abs, 0x8000_0001, 0x7fff_ffff),
(Form::Abs, 0x8000_0002, 0x7fff_fffe),
(Form::Abs, 0xffff_ffff, 0x0000_0001),
// Not printed as examples; direct readings of the one-line pseudocode.
(Form::Not, 0x0f0f_0000, 0xf0f0_ffff),
(Form::Brev, 0x0000_0001, 0x8000_0000),
(Form::Brev, 0x1234_5678, 0x1e6a_2c48),
(Form::SextI8, 0x1234_5680, 0xffff_ff80),
(Form::SextI16, 0x1234_7fff, 0x0000_7fff),
];
/// Guide scalar operand table: 128 is 0, 129-192 are 1 to 64 and 193-208 are
/// -1 to -16, as 32-bit words.
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"),
}
}
const LITERAL: u32 = 255;
/// Boundaries, alternating patterns, the guide's example inputs and values
/// whose low 8 or 16 bits have the sign bit set (or just clear).
const VALUES: [u32; 24] = [
0,
1,
2,
0x7fff_ffff,
0x8000_0000,
0x8000_0001,
0xffff_fffe,
0xffff_ffff,
0xaaaa_aaaa,
0x5555_5555,
0xcccc_cccc,
0x0000_cccc,
0xffff_3333,
0xfffe_ffff,
0x0001_0000,
0x0000_007f,
0x0000_0080,
0x0000_00ff,
0x0000_7fff,
0x0000_8000,
0x0000_ffff,
0xffff_ff7f,
0x1234_8080,
0x1234_5678,
];
const INPUT: [u32; 2] = [0, u32::MAX];
const COUNTS: [(&str, usize); 7] = [
("sop1 domain", 11 * 24 * 2),
("sop1 single bit", 11 * 64 * 2),
("sop1 guide example", 39 * 2),
("sop1 inline integer", 11 * 81 * 2),
("sop1 literal", 11 * 6 * 2),
("sop1 aliasing", 11 * 3 * 2 * 2),
("sop1 max register", 11 * 3 * 2),
];
/// Per form: 6 destinations and 15 sources outside the supported subset.
const REJECTIONS: usize = 11 * (6 + 15);
/// ENCODING 0b10_1111101 in bits 23-31, SDST 16-22, OP 8-15, SSRC0 0-7
/// (guide 13.1.3).
fn sop1(op: u32, dst: u32, src0: u32) -> u32 {
0xbe80_0000 | dst << 16 | op << 8 | src0
}
/// The program around `alu`: load v1, `s_mov_b32` each `init` pair, set SCC to
/// `scc` with `s_and_b32 s12, x, x` (x = 1 or 0), run `alu`, then
/// v2 = s<result>, `s_cbranch_scc0` over `v_xor_b32 v2, v1, v2`, and store v2.
/// With the lane input [0, !0] the output is [R, R] when SCC is clear after
/// `alu` and [R, !R] when it is set.
fn program(init: &[(u32, u32)], scc: bool, alu: &[u32], result: u32) -> Vec<u8> {
let mut code = vec![0xe030_2000, 0x8000_0100, 0xbf8c_3f70];
for &(reg, value) in init {
code.extend([0xbe80_03ff | reg << 16, value]);
}
let x = if scc { 129 } else { 128 };
code.push(0x8000_0000 | 14 << 23 | 12 << 16 | x << 8 | x);
code.extend(alu);
code.extend([0x7e04_0200 | result, 0xbf84_0001, 0x3a04_0501]);
code.extend([0xe070_2000, 0x8001_0200, 0xbbfd_0000, 0xbf81_0000]);
words(&code)
}
/// The case for `form` with S0 = `s0` and SCC = `scc` before it, reading back
/// `result`, whose value afterwards is `r` (D unless another register is read).
#[allow(clippy::too_many_arguments)]
fn case(
(form, name): (Form, &'static str),
family: &'static str,
label: String,
code: Vec<u8>,
s0: u32,
scc: bool,
r: Option<u32>,
) -> Case {
let (d, written) = expect(form, s0);
let r = r.unwrap_or(d);
let label = format!("{name} {label}, scc before {scc}");
let scc = written.unwrap_or(scc);
Case {
form: name,
family,
label,
code,
input: INPUT.to_vec(),
expected: vec![r, if scc { !r } else { r }],
}
}
fn cases() -> Vec<Case> {
let mut cases = Vec::new();
for (form, name) in FORMS {
let op = form as u32;
for scc in [false, true] {
let single = (0..32).flat_map(|k| [1 << k, !(1 << k)]);
let values = VALUES.iter().map(|&v| (v, "sop1 domain"));
let examples = GUIDE_EXAMPLES
.iter()
.filter(|example| example.0 == form)
.map(|example| (example.1, "sop1 guide example"));
let all = values
.chain(single.map(|v| (v, "sop1 single bit")))
.chain(examples);
for (value, family) in all {
let code = program(&[(8, value)], scc, &[sop1(op, 10, 8)], 10);
let label = format!("{value:#x}");
cases.push(case((form, name), family, label, code, value, scc, None));
}
for selector in 128..=208 {
let value = inline_integer(selector);
let code = program(&[], scc, &[sop1(op, 10, selector)], 10);
let label = format!("inline {value:#x}");
cases.push(case(
(form, name),
"sop1 inline integer",
label,
code,
value,
scc,
None,
));
}
for value in [0, 1, 0x8000_0000, u32::MAX, 0x1234_8080, 0x0001_0000] {
let code = program(&[], scc, &[sop1(op, 10, LITERAL), value], 10);
let label = format!("literal {value:#x}");
cases.push(case(
(form, name),
"sop1 literal",
label,
code,
value,
scc,
None,
));
}
// s8 = op(s8), and s10 = op(s8) reading s8 back unchanged.
for value in [0x8000_0000, 0x0000_80ff, u32::MAX] {
let code = program(&[(8, value)], scc, &[sop1(op, 8, 8)], 8);
let label = format!("s8 = op s8 ({value:#x})");
cases.push(case(
(form, name),
"sop1 aliasing",
label,
code,
value,
scc,
None,
));
let code = program(&[(8, value)], scc, &[sop1(op, 10, 8)], 8);
let label = format!("s8 kept after s10 = op s8 ({value:#x})");
let kept = Some(value);
cases.push(case(
(form, name),
"sop1 aliasing",
label,
code,
value,
scc,
kept,
));
}
// The highest SGPR, s105 (0b1101001), as source, destination or both.
let value = 0x0000_8001;
for (dst, src, init) in [(105, 105, 105), (10, 105, 105), (105, 8, 8)] {
let code = program(&[(init, value)], scc, &[sop1(op, dst, src)], dst);
let label = format!("s{dst} = op s{src} ({value:#x})");
cases.push(case(
(form, name),
"sop1 max register",
label,
code,
value,
scc,
None,
));
}
}
}
cases
}
/// The SOP1 word's byte offset in `program` with one init pair.
const ALU_OFFSET: usize = 12 + 8 + 4;
/// Programs both interpreters must refuse at the SOP1 word.
fn rejections() -> Vec<(String, Vec<u8>)> {
let mut all = Vec::new();
for (form, name) in FORMS {
let op = form as u32;
// VCC_LO, VCC_HI, M0, NULL, EXEC_LO, EXEC_HI as SDST.
for dst in [106, 107, 124, 125, 126, 127] {
let code = program(&[(8, 1)], false, &[sop1(op, dst, 8)], 10);
all.push((format!("{name} destination {dst}"), code));
}
// VCC_LO, VCC_HI, M0, EXEC_LO, EXEC_HI, SCC, and the float inline
// constants 240-248 as SSRC0.
for src in [106, 107, 124, 126, 127, 253].into_iter().chain(240..=248) {
let code = program(&[(8, 1)], false, &[sop1(op, 10, src)], 10);
all.push((format!("{name} source {src}"), code));
}
}
all
}
fn assert_rejected_at_alu(label: &str, code: &[u8]) {
match xenora_ref::execute(code, &INPUT) {
Ok(_) => panic!("reference accepted {label}"),
Err(error) => assert_eq!(
error.offset, ALU_OFFSET,
"reference rejected {label} elsewhere"
),
}
match independent_ref::execute(code, &INPUT) {
Ok(_) => panic!("independent accepted {label}"),
Err(error) => assert!(
error.starts_with(&format!("{ALU_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<Vec<u32>, String>,
) -> Vec<String> {
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:?}, expected {:?}", 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<Case> {
let cases = cases();
assert_eq!(tally(&cases, |case| case.family), BTreeMap::from(COUNTS));
cases
}
#[test]
fn expectations_reproduce_the_guide_examples() {
for (form, s0, d) in GUIDE_EXAMPLES {
assert_eq!(expect(form, s0).0, d, "{form:?}({s0:#x})");
}
}
#[test]
fn sop1_unary_forms_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!("sop1_unary: {} reference cases", cases.len());
for (form, n) in tally(&cases, |case| case.form) {
eprintln!(" form {form}: {n}");
}
}
#[test]
fn sop1_unary_forms_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!("sop1_unary: {} independent-interpreter cases", cases.len());
}
#[test]
fn unsupported_sop1_operands_are_rejected() {
let rejections = rejections();
assert_eq!(rejections.len(), REJECTIONS);
for (label, code) in &rejections {
assert_rejected_at_alu(label, code);
}
eprintln!("sop1_unary: {} rejections", rejections.len());
}
#[test]
fn other_sop1_opcodes_stay_unsupported() {
// Every 8-bit SOP1 opcode except s_mov_b32 (3) and the eleven forms.
let supported: Vec<u32> = FORMS
.iter()
.map(|&(form, _)| form as u32)
.chain([3])
.collect();
for op in (0..=255).filter(|op| !supported.contains(op)) {
let code = program(&[(8, 1)], false, &[sop1(op, 10, 8)], 10);
assert_rejected_at_alu(&format!("opcode {op}"), &code);
}
}
#[test]
#[ignore = "requires a native Metal device with API and shader validation"]
fn sop1_unary_forms_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) in rejections() {
// A decode error at the SOP1 word, so a later failure cannot stand in.
match compile(Architecture::Gfx1030, &code) {
Err(CompileError::Decode(error)) => assert_eq!(
error.offset, ALU_OFFSET,
"compiler rejected {label} elsewhere: {error:?}"
),
other => panic!("compiler did not reject {label} at decode: {other:?}"),
}
}
let cases = checked_cases();
let (failures, programs) = harness::check_metal(&cases);
failures.assert_none("native Metal disagrees with the guide");
eprintln!(
"sop1_unary: {} Metal cases in {programs} programs",
cases.len()
);
}
+589
View File
@@ -0,0 +1,589 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Independent expected values for sixteen 32-bit SOP2 integer forms (#215):
//! `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`.
//!
//! The expectations are written below from the public AMD "RDNA 2" Instruction
//! Set Architecture Reference Guide only: section 12.1 "SOP2 Instructions"
//! (pseudocode and the ABSDIFF functional examples), Tables 11, 12 and 14 in
//! section 5 (which forms set SCC, and that CSELECT reads it), section 13.1.1
//! for the SOP2 word and the scalar operand table for inline integer
//! constants. 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.
//!
//! Reading of the pseudocode where the guide leaves C-like operators open:
//! arithmetic is exact (unbounded integers, as the guide's own
//! `>= 0x100000000ULL` carry tests require) and D keeps the low 32 bits. So a
//! BFE width of 32 or more gives an all-ones mask, and LSHLn_ADD's SCC is the
//! carry out of the whole `(S0 << N) + S1`, including bits shifted out of S0.
//! These are guide readings, not hardware evidence.
#[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 sixteen forms with their ENC_SOP2 opcodes (guide 12.1).
#[derive(Clone, Copy, Debug, PartialEq)]
enum Form {
MinI32 = 6,
MinU32 = 7,
MaxI32 = 8,
MaxU32 = 9,
Cselect = 10,
Bfm = 36,
Mul = 38,
BfeU32 = 39,
BfeI32 = 40,
Absdiff = 44,
Lshl1Add = 46,
Lshl2Add = 47,
Lshl3Add = 48,
Lshl4Add = 49,
MulHiU32 = 53,
MulHiI32 = 54,
}
const FORMS: [(Form, &str); 16] = [
(Form::MinI32, "s_min_i32"),
(Form::MinU32, "s_min_u32"),
(Form::MaxI32, "s_max_i32"),
(Form::MaxU32, "s_max_u32"),
(Form::Cselect, "s_cselect_b32"),
(Form::Bfm, "s_bfm_b32"),
(Form::Mul, "s_mul_i32"),
(Form::BfeU32, "s_bfe_u32"),
(Form::BfeI32, "s_bfe_i32"),
(Form::Absdiff, "s_absdiff_i32"),
(Form::Lshl1Add, "s_lshl1_add_u32"),
(Form::Lshl2Add, "s_lshl2_add_u32"),
(Form::Lshl3Add, "s_lshl3_add_u32"),
(Form::Lshl4Add, "s_lshl4_add_u32"),
(Form::MulHiU32, "s_mul_hi_u32"),
(Form::MulHiI32, "s_mul_hi_i32"),
];
/// BFE's S1 fields (guide 12.1): "S1[4:0] is field offset, S1[22:16] is field
/// width", so the width is seven bits (0-127) and bits 5-15 and 23-31 are
/// ignored.
fn field(s1: u32) -> (u32, u32) {
(s1 & 0x1f, (s1 >> 16) & 0x7f)
}
/// `(1 << width) - 1` in exact arithmetic.
fn mask(width: u32) -> i128 {
((1u128 << width) - 1) as i128
}
/// The guide's D for `form` with S0 = `s0`, S1 = `s1` and SCC = `scc` before
/// it, and the SCC after it: `Some` for the forms that write SCC, `None` for
/// those that leave it unchanged. Only CSELECT reads `scc`.
fn expect(form: Form, s0: u32, s1: u32, scc: bool) -> (u32, Option<bool>) {
let (i0, i1) = (i128::from(s0 as i32), i128::from(s1 as i32));
let (u0, u1) = (i128::from(s0), i128::from(s1));
// D keeps the low 32 bits of the exact result.
let low = |exact: i128| exact as u32;
let not_zero = |d: u32| (d, Some(d != 0));
match form {
// 6 S_MIN_I32: D.i = (S0.i < S1.i) ? S0.i : S1.i; SCC = (S0.i < S1.i).
// Equal operands give S1 (the same value) and SCC = 0; Table 11's
// "SCC = 1 if S0 was min" agrees only if a tie does not count as S0.
Form::MinI32 => (if i0 < i1 { s0 } else { s1 }, Some(i0 < i1)),
// 7 S_MIN_U32: D.u = (S0.u < S1.u) ? S0.u : S1.u; SCC = (S0.u < S1.u).
Form::MinU32 => (if u0 < u1 { s0 } else { s1 }, Some(u0 < u1)),
// 8 S_MAX_I32: D.i = (S0.i > S1.i) ? S0.i : S1.i; SCC = (S0.i > S1.i).
Form::MaxI32 => (if i0 > i1 { s0 } else { s1 }, Some(i0 > i1)),
// 9 S_MAX_U32: D.u = (S0.u > S1.u) ? S0.u : S1.u; SCC = (S0.u > S1.u).
Form::MaxU32 => (if u0 > u1 { s0 } else { s1 }, Some(u0 > u1)),
// 10 S_CSELECT_B32: D.u = SCC ? S0.u : S1.u. Table 12: "Sets SCC? n".
Form::Cselect => (if scc { s0 } else { s1 }, None),
// 36 S_BFM_B32: D.u = ((1 << S0.u[4:0]) - 1) << S1.u[4:0]. Table 14:
// "Sets SCC? n".
Form::Bfm => (low(mask(s0 & 0x1f) << (s1 & 0x1f)), None),
// 38 S_MUL_I32: D.i = S0.i * S1.i; Table 11: "Low 32 bits of result",
// "Sets SCC? n".
Form::Mul => (low(i0 * i1), None),
// 39 S_BFE_U32: D.u = (S0.u >> S1.u[4:0]) & ((1 << S1.u[22:16]) - 1);
// SCC = (D.u != 0). Width 0 gives 0; bits past bit 31 of S0 are 0.
Form::BfeU32 => {
let (offset, width) = field(s1);
not_zero(low((u0 >> offset) & mask(width)))
}
// 40 S_BFE_I32: D.i = signext((S0.i >> S1.u[4:0]) & ((1 << S1.u[22:16])
// - 1)); SCC = (D.i != 0). Section 5.7: "Bit Field Extract, then
// sign-extend result", i.e. from the field's top bit, width - 1. S0.i
// shifts arithmetically, so a field past bit 31 is filled with S0[31].
// Width 0 gives 0.
Form::BfeI32 => {
let (offset, width) = field(s1);
let bits = (i0 >> offset) & mask(width);
let d = if width > 0 && (bits >> (width - 1)) & 1 == 1 {
bits.wrapping_sub(1i128.wrapping_shl(width))
} else {
bits
};
not_zero(low(d))
}
// 44 S_ABSDIFF_I32: D.i = S0.i - S1.i; if (D.i < 0) D.i = -D.i;
// SCC = (D.i != 0). D.i is 32-bit: the functional examples give
// (0x80000000, 1) => 0x7fffffff and keep 0x80000000 for
// (0x80000000, 0), so the difference wraps before the negation.
Form::Absdiff => {
let d = (s0 as i32).wrapping_sub(s1 as i32);
not_zero(if d < 0 { d.wrapping_neg() } else { d } as u32)
}
// 46-49 S_LSHLn_ADD_U32: D.u = (S0.u << N) + S1.u; SCC = (((S0.u << N)
// + S1.u) >= 0x100000000ULL ? 1 : 0), N = 1, 2, 3, 4.
Form::Lshl1Add | Form::Lshl2Add | Form::Lshl3Add | Form::Lshl4Add => {
let n = form as u32 - 45;
let exact = (u0 << n) + u1;
(low(exact), Some(exact >= 1 << 32))
}
// 53 S_MUL_HI_U32: D.u = (S0.u * S1.u) >> 32. No SCC line.
Form::MulHiU32 => (low((u0 * u1) >> 32), None),
// 54 S_MUL_HI_I32: D.i = (S0.i * S1.i) >> 32 (signed). No SCC line.
Form::MulHiI32 => (low((i0 * i1) >> 32), None),
}
}
/// The ABSDIFF functional examples printed in guide 12.1, with D only, and
/// direct readings of other one-line pseudocode.
const GUIDE_EXAMPLES: [(Form, u32, u32, u32); 18] = [
(Form::Absdiff, 0x0000_0002, 0x0000_0005, 0x0000_0003),
(Form::Absdiff, 0xffff_ffff, 0x0000_0000, 0x0000_0001),
(Form::Absdiff, 0x8000_0000, 0x0000_0000, 0x8000_0000),
(Form::Absdiff, 0x8000_0000, 0x0000_0001, 0x7fff_ffff),
(Form::Absdiff, 0x8000_0000, 0xffff_ffff, 0x7fff_ffff),
(Form::Absdiff, 0x8000_0000, 0xffff_fffe, 0x7fff_fffe),
// Not printed as examples.
(Form::Bfm, 4, 8, 0x0000_0f00),
(Form::Bfm, 31, 1, 0xffff_fffe),
(Form::Bfm, 32, 0, 0),
(Form::BfeU32, 0x1234_5678, 0x0008_0004, 0x0000_0067),
(Form::BfeU32, 0x8000_0000, 0x0004_001f, 0x0000_0001),
(Form::BfeI32, 0x0000_0080, 0x0008_0000, 0xffff_ff80),
(Form::BfeI32, 0x8000_0000, 0x0004_001f, 0xffff_ffff),
(Form::BfeI32, 0x1234_5678, 0x0040_0000, 0x1234_5678),
(Form::MulHiU32, 0xffff_ffff, 0xffff_ffff, 0xffff_fffe),
(Form::MulHiI32, 0xffff_ffff, 0xffff_ffff, 0x0000_0000),
(Form::MulHiI32, 0x8000_0000, 0x8000_0000, 0x4000_0000),
(Form::Lshl4Add, 0x1000_0000, 0x0000_0001, 0x0000_0001),
];
/// Guide scalar operand table: 128 is 0, 129-192 are 1 to 64 and 193-208 are
/// -1 to -16, as 32-bit words.
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"),
}
}
const LITERAL: u32 = 255;
/// Boundaries, their neighbours and alternating patterns; all pairs include
/// the equal pairs that are MIN/MAX ties.
const VALUES: [u32; 13] = [
0,
1,
2,
0x7fff_ffff,
0x8000_0000,
0x8000_0001,
0xffff_fffe,
0xffff_ffff,
0xaaaa_aaaa,
0x5555_5555,
0x1234_5678,
0x0000_ffff,
0xffff_0000,
];
/// BFE widths around 0, 32 and the seven-bit field, and offsets around 0, 31
/// and the five-bit field.
const WIDTHS: [u32; 10] = [0, 1, 2, 8, 16, 31, 32, 33, 64, 127];
const OFFSETS: [u32; 8] = [0, 1, 4, 16, 28, 31, 32, 63];
/// S1 words with bit 23 (just above the width) or every ignored bit set.
const BFE_EXTRA: [u32; 2] = [0x0084_0004, 0xff80_ffe4];
/// BFM sizes and offsets around the five-bit fields.
const BFM_FIELDS: [u32; 9] = [0, 1, 4, 16, 31, 32, 33, 63, 0xffff_ffe1];
const INPUT: [u32; 2] = [0, u32::MAX];
const COUNTS: [(&str, usize); 7] = [
("sop2 arith domain", 16 * 13 * 13 * 2),
("sop2 arith bit field", (2 * 13 * (10 * 8 + 2) + 9 * 9) * 2),
("sop2 arith guide example", 18 * 2),
("sop2 arith aliasing", 16 * 2 * 5 * 2),
("sop2 arith inline integer", 16 * 81 * 2 * 2 * 2),
("sop2 arith literal", 16 * 6 * 2 * 2),
("sop2 arith max register", 16 * 4 * 2),
];
/// Per form: two literals, 6 destinations and 15 sources in each slot outside
/// the supported subset; and CSELECT with SCC never written.
const REJECTIONS: usize = 16 * (1 + 6 + 2 * 15) + 1 + 4;
/// ENCODING 0b10 in bits 30-31, OP 23-29, SDST 16-22, SSRC1 8-15, SSRC0 0-7
/// (guide 13.1.1).
fn sop2(op: u32, dst: u32, src0: u32, src1: u32) -> u32 {
0x8000_0000 | op << 23 | dst << 16 | src1 << 8 | src0
}
/// The program around `alu`: load v1, `s_mov_b32` each `init` pair, set SCC to
/// `scc` with `s_cmp_eq_u32` (or leave it unwritten for `None`), run `alu`, then
/// v2 = s<result>, XORed with v1 when SCC is set afterwards, and store v2. With
/// the lane input [0, !0] the output is [R, R] when SCC is clear after `alu`
/// and [R, !R] when it is set.
fn program(init: &[(u32, u32)], scc: Option<bool>, alu: &[u32], result: u32) -> Vec<u8> {
let mut code = vec![0xe030_2000, 0x8000_0100, 0xbf8c_3f70];
for &(reg, value) in init {
code.extend([0xbe80_03ff | reg << 16, value]);
}
match scc {
Some(true) => code.push(0xbf06_8080),
Some(false) => code.push(0xbf06_8180),
None => {}
}
code.extend(alu);
code.extend([0x7e04_0200 | result, 0xbf84_0001, 0x3a04_0501]);
code.extend([0xe070_2000, 0x8001_0200, 0xbbfd_0000, 0xbf81_0000]);
words(&code)
}
/// The case for `form` on `s0`, `s1` with SCC = `scc` before it, reading back
/// `result`, whose value afterwards is `r` (D unless another register is read).
#[allow(clippy::too_many_arguments)]
fn case(
(form, name): (Form, &'static str),
family: &'static str,
label: String,
code: Vec<u8>,
(s0, s1): (u32, u32),
scc: bool,
r: Option<u32>,
) -> Case {
let (d, written) = expect(form, s0, s1, scc);
let r = r.unwrap_or(d);
let label = format!("{name} {label}, scc before {scc}");
let scc = written.unwrap_or(scc);
Case {
form: name,
family,
label,
code,
input: INPUT.to_vec(),
expected: vec![r, if scc { !r } else { r }],
}
}
fn pairs(form: Form) -> Vec<(u32, u32, &'static str)> {
let mut all: Vec<_> = VALUES
.iter()
.flat_map(|&a| VALUES.map(|b| (a, b, "sop2 arith domain")))
.collect();
let family = "sop2 arith bit field";
if matches!(form, Form::BfeU32 | Form::BfeI32) {
let fields = WIDTHS
.iter()
.flat_map(|&w| OFFSETS.map(|o| w << 16 | o))
.chain(BFE_EXTRA);
let fields: Vec<_> = fields.collect();
all.extend(
VALUES
.iter()
.flat_map(|&a| fields.iter().map(move |&b| (a, b, family))),
);
}
if form == Form::Bfm {
all.extend(
BFM_FIELDS
.iter()
.flat_map(|&a| BFM_FIELDS.map(|b| (a, b, family))),
);
}
let examples = GUIDE_EXAMPLES.iter().filter(|example| example.0 == form);
all.extend(examples.map(|example| (example.1, example.2, "sop2 arith guide example")));
all
}
fn cases() -> Vec<Case> {
let mut cases = Vec::new();
for (form, name) in FORMS {
let op = form as u32;
for scc in [false, true] {
let alu = [sop2(op, 10, 8, 9)];
for (a, b, family) in pairs(form) {
let code = program(&[(8, a), (9, b)], Some(scc), &alu, 10);
let label = format!("{a:#x}, {b:#x}");
cases.push(case((form, name), family, label, code, (a, b), scc, None));
}
// dst/src aliasing with s8 = a, s9 = b.
for (a, b) in [(0xffff_fff0, 0x0008_0004), (0x8000_0001, 0x8000_0001)] {
for (dst, src0, src1) in [(8, 8, 9), (9, 8, 9), (8, 8, 8), (9, 9, 9), (8, 9, 8)] {
let pick = |reg| if reg == 8 { a } else { b };
let alu = [sop2(op, dst, src0, src1)];
let code = program(&[(8, a), (9, b)], Some(scc), &alu, dst);
let label = format!("s{dst} = s{src0}, s{src1} ({a:#x}, {b:#x})");
let operands = (pick(src0), pick(src1));
let family = "sop2 arith aliasing";
cases.push(case((form, name), family, label, code, operands, scc, None));
}
}
// Every integer inline constant (-16..64) in each source slot. The
// register operand s8 takes two words chosen so a wrong inline value
// changes D for at least one of them; as a BFE S1 they are fields
// (width 8, offset 0) and (width 32, offset 1).
let bfe = matches!(form, Form::BfeU32 | Form::BfeI32);
for selector in 128..=208 {
let value = inline_integer(selector);
for slot in 0..2 {
let others = if slot == 0 && bfe {
[0x0008_0000, 0x0020_0001]
} else {
[0x8000_0f0f, 0x7fff_f0f0]
};
for other in others {
let (alu, operands) = if slot == 0 {
(sop2(op, 10, selector, 8), (value, other))
} else {
(sop2(op, 10, 8, selector), (other, value))
};
let code = program(&[(8, other)], Some(scc), &[alu], 10);
let label = format!("inline {value:#x} in src{slot}, s8 {other:#x}");
let family = "sop2 arith inline integer";
cases.push(case((form, name), family, label, code, operands, scc, None));
}
}
}
// The highest SGPR, s105 (0b1101001), as destination, either
// source or all three; s8 and s105 differ in sign and as BFE fields.
let (a, b, top) = (0x0004_0001, 0x0003_0002, 0x8000_0006);
for (dst, src0, src1) in [(105, 8, 9), (10, 105, 8), (10, 8, 105), (105, 105, 105)] {
let pick = |reg| match reg {
8 => a,
9 => b,
_ => top,
};
let alu = [sop2(op, dst, src0, src1)];
let code = program(&[(8, a), (9, b), (105, top)], Some(scc), &alu, dst);
let label = format!("s{dst} = s{src0}, s{src1}");
let operands = (pick(src0), pick(src1));
let family = "sop2 arith max register";
cases.push(case((form, name), family, label, code, operands, scc, None));
}
// A 32-bit literal dword after the SOP2 word in each source slot.
for value in [0, 1, 0x7fff_ffff, 0x8000_0000, u32::MAX, 0x0021_0003] {
for slot in 0..2 {
let other = 0xc005_0003;
let (alu, operands) = if slot == 0 {
([sop2(op, 10, LITERAL, 8), value], (value, other))
} else {
([sop2(op, 10, 8, LITERAL), value], (other, value))
};
let code = program(&[(8, other)], Some(scc), &alu, 10);
let label = format!("literal {value:#x} in src{slot}");
let family = "sop2 arith literal";
cases.push(case((form, name), family, label, code, operands, scc, None));
}
}
}
}
cases
}
/// The SOP2 word's byte offset in `program` with two init pairs and the SCC
/// preset.
const ALU_OFFSET: usize = 12 + 16 + 4;
/// Programs both interpreters must refuse at the SOP2 word, with that offset.
fn rejections() -> Vec<(String, Vec<u8>, usize)> {
let init = [(8, 1), (9, 2)];
let mut all = Vec::new();
for (form, name) in FORMS {
let op = form as u32;
// Guide 12.1 (SOP2 note): at most one literal; two are refused.
let alu = [sop2(op, 10, LITERAL, LITERAL), 1];
let code = program(&init, Some(false), &alu, 10);
all.push((format!("{name} two literals"), code, ALU_OFFSET));
// VCC_LO, VCC_HI, M0, NULL, EXEC_LO, EXEC_HI as SDST.
for dst in [106, 107, 124, 125, 126, 127] {
let code = program(&init, Some(false), &[sop2(op, dst, 8, 9)], 10);
all.push((format!("{name} destination {dst}"), code, ALU_OFFSET));
}
// VCC_LO, VCC_HI, M0, EXEC_LO, EXEC_HI, SCC, and the float inline
// constants 240-248 in either source slot.
for src in [106, 107, 124, 126, 127, 253].into_iter().chain(240..=248) {
for (src0, src1, slot) in [(src, 9, 0), (8, src, 1)] {
let code = program(&init, Some(false), &[sop2(op, 10, src0, src1)], 10);
all.push((format!("{name} src{slot} {src}"), code, ALU_OFFSET));
}
}
}
// CSELECT reads SCC; here nothing has written it.
let code = program(&init, None, &[sop2(Form::Cselect as u32, 10, 8, 9)], 10);
all.push(("s_cselect_b32 with SCC unset".into(), code, ALU_OFFSET - 4));
// The forms that leave SCC unchanged must keep it unset, so a CSELECT after
// them is still refused (at the CSELECT, the second ALU word).
for form in [Form::Bfm, Form::Mul, Form::MulHiU32, Form::MulHiI32] {
let alu = [
sop2(form as u32, 10, 8, 9),
sop2(Form::Cselect as u32, 11, 8, 9),
];
let code = program(&init, None, &alu, 11);
all.push((
format!("{form:?} then s_cselect_b32 with SCC unset"),
code,
ALU_OFFSET,
));
}
all
}
fn assert_rejected_at(label: &str, code: &[u8], offset: usize) {
match xenora_ref::execute(code, &INPUT) {
Ok(_) => panic!("reference accepted {label}"),
Err(error) => assert_eq!(error.offset, offset, "reference rejected {label} elsewhere"),
}
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<Vec<u32>, String>,
) -> Vec<String> {
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:?}, expected {:?}", 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<Case> {
let cases = cases();
assert_eq!(tally(&cases, |case| case.family), BTreeMap::from(COUNTS));
cases
}
#[test]
fn expectations_reproduce_the_guide_examples() {
for (form, s0, s1, d) in GUIDE_EXAMPLES {
assert_eq!(
expect(form, s0, s1, false).0,
d,
"{form:?}({s0:#x}, {s1:#x})"
);
}
}
#[test]
fn sop2_arith_forms_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!("sop2_arith: {} reference cases", cases.len());
for (form, n) in tally(&cases, |case| case.form) {
eprintln!(" form {form}: {n}");
}
}
#[test]
fn sop2_arith_forms_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!("sop2_arith: {} independent-interpreter cases", cases.len());
}
#[test]
fn unsupported_sop2_arith_operands_are_rejected() {
let rejections = rejections();
assert_eq!(rejections.len(), REJECTIONS);
for (label, code, offset) in &rejections {
assert_rejected_at(label, code, *offset);
}
eprintln!("sop2_arith: {} rejections", rejections.len());
}
#[test]
fn other_sop2_opcodes_stay_unsupported() {
// Every SOP2 opcode (0-95; 96 and up are other encodings) except the
// earlier stages' forms (0-5 and the even opcodes 14-34) and these
// sixteen. Sources and destination are aligned pairs, all initialized, so
// a 64-bit form would read and write only set registers.
let earlier = (0..=5).chain((14..=34).step_by(2));
let supported: Vec<u32> = FORMS
.iter()
.map(|&(form, _)| form as u32)
.chain(earlier)
.collect();
let init = [(8, 1), (9, 2), (12, 3), (13, 4)];
for op in (0..=95).filter(|op| !supported.contains(op)) {
let code = program(&init, Some(false), &[sop2(op, 10, 8, 12)], 10);
assert_rejected_at(&format!("opcode {op}"), &code, 12 + 32 + 4);
}
}
#[test]
#[ignore = "requires a native Metal device with API and shader validation"]
fn sop2_arith_forms_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() {
// Refused at the same word as by the interpreters, so a later failure
// cannot stand in.
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!(
"sop2_arith: {} Metal cases in {programs} programs",
cases.len()
);
}
+328
View File
@@ -0,0 +1,328 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Independent expected values for the eight SOP2 forms added in #215 stage C:
//! `s_andn2_b32`, `s_orn2_b32`, `s_nand_b32`, `s_nor_b32`, `s_xnor_b32`,
//! `s_lshl_b32`, `s_lshr_b32` and `s_ashr_i32`.
//!
//! The expectations are written below from the public AMD "RDNA 2" Instruction
//! Set Architecture Reference Guide only: section 12.1 "SOP2 Instructions" for
//! D and SCC of each form, section 5.3 for the SCC rule of bit/logical
//! operations, and the scalar operand table (section 3) for inline integer
//! constants. 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.
#[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};
/// The eight stage C forms with their ENC_SOP2 opcodes (guide 12.1).
#[derive(Clone, Copy, Debug)]
enum Form {
Andn2 = 20,
Orn2 = 22,
Nand = 24,
Nor = 26,
Xnor = 28,
Lshl = 30,
Lshr = 32,
Ashr = 34,
}
const FORMS: [(Form, &str); 8] = [
(Form::Andn2, "s_andn2_b32"),
(Form::Orn2, "s_orn2_b32"),
(Form::Nand, "s_nand_b32"),
(Form::Nor, "s_nor_b32"),
(Form::Xnor, "s_xnor_b32"),
(Form::Lshl, "s_lshl_b32"),
(Form::Lshr, "s_lshr_b32"),
(Form::Ashr, "s_ashr_i32"),
];
/// The guide's D and SCC for `form` with S0 = `s0` and S1 = `s1`. None of
/// these forms reads SCC, so the value of SCC before the instruction is not an
/// input.
fn expect(form: Form, s0: u32, s1: u32) -> (u32, bool) {
let d = match form {
// 20 S_ANDN2_B32: D = S0 & ~S1; SCC = (D != 0).
Form::Andn2 => s0 & !s1,
// 22 S_ORN2_B32: D = S0 | ~S1; SCC = (D != 0).
Form::Orn2 => s0 | !s1,
// 24 S_NAND_B32: D = ~(S0 & S1); SCC = (D != 0).
Form::Nand => !(s0 & s1),
// 26 S_NOR_B32: D = ~(S0 | S1); SCC = (D != 0).
Form::Nor => !(s0 | s1),
// 28 S_XNOR_B32: D = ~(S0 ^ S1); SCC = (D != 0).
Form::Xnor => !(s0 ^ s1),
// 30 S_LSHL_B32: D.u = S0.u << S1.u[4:0]; SCC = (D.u != 0).
Form::Lshl => s0 << (s1 & 0x1f),
// 32 S_LSHR_B32: D.u = S0.u >> S1.u[4:0]; SCC = (D.u != 0).
Form::Lshr => s0 >> (s1 & 0x1f),
// 34 S_ASHR_I32: D.i = signext(S0.i) >> S1.u[4:0]; SCC = (D.i != 0).
// S1 is read as unsigned and only its low five bits count, so its
// sign never matters; the shift replicates S0's sign bit.
Form::Ashr => ((s0 as i32) >> (s1 & 0x1f)) as u32,
};
// Section 5.3: bit/logical operations set SCC = 1 iff the result is not zero.
(d, d != 0)
}
/// Guide section 3 scalar operand table: 128 is 0, 129-192 are 1 to 64 and
/// 193-208 are -1 to -16, as 32-bit words.
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"),
}
}
const LITERAL: u32 = 255;
/// Boundary operands and alternating bit patterns.
const VALUES: [u32; 8] = [
0,
1,
0x7fff_ffff,
0x8000_0000,
0xffff_ffff,
0xaaaa_aaaa,
0x5555_5555,
0x1234_5678,
];
/// Shift counts around the five-bit field, and one whose low bits are 1.
const SHIFTS: [u32; 7] = [0, 1, 31, 32, 33, 63, 0xffff_ffe1];
const INPUT: [u32; 2] = [0, u32::MAX];
const COUNTS: [(&str, usize); 5] = [
("stage c domain", 8 * 8 * 8 * 2),
("stage c shift count", 3 * 8 * 7 * 2),
("stage c aliasing", 8 * 2 * 5 * 2),
("stage c inline integer", 8 * 81 * 2 * 2 * 2),
("stage c literal", 8 * 6 * 2 * 2),
];
/// ENCODING 0b10 in bits 30-31, OP 23-29, SDST 16-22, SSRC1 8-15, SSRC0 0-7.
fn sop2(form: Form, dst: u32, src0: u32, src1: u32) -> u32 {
0x8000_0000 | (form as u32) << 23 | dst << 16 | src1 << 8 | src0
}
/// The program around `alu`: load v1, `s_mov_b32` each `init` pair, set SCC to
/// `scc` with `s_cmp_eq_u32`, run `alu`, then v2 = s<result>, XORed with v1
/// when SCC is set afterwards, and store v2. With the lane input [0, !0] the
/// output is [D, D] when SCC is clear and [D, !D] when it is set.
fn program(init: &[(u32, u32)], scc: bool, alu: &[u32], result: u32) -> Vec<u8> {
let mut code = vec![0xe030_2000, 0x8000_0100, 0xbf8c_3f70];
for &(reg, value) in init {
code.extend([0xbe80_03ff | reg << 16, value]);
}
code.push(if scc { 0xbf06_8080 } else { 0xbf06_8180 });
code.extend(alu);
code.extend([0x7e04_0200 | result, 0xbf84_0001, 0x3a04_0501]);
code.extend([0xe070_2000, 0x8001_0200, 0xbbfd_0000, 0xbf81_0000]);
words(&code)
}
fn case(
name: &'static str,
family: &'static str,
label: String,
code: Vec<u8>,
out: (u32, bool),
) -> Case {
let (d, scc) = out;
Case {
form: name,
family,
label: format!("{name} {label}"),
code,
input: INPUT.to_vec(),
expected: vec![d, if scc { !d } else { d }],
}
}
fn cases() -> Vec<Case> {
let mut cases = Vec::new();
for (form, name) in FORMS {
let shift = matches!(form, Form::Lshl | Form::Lshr | Form::Ashr);
for scc in [false, true] {
let alu = [sop2(form, 10, 8, 9)];
let pairs = VALUES
.iter()
.flat_map(|&a| VALUES.map(|b| (a, b, "stage c domain")));
let counts = VALUES
.iter()
.flat_map(|&a| SHIFTS.map(|b| (a, b, "stage c shift count")));
let counts: Vec<_> = if shift { counts.collect() } else { Vec::new() };
for (a, b, family) in pairs.chain(counts) {
let code = program(&[(8, a), (9, b)], scc, &alu, 10);
let label = format!("{a:#x}, {b:#x}, scc before {scc}");
cases.push(case(name, family, label, code, expect(form, a, b)));
}
// dst/src aliasing with s8 = a, s9 = b.
for (a, b) in [(0xffff_fff0, 0x21), (0x8000_0001, 0x8000_0001)] {
for (dst, src0, src1) in [(8, 8, 9), (9, 8, 9), (8, 8, 8), (9, 9, 9), (8, 9, 8)] {
let pick = |reg| if reg == 8 { a } else { b };
let code = program(&[(8, a), (9, b)], scc, &[sop2(form, dst, src0, src1)], dst);
let label =
format!("s{dst} = s{src0}, s{src1} ({a:#x}, {b:#x}), scc before {scc}");
let out = expect(form, pick(src0), pick(src1));
cases.push(case(name, "stage c aliasing", label, code, out));
}
}
// Every integer inline constant (-16..64) in each source slot. The
// register operand s8 takes a word and its complement, so a wrong
// inline value changes D for at least one of them (as a shift
// count it is 0x40 and 0x21, i.e. counts 0 and 1).
for selector in 128..=208 {
let value = inline_integer(selector);
for (slot, other) in [0, 1].into_iter().flat_map(|slot| {
let others = if slot == 0 && shift {
[0x40, 0x21]
} else {
[0x8000_0f0f, 0x7fff_f0f0]
};
others.map(|other| (slot, other))
}) {
let (alu, out) = if slot == 0 {
(sop2(form, 10, selector, 8), expect(form, value, other))
} else {
(sop2(form, 10, 8, selector), expect(form, other, value))
};
let code = program(&[(8, other)], scc, &[alu], 10);
let label =
format!("inline {value:#x} in src{slot}, s8 {other:#x}, scc before {scc}");
cases.push(case(name, "stage c inline integer", label, code, out));
}
}
// A 32-bit literal dword after the SOP2 word in each source slot.
for value in [0, 1, 0x7fff_ffff, 0x8000_0000, u32::MAX, 0xffff_ffe1] {
for slot in 0..2 {
let other = 0xc000_0003;
let (alu, out) = if slot == 0 {
(
[sop2(form, 10, LITERAL, 8), value],
expect(form, value, other),
)
} else {
(
[sop2(form, 10, 8, LITERAL), value],
expect(form, other, value),
)
};
let code = program(&[(8, other)], scc, &alu, 10);
let label = format!("literal {value:#x} in src{slot}, scc before {scc}");
cases.push(case(name, "stage c literal", label, code, out));
}
}
}
}
cases
}
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<Vec<u32>, String>,
) -> Vec<String> {
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:?}, expected {:?}", 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<Case> {
let cases = cases();
assert_eq!(tally(&cases, |case| case.family), BTreeMap::from(COUNTS));
cases
}
#[test]
fn stage_c_forms_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!("sop2_stage_c: {} reference cases", cases.len());
for (form, n) in tally(&cases, |case| case.form) {
eprintln!(" form {form}: {n}");
}
}
#[test]
fn stage_c_forms_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!(
"sop2_stage_c: {} independent-interpreter cases",
cases.len()
);
}
#[test]
fn odd_opcodes_beside_the_stage_c_forms_stay_unsupported() {
// The 64-bit neighbours (opcodes 21-35 odd) read aligned SGPR pairs
// (s[10:11] = s[8:9] op s[12:13], all initialized); neither interpreter
// supports them, so each must refuse the SOP2 word.
for op in (21..=35).step_by(2) {
let alu = [0x8000_0000 | op << 23 | 10 << 16 | 12 << 8 | 8];
let init = [(8, 1), (9, 2), (12, 3), (13, 4)];
let code = program(&init, false, &alu, 10);
assert!(
xenora_ref::execute(&code, &INPUT).is_err(),
"reference accepted opcode {op}"
);
assert!(
independent_ref::execute(&code, &INPUT).is_err(),
"independent accepted opcode {op}"
);
}
}
#[test]
#[ignore = "requires a native Metal device with API and shader validation"]
fn stage_c_forms_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"));
let cases = checked_cases();
let (failures, programs) = harness::check_metal(&cases);
failures.assert_none("native Metal disagrees with the guide");
eprintln!(
"sop2_stage_c: {} Metal cases in {programs} programs",
cases.len()
);
}
+397
View File
@@ -0,0 +1,397 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Independent expected values for the twelve SOPC 32-bit integer compares of
//! #215 stage D: `s_cmp_{eq,lg,gt,ge,lt,le}_{i32,u32}`.
//!
//! The expectations are written below from the public AMD "RDNA 2" Instruction
//! Set Architecture Reference Guide only: section 12.4 "SOPC Instructions" for
//! the SCC of each form, section 13.1.4 for the SOPC word, section 5.3 (compare
//! operations set SCC = 1 when true) and the scalar operand table for inline
//! integer constants. 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.
#[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, compile};
/// The twelve forms with their ENC_SOPC opcodes (guide 12.4, Table 70).
#[derive(Clone, Copy, Debug)]
enum Form {
EqI32 = 0,
LgI32 = 1,
GtI32 = 2,
GeI32 = 3,
LtI32 = 4,
LeI32 = 5,
EqU32 = 6,
LgU32 = 7,
GtU32 = 8,
GeU32 = 9,
LtU32 = 10,
LeU32 = 11,
}
const FORMS: [(Form, &str); 12] = [
(Form::EqI32, "s_cmp_eq_i32"),
(Form::LgI32, "s_cmp_lg_i32"),
(Form::GtI32, "s_cmp_gt_i32"),
(Form::GeI32, "s_cmp_ge_i32"),
(Form::LtI32, "s_cmp_lt_i32"),
(Form::LeI32, "s_cmp_le_i32"),
(Form::EqU32, "s_cmp_eq_u32"),
(Form::LgU32, "s_cmp_lg_u32"),
(Form::GtU32, "s_cmp_gt_u32"),
(Form::GeU32, "s_cmp_ge_u32"),
(Form::LtU32, "s_cmp_lt_u32"),
(Form::LeU32, "s_cmp_le_u32"),
];
/// The guide's SCC for `form` with S0 = `s0` (SSRC0, the left operand) and
/// S1 = `s1` (SSRC1). The compares write no SGPR and read no SCC.
fn expect(form: Form, s0: u32, s1: u32) -> bool {
let (i0, i1) = (s0 as i32, s1 as i32);
match form {
// 0 S_CMP_EQ_I32 and 6 S_CMP_EQ_U32 ("identical opcodes"): SCC = (S0 == S1).
Form::EqI32 | Form::EqU32 => s0 == s1,
// 1 S_CMP_LG_I32 and 7 S_CMP_LG_U32 ("identical opcodes"): SCC = (S0 != S1).
Form::LgI32 | Form::LgU32 => s0 != s1,
// 2 S_CMP_GT_I32: SCC = (S0.i > S1.i).
Form::GtI32 => i0 > i1,
// 3 S_CMP_GE_I32: SCC = (S0.i >= S1.i).
Form::GeI32 => i0 >= i1,
// 4 S_CMP_LT_I32: SCC = (S0.i < S1.i).
Form::LtI32 => i0 < i1,
// 5 S_CMP_LE_I32: SCC = (S0.i <= S1.i).
Form::LeI32 => i0 <= i1,
// 8 S_CMP_GT_U32: SCC = (S0.u > S1.u).
Form::GtU32 => s0 > s1,
// 9 S_CMP_GE_U32: SCC = (S0.u >= S1.u).
Form::GeU32 => s0 >= s1,
// 10 S_CMP_LT_U32: SCC = (S0.u < S1.u).
Form::LtU32 => s0 < s1,
// 11 S_CMP_LE_U32: SCC = (S0.u <= S1.u).
Form::LeU32 => s0 <= s1,
}
}
/// Guide scalar operand table: 128 is 0, 129-192 are 1 to 64 and 193-208 are
/// -1 to -16, as 32-bit words.
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"),
}
}
const LITERAL: u32 = 255;
/// Signed and unsigned boundaries and their neighbours.
const VALUES: [u32; 8] = [
0,
1,
0x7fff_fffe,
0x7fff_ffff,
0x8000_0000,
0x8000_0001,
0xffff_fffe,
0xffff_ffff,
];
/// The value s10 holds throughout; the output shows it unchanged.
const MARKER: u32 = 0x0f0f_1234;
const INPUT: [u32; 2] = [0, u32::MAX];
const COUNTS: [(&str, usize); 5] = [
("sopc domain", 12 * 8 * 8 * 2),
("sopc inline integer", 12 * 81 * 3 * 2),
("sopc literal", 12 * 5 * 3 * 2),
("sopc aliasing", 12 * 3),
("sopc no sgpr write", 12 * 5),
];
/// Per form: two literals, 5 special registers and 9 float inline constants in
/// each slot.
const REJECTIONS: usize = 12 * (1 + (5 + 9) * 2);
/// ENCODING 0b10_1111110 in bits 23-31, OP 16-22, SSRC1 8-15, SSRC0 0-7
/// (guide 13.1.4).
fn sopc(op: u32, src0: u32, src1: u32) -> u32 {
0xbf00_0000 | op << 16 | src1 << 8 | src0
}
/// The program around `alu`: load v1, `s_mov_b32` each `init` pair and
/// s10 = MARKER, set SCC to `scc` with `s_and_b32 s12, x, x` (x = 1 or 0, a
/// SOP2 form, so no compare is involved), run `alu`, then v2 = s<result>,
/// `s_cbranch_scc0` over `v_xor_b32 v2, v1, v2`, and store v2. With the lane
/// input [0, !0] the output is [R, R] when SCC is clear (branch taken) and
/// [R, !R] when it is set (fall through).
fn program(init: &[(u32, u32)], scc: bool, alu: &[u32], result: u32) -> Vec<u8> {
let mut code = vec![0xe030_2000, 0x8000_0100, 0xbf8c_3f70];
for &(reg, value) in init.iter().chain(&[(10, MARKER)]) {
code.extend([0xbe80_03ff | reg << 16, value]);
}
let x = if scc { 129 } else { 128 };
code.push(0x8000_0000 | 14 << 23 | 12 << 16 | x << 8 | x);
code.extend(alu);
code.extend([0x7e04_0200 | result, 0xbf84_0001, 0x3a04_0501]);
code.extend([0xe070_2000, 0x8001_0200, 0xbbfd_0000, 0xbf81_0000]);
words(&code)
}
fn case(
name: &'static str,
family: &'static str,
label: String,
code: Vec<u8>,
out: (u32, bool),
) -> Case {
let (r, scc) = out;
Case {
form: name,
family,
label: format!("{name} {label}"),
code,
input: INPUT.to_vec(),
expected: vec![r, if scc { !r } else { r }],
}
}
fn cases() -> Vec<Case> {
let mut cases = Vec::new();
for (form, name) in FORMS {
let op = form as u32;
for a in VALUES {
for b in VALUES {
for scc in [false, true] {
let code = program(&[(8, a), (9, b)], scc, &[sopc(op, 8, 9)], 10);
let label = format!("{a:#x}, {b:#x}, scc before {scc}");
let out = (MARKER, expect(form, a, b));
cases.push(case(name, "sopc domain", label, code, out));
}
}
}
// Every integer inline constant (-16..64) in each slot against a
// register that is negative as i32 and large as u32, then 32. SCC
// before is the opposite of the result, so a missing write shows.
for selector in 128..=208 {
let value = inline_integer(selector);
for other in [0xffff_fff8, 0x20, value] {
for slot in 0..2 {
let (alu, scc) = if slot == 0 {
(sopc(op, selector, 8), expect(form, value, other))
} else {
(sopc(op, 8, selector), expect(form, other, value))
};
let code = program(&[(8, other)], !scc, &[alu], 10);
let label = format!("inline {value:#x} in src{slot}, s8 {other:#x}");
cases.push(case(
name,
"sopc inline integer",
label,
code,
(MARKER, scc),
));
}
}
}
// A literal dword after the SOPC word in each slot.
for value in [0, 1, 0x7fff_ffff, 0x8000_0000, u32::MAX] {
for other in [0x7fff_ffff, 0x8000_0000, value] {
for slot in 0..2 {
let (alu, scc) = if slot == 0 {
([sopc(op, LITERAL, 8), value], expect(form, value, other))
} else {
([sopc(op, 8, LITERAL), value], expect(form, other, value))
};
let code = program(&[(8, other)], !scc, &alu, 10);
let label = format!("literal {value:#x} in src{slot}, s8 {other:#x}");
cases.push(case(name, "sopc literal", label, code, (MARKER, scc)));
}
}
}
// One register in both slots: S0 == S1.
for value in [0, 0x8000_0000, u32::MAX] {
let scc = expect(form, value, value);
let code = program(&[(8, value)], !scc, &[sopc(op, 8, 8)], 10);
let label = format!("s8, s8 = {value:#x}");
cases.push(case(name, "sopc aliasing", label, code, (MARKER, scc)));
}
// No SGPR is written: the sources, the marker and s11 (which a SOP2
// reading of the word would name as SDST for opcode 11) keep their
// values.
let (a, b) = (0x8000_0000, 1);
let scc = expect(form, a, b);
let init = [(8, a), (9, b), (11, 0x1111_1111)];
// s12 holds the SCC-setting AND result, 1 when SCC was set before.
let s12 = u32::from(!scc);
for (reg, value) in [(8, a), (9, b), (10, MARKER), (11, 0x1111_1111), (12, s12)] {
let code = program(&init, !scc, &[sopc(op, 8, 9)], reg);
let label = format!("s{reg} after s8 {a:#x}, s9 {b:#x}");
cases.push(case(name, "sopc no sgpr write", label, code, (value, scc)));
}
}
cases
}
/// The SOPC word's byte offset in `program` with `init` SGPR moves: three
/// header words, one 8-byte move per init pair and the marker, and the AND.
fn alu_offset(init: usize) -> usize {
12 + 8 * (init + 1) + 4
}
/// Both interpreters must refuse `code` at the SOPC word, not later.
fn assert_rejected_at_alu(label: &str, code: &[u8], init: usize) {
let offset = alu_offset(init);
match xenora_ref::execute(code, &INPUT) {
Ok(_) => panic!("reference accepted {label}"),
Err(error) => assert_eq!(error.offset, offset, "reference rejected {label} elsewhere"),
}
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}"
),
}
}
/// Programs both interpreters must refuse at the SOPC word, with the number
/// of init pairs before it.
fn rejections() -> Vec<(String, Vec<u8>, usize)> {
let mut all = Vec::new();
for (form, name) in FORMS {
let op = form as u32;
let code = program(&[], false, &[sopc(op, LITERAL, LITERAL), 1], 10);
all.push((format!("{name} two literals"), code, 0));
// VCC_LO, VCC_HI, M0, EXEC_LO, EXEC_HI, and the float inline
// constants 240-248 (0.5 .. 1/(2*pi)).
for selector in [106, 107, 124, 126, 127].into_iter().chain(240..=248) {
for slot in 0..2 {
let alu = if slot == 0 {
sopc(op, selector, 8)
} else {
sopc(op, 8, selector)
};
let code = program(&[(8, 1)], false, &[alu], 10);
all.push((format!("{name} source {selector} in src{slot}"), code, 1));
}
}
}
all
}
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<Vec<u32>, String>,
) -> Vec<String> {
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:?}, expected {:?}", 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<Case> {
let cases = cases();
assert_eq!(tally(&cases, |case| case.family), BTreeMap::from(COUNTS));
cases
}
fn reference(code: &[u8], input: &[u32]) -> Result<Vec<u32>, String> {
xenora_ref::execute(code, input).map_err(|error| format!("{error:?}"))
}
#[test]
fn stage_d_compares_match_the_guide_on_the_reference() {
let cases = checked_cases();
let failed = failures(&cases, reference);
assert!(
failed.is_empty(),
"reference disagrees with the guide:\n{}",
failed.join("\n")
);
eprintln!("sopc_stage_d: {} reference cases", cases.len());
for (form, n) in tally(&cases, |case| case.form) {
eprintln!(" form {form}: {n}");
}
}
#[test]
fn stage_d_compares_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!(
"sopc_stage_d: {} independent-interpreter cases",
cases.len()
);
}
#[test]
fn unsupported_compare_operands_are_rejected() {
let rejections = rejections();
assert_eq!(rejections.len(), REJECTIONS);
for (label, code, init) in &rejections {
assert_rejected_at_alu(label, code, *init);
}
eprintln!("sopc_stage_d: {} rejections", rejections.len());
}
#[test]
fn neighbouring_sopc_opcodes_stay_unsupported() {
// 12-15 are bit tests, 18-19 the 64-bit compares (guide 12.4); 16, 17 and
// 20-127 are not listed. Neither interpreter supports any of them.
for op in 12..=127 {
let code = program(&[(8, 1), (9, 2)], false, &[sopc(op, 8, 9)], 10);
assert_rejected_at_alu(&format!("opcode {op}"), &code, 2);
}
}
#[test]
#[ignore = "requires a native Metal device with API and shader validation"]
fn stage_d_compares_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, _) in rejections() {
assert!(
compile(Architecture::Gfx1030, &code).is_err(),
"compiler accepted {label}"
);
}
let cases = checked_cases();
let (failures, programs) = harness::check_metal(&cases);
failures.assert_none("native Metal disagrees with the guide");
eprintln!(
"sopc_stage_d: {} Metal cases in {programs} programs",
cases.len()
);
}