mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-26 11:00:43 +00:00
Compare commits
31
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0687a8add6 | ||
|
|
f856671b6d | ||
|
|
0609012903 | ||
|
|
dffa50cd9c | ||
|
|
b541dce0cc | ||
|
|
52ecece126 | ||
|
|
440856a997 | ||
|
|
1eeb614ea2 | ||
|
|
afd936b20b | ||
|
|
6772205213 | ||
|
|
4b5e2b690d | ||
|
|
ee6c9ac067 | ||
|
|
1680e6b19c | ||
|
|
3eef0ecfa8 | ||
|
|
999de9f2df | ||
|
|
e616583c3f | ||
|
|
025f9dfd21 | ||
|
|
d8c02270ee | ||
|
|
08c4451e68 | ||
|
|
2ab189ddbe | ||
|
|
fa94b56ba3 | ||
|
|
385e7a0729 | ||
|
|
819699e8a7 | ||
|
|
4404e3f4bb | ||
|
|
d35cea8eff | ||
|
|
8a69f80aa0 | ||
|
|
c21d9ba92a | ||
|
|
e06242f2e0 | ||
|
|
c9e3394eb3 | ||
|
|
72d2ceb967 | ||
|
|
358ddc5eba |
No files matched your search
@@ -38,6 +38,8 @@ jobs:
|
||||
- name: Check generated status and PE fixtures
|
||||
run: |
|
||||
python3 crates/isa/generate_rdna2_meta.py --check
|
||||
python3 crates/isa/generate_semantics.py --check
|
||||
python3 scripts/audit/semantic_coverage.py --check
|
||||
python3 scripts/audit/status.py --check
|
||||
for fixture in x2 x3 x4; do
|
||||
python3 "experiments/x1/fixtures/$fixture.py" --check || exit 1
|
||||
@@ -48,6 +50,10 @@ jobs:
|
||||
sh -n scripts/agent-queue.sh scripts/agent-sync.sh
|
||||
- name: Test pull request template check
|
||||
run: PYTHONPATH=scripts python3 -m unittest discover -s tests/pr_template
|
||||
- name: Test semantic registry generator and coverage report
|
||||
run: |
|
||||
python3 -m unittest discover -s tests/semantics_generator
|
||||
PYTHONPATH=scripts python3 -m unittest discover -s tests/semantic_coverage
|
||||
- name: Check formatting and lint
|
||||
run: |
|
||||
cargo fmt --all -- --check
|
||||
|
||||
@@ -11,6 +11,7 @@ remains unsupported.
|
||||
|
||||
### Added
|
||||
|
||||
- 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.
|
||||
- Added indexed triangle draws. Native Metal: `NativeCompute::render_indexed` issues one real `drawIndexedPrimitives` call per draw (up to 16) on a 16- or 32-bit index buffer with a start index and a signed base vertex, into an RGBA8 target; a draw can sample an original BC1 texture uploaded natively. Before encoding anything it rejects the whole pass for a bad index count, an index range past the buffer, any `index + base vertex` outside the vertex buffer, and, as this API's policy, a raw all-ones index (the primitive-restart value, which Metal does not define for triangle lists). Loader: a synthetic, CPU-side index buffer binding (resource handle and offset, the view running to the end of the resource) with `cmd_set_index_buffer` and `cmd_draw_indexed_instanced`, which fetch one triangle, drawn once, through the index buffer, start index and base vertex and pass it to the existing one-triangle backend; each drawn triangle replaces the previous output. Recording rejects formats other than DXGI `R16_UINT` and `R32_UINT`, offsets not aligned to the index size or past the resource, and unknown resources. Execution checks each draw in turn, so earlier draws have already rendered when a later one fails: index counts other than 0 or 3, more than one instance or a nonzero start instance, a missing index buffer, indices past the buffer and an `index + base vertex` outside the vertex buffer are typed errors; a valid zero index or instance count draws nothing. All-ones indices are ordinary indices there. Checked on the GPU with Metal validation in 16 passes (both index sizes, 32-bit indices above 16 bits, odd 16-bit start, positive and negative base vertex, reversed winding, flat and textured two-triangle draws, draw order, BC1-textured draws), compared per pixel against images derived independently from the geometry, the public D3D12 and Metal index semantics and the public BC1 rules, which a new CPU reference in `xenora-ref` also reproduces; the loader's fetch is checked against literal positions with synthetic guest-backed buffers and through the native Metal renderer. Synthetic fixtures only; no console index-buffer views, guest programs or console draw state are involved.
|
||||
- Added a `cpu_decode` cargo-fuzz target for the static x86-64 decoder used by the read-only PE probe. It places up to 4,096 fuzz bytes as the code section of a fixed, original PE32+ header and runs `probe_pe_bytes` twice with a bounded `ProbeConfig` (4,096 bytes, 2,048 instructions, 1,024 worklist entries); nothing is executed. It checks that the two reports are identical and that every decoded instruction is 1 to 15 bytes long, lies inside the code and matches the input bytes. A startup self-check aborts the run if the synthetic header stops reaching the decoder. A 600-second local campaign (nightly cargo-fuzz, one fork-mode worker, seeded from instruction bytes in the loader's probe tests; about 2.38 million executions, coverage 1,350 edges) found one decoder defect, reported to the CPU owner on #74 and not fixed here: the probe accepts unlimited FS/GS segment prefixes and reports instructions longer than 15 bytes (minimized input: 16 bytes of `0x65`). Run it with `rustup run nightly cargo fuzz run cpu_decode`; `scripts/fuzz.sh` does not list it yet.
|
||||
|
||||
@@ -2,13 +2,17 @@
|
||||
|
||||
**Experimental Xbox Series X|S emulation research for Apple Silicon Macs.**
|
||||
|
||||
Xenora is an open-source project written primarily in Rust, exploring native Xbox Series X|S compatibility on ARM64 macOS.
|
||||
|
||||
The project combines a bounded x86-64 guest execution environment, Portable Executable (PE32+) loading, AMD RDNA 2 shader translation, and a native Apple Metal graphics backend.
|
||||
Xenora is an open-source project written primarily in Rust that builds and verifies a native, bounded execution environment on Apple Silicon: an independent x86-64 guest path, original PE32+ loading, AMD RDNA 2 shader translation, and a native Apple Metal graphics backend.
|
||||
|
||||
**No Wine. No CrossOver. No Rosetta. No Vulkan runtime.**
|
||||
|
||||
Xenora is still experimental. It currently executes independently authored synthetic guest programs and shaders. **Commercial Xbox games, including Grand Theft Auto VI, do not boot.** Authentic Xbox executable loading and system-service compatibility remain unsupported.
|
||||
Xenora is still experimental. Verified work is restricted to independently authored synthetic programs and shaders; authentic Xbox executable loading, system-service compatibility and commercial game execution remain unsupported. See the [current limitations](#current-limitations).
|
||||
|
||||
### At a glance
|
||||
|
||||
- **Native graphics:** translated gfx1030 vertex and pixel stages and native passes (indexed draws, blend, depth) run on Apple Silicon GPUs — verified, see [Blend pass](#blend-pass) and [Verified Apple M5 results](#verified-apple-m5-results).
|
||||
- **Guest execution:** bounded x86-64 execution, original PE32+ loading, synthetic services and guest-driven GPU dispatch — verified milestones X1–X9.
|
||||
- **Not supported:** authentic Xbox executable loading and commercial game execution; see the [milestone table](#development-milestones).
|
||||
|
||||
[](https://github.com/ranveersoni98/Xenora/actions/workflows/ci.yml)
|
||||
|
||||
@@ -18,7 +22,7 @@ Xenora is still experimental. It currently executes independently authored synth
|
||||
|
||||
Xenora has progressed from executing individual x86-64 instructions to running original PE32+ guest programs that interact with translated GPU workloads on Apple Silicon.
|
||||
|
||||
The latest verified milestone includes **translated gfx1030 vertex and pixel shaders executing through native Apple Metal**, with rendered pixels compared against independently calculated reference results.
|
||||
The latest verified milestones include **translated gfx1030 vertex and pixel shaders executing through native Apple Metal**, the native Metal **blend pass** (`NativeCompute::render_blend`) and **indexed triangle draws** (`NativeCompute::render_indexed`) into offscreen targets, with rendered pixels compared against independently calculated reference results.
|
||||
|
||||
### Development milestones
|
||||
|
||||
@@ -33,14 +37,14 @@ The latest verified milestone includes **translated gfx1030 vertex and pixel sha
|
||||
| X7 — Imported services | Named imports, guest-to-host service dispatch and result validation | Verified |
|
||||
| X8 — Translated compute | Original gfx1030 compute shaders executing on Metal, partial Wave32 handling and BC1 readback | Verified subset |
|
||||
| X9 — Translated graphics | Persistent resource handles, translated vertex/pixel stages and offscreen Metal rendering | Verified subset |
|
||||
| X10 — Texture sampling | Translate RDNA2 image instructions, implement samplers, mipmapping and guest-backed texture bindings | Planned |
|
||||
| X11 — Graphics pipeline | Multiple draw calls, vertex buffers, index buffers, depth/stencil testing, blending and render targets | Planned |
|
||||
| X10 — Texture sampling | Translated image instructions are still planned; upload, readback and decode of BC compressed formats is implemented (see [Texture support](#texture-support)) | Planned |
|
||||
| X11 — Graphics pipeline | Bounded multi-draw passes into offscreen RGBA8 targets: translated vertex and pixel stages, indexed triangle draws, colour write masks and blend state | Implemented |
|
||||
| X12 — Wave execution | Expand Wave32/Wave64 semantics, divergent control flow, cross-lane operations, LDS and barriers | Planned |
|
||||
| X13 — Advanced shaders | Mesh, geometry and additional compute shader capabilities with verified Metal execution | Planned |
|
||||
| X14 — CPU recompilation | Native ARM64 dynamic recompilation of supported x86-64 instructions in synthetic fixtures | Implemented subset |
|
||||
| X15 — Executable compatibility | Static PE inspection reports sections, relocations, thread-local storage (TLS) callbacks, imports and entry-point instructions | Static probe implemented |
|
||||
| X16 — Guest memory and threading | Virtual memory mapping, thread scheduling, synchronization primitives and atomic operations | Implemented subset |
|
||||
| X17 — System services | Implement a tested subset of Xbox-compatible runtime APIs, memory services, filesystem access and application lifecycle | Implemented subet |
|
||||
| X17 — System services | Implement a tested subset of Xbox-compatible runtime APIs, memory services, filesystem access and application lifecycle | Implemented subset |
|
||||
| X18 — Graphics API translation | Translate supported Xbox graphics commands, resource descriptors, command queues, barriers and fences into Metal operations | Planned |
|
||||
| X19 — Advanced GPU features | Indirect rendering, asynchronous compute, additional texture formats and ray-tracing compatibility research | Planned |
|
||||
| X20 — Integrated guest runtime | Connect CPU recompilation, executable loading, system services and graphics translation into one persistent runtime | Planned |
|
||||
@@ -97,14 +101,35 @@ The current graphics subset supports:
|
||||
- Offscreen RGBA8 render targets.
|
||||
- Native GPU readback and pixel-by-pixel validation.
|
||||
- Explicit rejection of unsupported shader forms.
|
||||
- Flat-coloured triangle draws with colour write masks and blending (see [Blend pass](#blend-pass)).
|
||||
- Indexed triangle draws (see [Indexed draws](#indexed-draws)).
|
||||
- Depth testing with an optional `Depth32Float` attachment (see [Depth pass](#depth-pass)).
|
||||
|
||||
These are genuine translated shader stages, not merely demonstrations using handwritten Metal vertex and fragment programs.
|
||||
|
||||
The current rendering tests are deliberately narrow: original fixtures, a single triangle per draw, and controlled shader inputs and outputs.
|
||||
|
||||
### Blend pass
|
||||
|
||||
`NativeCompute::render_blend` draws up to 16 flat-coloured triangles in order into an offscreen RGBA8 target. Each draw has 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). Colours are compared per channel against images derived independently (in exact fractions) from the public Metal blend equations.
|
||||
|
||||
GPU verification (Metal API and shader validation enabled): 39 Metal-validated 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; and a pass whose first draw is itself blended and masked. On an Apple M5 Pro every rounded channel matched round-to-nearest exactly.
|
||||
|
||||
### Indexed draws
|
||||
|
||||
`NativeCompute::render_indexed` issues one real `drawIndexedPrimitives` call per draw (up to 16) on a 16- or 32-bit index buffer with a start index and a signed base vertex, into an offscreen RGBA8 target. A draw can sample an original BC1 texture uploaded natively.
|
||||
|
||||
GPU verification (Metal API and shader validation enabled): 16 Metal-validated passes (both index sizes, 32-bit indices above 16 bits, odd 16-bit start, positive and negative base vertex, reversed winding, flat and textured two-triangle draws, draw order, BC1-textured draws), compared per pixel against images derived independently from the geometry, the public D3D12 and Metal index semantics and the public BC1 rules.
|
||||
|
||||
### Depth pass
|
||||
|
||||
`NativeCompute::render_depth` draws up to 16 triangles in order into an offscreen RGBA8 target with an optional `Depth32Float` attachment, a chosen clear depth, a per-draw depth compare function (all eight) and depth write enable. Colour and the stored depth are both read back.
|
||||
|
||||
GPU verification (Metal API and shader validation enabled): 30 Metal-validated passes of original overlapping triangles: clear, every compare function at three depths, write enabled and disabled, depth test disabled with an attachment and no attachment at all, and a BC1-textured draw.
|
||||
|
||||
### Verified Apple M5 results
|
||||
|
||||
The X9 native Metal acceptance run reported **20 passing tests, zero failures and zero ignored tests**, with Metal API and GPU validation enabled.
|
||||
The X9 native Metal acceptance run reported **20 passing tests, zero failures and zero ignored tests**, with Metal API and GPU validation enabled. The newer passes below are separate Metal-validated campaigns, also with Metal API and shader validation enabled.
|
||||
|
||||
Representative checks include:
|
||||
|
||||
@@ -115,6 +140,9 @@ Representative checks include:
|
||||
| Perspective interpolation | Exact checks of 16 pixels and another 16 after swapping vertex color channels |
|
||||
| BC1 texture handling | 33 texels across selected mip levels and array layers |
|
||||
| Guest rendering | PE32+ guest receives and checks the translated render output |
|
||||
| Blend pass | 39 Metal-validated passes over two overlapping triangles |
|
||||
| Indexed draws | 16 Metal-validated passes (both index sizes, signed base vertices, draw order) |
|
||||
| Depth pass | 30 Metal-validated passes (all eight compare functions, no-attachment case) |
|
||||
|
||||
The expected results were calculated independently of the production shader translation path.
|
||||
|
||||
@@ -141,20 +169,20 @@ The resource system remains experimental. Native GPU work already in flight duri
|
||||
|
||||
## Texture support
|
||||
|
||||
Xenora includes an original BC1 texture-processing path.
|
||||
Xenora includes original texture upload, readback and block-compression paths.
|
||||
|
||||
Implemented and tested functionality includes:
|
||||
|
||||
- Validated mip levels and array layers.
|
||||
- Pitched texture uploads.
|
||||
- Block-compressed texture handling.
|
||||
- Block-compressed texture handling, including BC4/BC5 upload and readback and a CPU BC7 decoder for the eight modes.
|
||||
- Native Metal texture readback.
|
||||
- Edge-block and transparency tests.
|
||||
- Invalid descriptor and bounds rejection.
|
||||
|
||||
**Translated texture-sampling instructions are not yet implemented.**
|
||||
|
||||
The existing texture readback path uses an authored Metal kernel. It should not be confused with executing arbitrary RDNA2 texture-fetch instructions.
|
||||
The existing texture readback path uses authored Metal kernels. It should not be confused with executing arbitrary RDNA2 texture-fetch instructions.
|
||||
|
||||
Xbox-specific texture layouts and additional compression formats require further research and validation.
|
||||
|
||||
@@ -209,6 +237,8 @@ flowchart TD
|
||||
|
||||
Xenora's host execution environment is native ARM64. The guest architecture being interpreted is x86-64.
|
||||
|
||||
The native graphics pipeline runs translated vertex and pixel stages, the indexed-draw and blend passes and the depth pass into offscreen Metal targets, with GPU readback compared against independent CPU references.
|
||||
|
||||
The project does not currently provide a general-purpose x86-64 dynamic recompiler or a complete Xbox operating-system implementation.
|
||||
|
||||
See [Interface Contracts](docs/interfaces.md) for the documented execution and resource boundaries.
|
||||
@@ -227,8 +257,8 @@ The following remain unsupported or incomplete:
|
||||
| Executable loader | General relocations, TLS, DLL initialization and authentic Xbox startup |
|
||||
| Xbox runtime | Console-specific services, system APIs, filesystem and application lifecycle |
|
||||
| RDNA2 shaders | General control flow, broader instructions, Wave64, cross-lane operations and mesh stages |
|
||||
| Graphics | Translated texture sampling, broader resource binding, synchronization and general draw workloads |
|
||||
| Textures | Authentic Xbox memory layouts and broader compressed-format support |
|
||||
| Graphics | Translated texture sampling and broader resource binding |
|
||||
| Textures | Authentic Xbox memory layouts and translated sampling |
|
||||
| Performance | Production-scale workloads, CPU/GPU profiling and optimized execution |
|
||||
| Game compatibility | No demonstrated execution of commercial Xbox titles |
|
||||
|
||||
@@ -272,6 +302,10 @@ cargo clippy --locked --workspace --all-targets -- -D warnings
|
||||
cargo test --locked --workspace
|
||||
```
|
||||
|
||||
The format, lint and test trio is the standard check set. The native Metal
|
||||
passes use Metal API and shader validation; `scripts/audit/status.py --check`
|
||||
verifies the generated status tables.
|
||||
|
||||
### Run native Metal tests
|
||||
|
||||
These require a Metal-capable Apple Silicon Mac.
|
||||
@@ -320,6 +354,9 @@ Testing distinguishes between:
|
||||
|
||||
Compiling a shader is not equivalent to proving its GPU output is correct.
|
||||
|
||||
### Where the work is heading
|
||||
|
||||
See the [roadmap table](#development-milestones) for proposed milestones, and the [changelog](CHANGELOG.md) for the current unreleased additions, such as the native blend pass, indexed draws and the depth pass. The remaining research steps are the outstanding items in [current limitations](#current-limitations).
|
||||
|
||||
---
|
||||
|
||||
|
||||
+28
-29
@@ -7,9 +7,8 @@ pub use xenora_isa::{
|
||||
ScalarSource, VectorCompareOp, VectorSource,
|
||||
};
|
||||
use xenora_isa::{
|
||||
BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_ADD_I32, S_ADD_U32, S_ADDC_U32,
|
||||
S_AND_B32, S_BRANCH, S_CBRANCH_EXECZ, S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_CMP_EQ_U32, S_ENDPGM,
|
||||
S_MOV_B32, S_OR_B32, S_SUB_I32, S_SUB_U32, S_SUBB_U32, S_WAITCNT, S_WAITCNT_VSCNT, S_XOR_B32,
|
||||
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,
|
||||
@@ -17,19 +16,36 @@ use xenora_isa::{
|
||||
};
|
||||
|
||||
use xenora_isa::meta::EncodingFamily;
|
||||
use xenora_isa::semantics::FORM_IDS;
|
||||
|
||||
/// Metadata forms that [`decode`] turns into an [`Instruction`] for at least one
|
||||
/// operand combination. Operand restrictions are listed in docs/status.toml;
|
||||
/// every other form in [`xenora_isa::meta::FORMS`] is rejected as unsupported.
|
||||
pub const SEMANTIC_FORMS: [(&str, EncodingFamily); 46] = [
|
||||
/// operand combination: the hand-written forms below followed by every form of
|
||||
/// the semantic registry ([`xenora_isa::semantics::FORM_IDS`]). Operand
|
||||
/// restrictions are listed in docs/status.toml; every other form in
|
||||
/// [`xenora_isa::meta::FORMS`] is rejected as unsupported.
|
||||
pub const SEMANTIC_FORMS: [(&str, EncodingFamily); HANDWRITTEN_FORMS.len() + FORM_IDS.len()] =
|
||||
concat_forms();
|
||||
|
||||
const fn concat_forms<const N: usize>() -> [(&'static str, EncodingFamily); N] {
|
||||
let mut forms = [("", EncodingFamily::Sop2); N];
|
||||
let mut index = 0;
|
||||
while index < N {
|
||||
forms[index] = if index < HANDWRITTEN_FORMS.len() {
|
||||
HANDWRITTEN_FORMS[index]
|
||||
} else {
|
||||
FORM_IDS[index - HANDWRITTEN_FORMS.len()]
|
||||
};
|
||||
index += 1;
|
||||
}
|
||||
forms
|
||||
}
|
||||
|
||||
/// Decoded forms not yet described by the semantic registry.
|
||||
const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 37] = [
|
||||
("BUFFER_LOAD_DWORD", EncodingFamily::Mubuf),
|
||||
("BUFFER_STORE_DWORD", EncodingFamily::Mubuf),
|
||||
("EXP", EncodingFamily::Exp),
|
||||
("IMAGE_SAMPLE_LZ", EncodingFamily::Mimg),
|
||||
("S_ADD_I32", EncodingFamily::Sop2),
|
||||
("S_ADD_U32", EncodingFamily::Sop2),
|
||||
("S_ADDC_U32", EncodingFamily::Sop2),
|
||||
("S_AND_B32", EncodingFamily::Sop2),
|
||||
("S_BRANCH", EncodingFamily::Sopp),
|
||||
("S_CBRANCH_EXECZ", EncodingFamily::Sopp),
|
||||
("S_CBRANCH_SCC0", EncodingFamily::Sopp),
|
||||
@@ -37,13 +53,8 @@ pub const SEMANTIC_FORMS: [(&str, EncodingFamily); 46] = [
|
||||
("S_CMP_EQ_U32", EncodingFamily::Sopc),
|
||||
("S_ENDPGM", EncodingFamily::Sopp),
|
||||
("S_MOV_B32", EncodingFamily::Sop1),
|
||||
("S_OR_B32", EncodingFamily::Sop2),
|
||||
("S_SUB_I32", EncodingFamily::Sop2),
|
||||
("S_SUB_U32", EncodingFamily::Sop2),
|
||||
("S_SUBB_U32", EncodingFamily::Sop2),
|
||||
("S_WAITCNT", EncodingFamily::Sopp),
|
||||
("S_WAITCNT_VSCNT", EncodingFamily::Sopk),
|
||||
("S_XOR_B32", EncodingFamily::Sop2),
|
||||
("V_ADD_F32", EncodingFamily::Vop2),
|
||||
("V_ADD_NC_U32", EncodingFamily::Vop3),
|
||||
("V_AND_B32", EncodingFamily::Vop2),
|
||||
@@ -384,20 +395,8 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
|
||||
let target = branch_target(first, offset, "s_branch")?;
|
||||
return Ok((Instruction::Branch { target }, S_BRANCH.byte_len()));
|
||||
}
|
||||
for (opcode, op) in [
|
||||
(S_ADD_U32, ScalarAluOp::AddU32),
|
||||
(S_SUB_U32, ScalarAluOp::SubU32),
|
||||
(S_ADD_I32, ScalarAluOp::AddI32),
|
||||
(S_SUB_I32, ScalarAluOp::SubI32),
|
||||
(S_ADDC_U32, ScalarAluOp::AddcU32),
|
||||
(S_SUBB_U32, ScalarAluOp::SubbU32),
|
||||
(S_AND_B32, ScalarAluOp::AndB32),
|
||||
(S_OR_B32, ScalarAluOp::OrB32),
|
||||
(S_XOR_B32, ScalarAluOp::XorB32),
|
||||
] {
|
||||
if opcode.matches(first) {
|
||||
return scalar_alu(op, first, bytes);
|
||||
}
|
||||
if let Some(op) = ScalarAluOp::from_word(first) {
|
||||
return scalar_alu(op, first, bytes);
|
||||
}
|
||||
if S_CBRANCH_SCC0.matches(first) {
|
||||
let target = branch_target(first, offset, "s_cbranch_scc0")?;
|
||||
|
||||
@@ -18,15 +18,6 @@ VARIANTS = (
|
||||
("S_ENDPGM", "ENC_SOPP"),
|
||||
("S_MOV_B32", "ENC_SOP1"),
|
||||
("S_CMP_EQ_U32", "ENC_SOPC"),
|
||||
("S_ADD_U32", "ENC_SOP2"),
|
||||
("S_SUB_U32", "ENC_SOP2"),
|
||||
("S_ADD_I32", "ENC_SOP2"),
|
||||
("S_SUB_I32", "ENC_SOP2"),
|
||||
("S_ADDC_U32", "ENC_SOP2"),
|
||||
("S_SUBB_U32", "ENC_SOP2"),
|
||||
("S_AND_B32", "ENC_SOP2"),
|
||||
("S_OR_B32", "ENC_SOP2"),
|
||||
("S_XOR_B32", "ENC_SOP2"),
|
||||
("S_CBRANCH_SCC0", "ENC_SOPP"),
|
||||
("S_CBRANCH_EXECZ", "ENC_SOPP"),
|
||||
("S_CBRANCH_VCCZ", "ENC_SOPP"),
|
||||
|
||||
Executable
+541
@@ -0,0 +1,541 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Validate the declarative gfx1030 semantic registry and generate its Rust tables.
|
||||
|
||||
validate check crates/isa/semantics/rdna2.toml against its closed vocabulary
|
||||
and the pinned AMD XML snapshot (crates/isa/data/rdna2.jsonl)
|
||||
generate validate, then write crates/isa/src/semantics_gen.rs
|
||||
--check validate and regenerate in memory; exit 1 if the committed file
|
||||
differs. Never writes.
|
||||
|
||||
The registry is data only. Behaviour is chosen from a closed set of primitives
|
||||
(crates/isa/src/primitive.rs) by the declared operation, signedness and SCC
|
||||
effect, never from a mnemonic. Only the Python standard library is used
|
||||
(tomllib needs Python 3.11 or newer). See docs/shaders/semantic-registry.md.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
try:
|
||||
import tomllib
|
||||
except ModuleNotFoundError: # pragma: no cover - depends on the interpreter
|
||||
sys.exit("generate_semantics.py needs Python 3.11 or newer (tomllib)")
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
REGISTRY = ROOT / "crates/isa/semantics/rdna2.toml"
|
||||
SNAPSHOT = ROOT / "crates/isa/data/rdna2.jsonl"
|
||||
RUST = ROOT / "crates/isa/src/semantics_gen.rs"
|
||||
|
||||
SCHEMA = 1
|
||||
ARCHITECTURE = "gfx1030"
|
||||
|
||||
FORM_KEYS = {
|
||||
"name", "family", "opcode", "variant", "operation", "signedness", "carry_in",
|
||||
"width", "scc", "vcc", "exec", "wave", "operands", "spec", "verify",
|
||||
}
|
||||
TOP_KEYS = {"schema", "architecture", "source_sha256", "documents", "operand_rules", "form"}
|
||||
|
||||
OPERATIONS = {"add": "Add", "sub": "Sub", "and": "And", "or": "Or", "xor": "Xor"}
|
||||
LOGICAL = {"and", "or", "xor"}
|
||||
SIGNEDNESS = {"unsigned": "Unsigned", "signed": "Signed", "bitwise": "Bitwise"}
|
||||
CARRY_IN = {"none": "None", "scc": "Scc"}
|
||||
SCC = {
|
||||
"unchanged": "Unchanged",
|
||||
"carry_out": "CarryOut",
|
||||
"borrow": "Borrow",
|
||||
"signed_overflow": "SignedOverflow",
|
||||
"nonzero": "Nonzero",
|
||||
}
|
||||
MASK = {"unchanged": "Unchanged"}
|
||||
WAVE = {"any": "Any", "wave32": "Wave32"}
|
||||
# The decoder has no wave-size input at the registry dispatch yet, so a Wave32
|
||||
# restriction could be declared but not enforced. Reject it until it can be.
|
||||
ENFORCED_WAVES = {"any"}
|
||||
EVIDENCE = {
|
||||
"reference": "Reference",
|
||||
"independent": "Independent",
|
||||
"metal": "Metal",
|
||||
"llvm_encoding": "LlvmEncoding",
|
||||
}
|
||||
DOCUMENTS = {"guide": "Guide", "xml": "Xml"}
|
||||
# The public documents spec references may cite, pinned so a citation cannot
|
||||
# silently point at another file.
|
||||
PINNED_DOCUMENTS = {
|
||||
"guide": {
|
||||
"title": "AMD RDNA 2 Instruction Set Architecture Reference Guide",
|
||||
"file": "rdna2-shader-instruction-set-architecture.pdf",
|
||||
"pages": 291,
|
||||
},
|
||||
"xml": {
|
||||
"title": "AMD RDNA 2 machine-readable ISA (pinned XML)",
|
||||
"file": "amdgpu_isa_rdna2.xml",
|
||||
},
|
||||
}
|
||||
WIDTHS = {32}
|
||||
|
||||
# (operation, signedness) -> (required SCC effect, primitive, takes carry-in).
|
||||
# A form whose declaration is not a row here has no primitive and is rejected.
|
||||
PRIMITIVES = {
|
||||
("add", "unsigned"): ("carry_out", "add_carry_u32", True),
|
||||
("sub", "unsigned"): ("borrow", "sub_borrow_u32", True),
|
||||
("add", "signed"): ("signed_overflow", "add_overflow_i32", False),
|
||||
("sub", "signed"): ("signed_overflow", "sub_overflow_i32", False),
|
||||
("and", "bitwise"): ("nonzero", "and_nonzero_b32", False),
|
||||
("or", "bitwise"): ("nonzero", "or_nonzero_b32", False),
|
||||
("xor", "bitwise"): ("nonzero", "xor_nonzero_b32", False),
|
||||
}
|
||||
|
||||
# Operand rules the decoder implements, each exactly once. A registry rule must
|
||||
# match one of these shapes; anything else is an unimplemented rule.
|
||||
UNSUPPORTED_COMBOS = {
|
||||
"dst_vcc", "dst_exec", "dst_ttmp", "dst_m0", "dst_null", "src_vcc", "src_exec",
|
||||
"src_m0", "src_ttmp", "src_float_inline", "src_special", "two_literals",
|
||||
}
|
||||
OPERAND_RULES = {
|
||||
"sop2_sgpr": {
|
||||
"rust": "Sop2Sgpr",
|
||||
"enum": "ScalarAluOp",
|
||||
"shape": {
|
||||
"family": "SOP2",
|
||||
"dst": {"field": "SDST", "class": "sgpr", "min": 0, "max": 105},
|
||||
"src": [
|
||||
{"field": "SSRC0", "class": "scalar_source"},
|
||||
{"field": "SSRC1", "class": "scalar_source"},
|
||||
],
|
||||
"max_literals": 1,
|
||||
},
|
||||
# Every one of these is rejected by the decoder's SOP2 operand checks.
|
||||
"unsupported": UNSUPPORTED_COMBOS,
|
||||
},
|
||||
}
|
||||
|
||||
VARIANT = re.compile(r"^[A-Z][A-Za-z0-9]*$")
|
||||
RESERVED_VARIANTS = {"Self", "ALL"}
|
||||
U16_MAX = 0xFFFF
|
||||
NAME = re.compile(r"^[A-Z][A-Z0-9_]*$")
|
||||
SECTION = re.compile(r"^[0-9]+(\.[0-9]+)*$")
|
||||
|
||||
|
||||
def load_registry(path=REGISTRY):
|
||||
"""Parse the TOML registry into a dict."""
|
||||
with open(path, "rb") as handle:
|
||||
return tomllib.load(handle)
|
||||
|
||||
|
||||
def load_snapshot(path=SNAPSHOT):
|
||||
"""Index the normalised XML snapshot: source line, encodings, default variants."""
|
||||
source = None
|
||||
encodings = {}
|
||||
variants = {}
|
||||
with open(path, encoding="utf-8") as handle:
|
||||
for line in handle:
|
||||
record = json.loads(line)
|
||||
kind = record.get("kind")
|
||||
if kind == "source":
|
||||
source = record
|
||||
elif kind == "encoding":
|
||||
encodings[record["name"]] = record
|
||||
elif kind == "variant" and record.get("condition") == "default":
|
||||
variants[(record["instruction"], record["encoding"])] = record
|
||||
return {"source": source or {}, "encodings": encodings, "variants": variants}
|
||||
|
||||
|
||||
def _family_encoding(family):
|
||||
return "ENC_" + family
|
||||
|
||||
|
||||
def _rust_family(family):
|
||||
return family[0] + family[1:].lower()
|
||||
|
||||
|
||||
def _check_rule(name, rule, errors):
|
||||
implemented = OPERAND_RULES.get(name)
|
||||
if implemented is None:
|
||||
errors.append(f"operand rule {name}: not implemented by the decoder")
|
||||
return
|
||||
unsupported = rule.get("unsupported", [])
|
||||
unknown = sorted(set(unsupported) - UNSUPPORTED_COMBOS)
|
||||
if unknown:
|
||||
errors.append(f"operand rule {name}: unknown unsupported combos {unknown}")
|
||||
if len(set(unsupported)) != len(unsupported):
|
||||
errors.append(f"operand rule {name}: duplicate unsupported combos")
|
||||
if set(unsupported) != implemented["unsupported"]:
|
||||
errors.append(
|
||||
f"operand rule {name}: unsupported combos differ from those the decoder rejects"
|
||||
)
|
||||
declared = {key: value for key, value in rule.items() if key != "unsupported"}
|
||||
if declared != implemented["shape"]:
|
||||
errors.append(
|
||||
f"operand rule {name}: declaration differs from the decoder's implemented rule"
|
||||
)
|
||||
|
||||
|
||||
def _check_xml(form, rule, snapshot, errors):
|
||||
label = form["name"]
|
||||
encoding_name = _family_encoding(form["family"])
|
||||
encoding = snapshot["encodings"].get(encoding_name)
|
||||
if encoding is None:
|
||||
errors.append(f"{label}: family {form['family']} has no XML encoding {encoding_name}")
|
||||
return
|
||||
variant = snapshot["variants"].get((form["name"], encoding_name))
|
||||
if variant is None:
|
||||
errors.append(f"{label}: no default {encoding_name} variant in the XML snapshot")
|
||||
return
|
||||
if variant["opcode"] != form["opcode"]:
|
||||
errors.append(
|
||||
f"{label}: opcode {form['opcode']} disagrees with the XML opcode {variant['opcode']}"
|
||||
)
|
||||
if _identifier(encoding, form["opcode"]) not in encoding["identifiers"]:
|
||||
errors.append(f"{label}: opcode {form['opcode']} is not an identifier of {encoding_name}")
|
||||
operands = {}
|
||||
scc_in = scc_out = False
|
||||
for field, data_format, kind, size, is_input, is_output, _implicit, _encoded in variant["operands"]:
|
||||
if kind == "OPR_SSRC_SPECIAL_SCC":
|
||||
scc_in |= is_input
|
||||
scc_out |= is_output
|
||||
elif field:
|
||||
operands[field] = (data_format, size, is_input, is_output)
|
||||
if scc_in != (form["carry_in"] == "scc"):
|
||||
errors.append(f"{label}: carry_in {form['carry_in']} contradicts the XML SCC input")
|
||||
if scc_out != (form["scc"] != "unchanged"):
|
||||
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"]]
|
||||
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']}")
|
||||
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"):
|
||||
errors.append(
|
||||
f"{label}: signedness {form['signedness']} contradicts XML format {data_format}"
|
||||
)
|
||||
extra = sorted(set(operands) - {field for field, _ in fields})
|
||||
if extra:
|
||||
errors.append(f"{label}: XML operands {extra} are not covered by rule {form['operands']}")
|
||||
|
||||
|
||||
def _identifier(encoding, opcode):
|
||||
fields = dict((name, ranges) for name, ranges in encoding["fields"])
|
||||
(offset, size), = fields["OP"]
|
||||
base = encoding["identifiers"][0] & ~(((1 << size) - 1) << offset)
|
||||
return base | (opcode << offset)
|
||||
|
||||
|
||||
def validate(registry, snapshot):
|
||||
"""Return every error in the registry; an empty list means it is valid."""
|
||||
errors = []
|
||||
unknown = sorted(set(registry) - TOP_KEYS)
|
||||
if unknown:
|
||||
errors.append(f"unknown top-level keys {unknown}")
|
||||
if type(registry.get("schema")) is not int or registry["schema"] != SCHEMA:
|
||||
errors.append(f"schema {registry.get('schema')!r} is not {SCHEMA}")
|
||||
if registry.get("architecture") != ARCHITECTURE:
|
||||
errors.append(f"architecture {registry.get('architecture')!r} is not {ARCHITECTURE}")
|
||||
if registry.get("source_sha256") != snapshot["source"].get("sha256"):
|
||||
errors.append("source_sha256 does not match the XML snapshot")
|
||||
documents = registry.get("documents", {})
|
||||
for name, document in documents.items():
|
||||
if name not in DOCUMENTS:
|
||||
errors.append(f"unknown document {name}")
|
||||
elif document != PINNED_DOCUMENTS[name]:
|
||||
errors.append(f"document {name}: differs from the pinned public document")
|
||||
if "guide" not in documents:
|
||||
errors.append("the guide document is not declared")
|
||||
rules = registry.get("operand_rules", {})
|
||||
for name, rule in rules.items():
|
||||
_check_rule(name, rule, errors)
|
||||
forms = registry.get("form", [])
|
||||
if not forms:
|
||||
errors.append("the registry declares no forms")
|
||||
seen = {"name": set(), "opcode": set(), "variant": set()}
|
||||
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)
|
||||
if missing:
|
||||
errors.append(f"{label}: incomplete, missing {missing}")
|
||||
if extra:
|
||||
errors.append(f"{label}: unknown keys {extra}")
|
||||
if missing:
|
||||
continue
|
||||
for key, vocabulary in (
|
||||
("operation", OPERATIONS), ("signedness", SIGNEDNESS), ("carry_in", CARRY_IN),
|
||||
("scc", SCC), ("vcc", MASK), ("exec", MASK), ("wave", WAVE),
|
||||
):
|
||||
if form[key] not in vocabulary:
|
||||
errors.append(f"{label}: unknown {key} {form[key]!r}")
|
||||
if not isinstance(form["name"], str) or not NAME.match(form["name"]):
|
||||
errors.append(f"{label}: invalid name")
|
||||
if not isinstance(form["variant"], str) or not VARIANT.match(form["variant"]):
|
||||
errors.append(f"{label}: invalid variant {form['variant']!r}")
|
||||
if form["variant"] in RESERVED_VARIANTS:
|
||||
errors.append(f"{label}: variant {form['variant']!r} is reserved")
|
||||
if type(form["opcode"]) is not int or not 0 <= form["opcode"] <= U16_MAX:
|
||||
errors.append(f"{label}: invalid opcode")
|
||||
if form["wave"] in WAVE and form["wave"] not in ENFORCED_WAVES:
|
||||
errors.append(f"{label}: wave {form['wave']} has no decoder enforcement yet")
|
||||
if type(form["width"]) is not int or form["width"] not in WIDTHS:
|
||||
errors.append(f"{label}: width {form['width']} is not supported")
|
||||
for key, value in (
|
||||
("name", form["name"]),
|
||||
("opcode", (form["family"], form["opcode"])),
|
||||
("variant", form["variant"]),
|
||||
):
|
||||
if value in seen[key]:
|
||||
errors.append(f"{label}: duplicate {key} {value}")
|
||||
seen[key].add(value)
|
||||
if (form["signedness"] == "bitwise") != (form["operation"] in LOGICAL):
|
||||
errors.append(
|
||||
f"{label}: signedness {form['signedness']} contradicts operation {form['operation']}"
|
||||
)
|
||||
primitive = PRIMITIVES.get((form["operation"], form["signedness"]))
|
||||
if primitive is None:
|
||||
errors.append(f"{label}: no primitive implements {form['operation']}/{form['signedness']}")
|
||||
else:
|
||||
scc, _, takes_carry = primitive
|
||||
if form["scc"] != scc:
|
||||
errors.append(
|
||||
f"{label}: scc {form['scc']} contradicts {form['operation']}/"
|
||||
f"{form['signedness']} (requires {scc})"
|
||||
)
|
||||
if form["carry_in"] == "scc" and not takes_carry:
|
||||
errors.append(f"{label}: carry_in scc contradicts {form['operation']}/{form['signedness']}")
|
||||
rule = rules.get(form["operands"])
|
||||
if rule is None:
|
||||
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')}")
|
||||
_check_spec(label, form["spec"], documents, errors)
|
||||
verify = form["verify"]
|
||||
if not verify:
|
||||
errors.append(f"{label}: no verification requirement")
|
||||
if any(item not in EVIDENCE for item in verify):
|
||||
errors.append(f"{label}: unknown verification requirement in {verify}")
|
||||
if len(set(verify)) != len(verify):
|
||||
errors.append(f"{label}: duplicate verification requirement")
|
||||
_check_xml(form, rule, snapshot, errors)
|
||||
return errors
|
||||
|
||||
|
||||
def _check_spec(label, spec, documents, errors):
|
||||
has_guide = False
|
||||
for ref in spec:
|
||||
if set(ref) != {"document", "section", "page"}:
|
||||
errors.append(f"{label}: spec reference needs exactly document, section, page")
|
||||
continue
|
||||
if ref["document"] not in documents:
|
||||
errors.append(f"{label}: spec cites undeclared document {ref['document']!r}")
|
||||
if not SECTION.match(str(ref["section"])):
|
||||
errors.append(f"{label}: invalid spec section {ref['section']!r}")
|
||||
if type(ref["page"]) is not int or not 0 <= ref["page"] <= U16_MAX:
|
||||
errors.append(f"{label}: invalid spec page")
|
||||
if ref["document"] == "guide" and type(ref["page"]) is int and ref["page"] > 0:
|
||||
has_guide = True
|
||||
if not has_guide:
|
||||
errors.append(f"{label}: missing a guide section and page reference")
|
||||
|
||||
|
||||
def render(registry, snapshot):
|
||||
"""Return the complete generated Rust source. Requires a valid registry."""
|
||||
forms = registry["form"]
|
||||
rule_names = sorted({form["operands"] for form in forms})
|
||||
positions = {form["name"]: position for position, form in enumerate(forms)}
|
||||
out = [
|
||||
"// @generated by crates/isa/generate_semantics.py from crates/isa/semantics/rdna2.toml.",
|
||||
"// Do not edit. Regenerate: python3 crates/isa/generate_semantics.py generate",
|
||||
"",
|
||||
"use crate::meta::EncodingFamily;",
|
||||
"use crate::primitive;",
|
||||
"use crate::semantics::{",
|
||||
" CarryIn, Document, Evidence, FormSemantics, MaskEffect, Operation, OperandRule, SccEffect,",
|
||||
" Signedness, SpecRef, Wave,",
|
||||
"};",
|
||||
"",
|
||||
"/// Registry schema of the generated tables.",
|
||||
f"pub const GENERATED_SCHEMA: u32 = {registry['schema']};",
|
||||
]
|
||||
for rule_name in rule_names:
|
||||
selected = [form for form in forms if form["operands"] == rule_name]
|
||||
out += _render_enum(rule_name, selected, snapshot, positions)
|
||||
out += [
|
||||
"",
|
||||
"/// Identity of every registry form, in registry order.",
|
||||
f"pub const FORM_IDS: [(&str, EncodingFamily); {len(forms)}] = [",
|
||||
]
|
||||
for form in forms:
|
||||
out.append(f" (\"{form['name']}\", EncodingFamily::{_rust_family(form['family'])}),")
|
||||
out += [
|
||||
"];",
|
||||
"",
|
||||
"/// One validated row per registry form, in registry order.",
|
||||
f"pub static FORMS: [FormSemantics; {len(forms)}] = [",
|
||||
]
|
||||
for form in forms:
|
||||
spec = ", ".join(
|
||||
f"SpecRef {{ document: Document::{DOCUMENTS[ref['document']]}, "
|
||||
f"section: \"{ref['section']}\", page: {ref['page']} }}"
|
||||
for ref in form["spec"]
|
||||
)
|
||||
verify = ", ".join(f"Evidence::{EVIDENCE[item]}" for item in form["verify"])
|
||||
out += [
|
||||
" FormSemantics {",
|
||||
f" name: \"{form['name']}\",",
|
||||
f" family: EncodingFamily::{_rust_family(form['family'])},",
|
||||
f" opcode: {form['opcode']},",
|
||||
f" operation: Operation::{OPERATIONS[form['operation']]},",
|
||||
f" signedness: Signedness::{SIGNEDNESS[form['signedness']]},",
|
||||
f" carry_in: CarryIn::{CARRY_IN[form['carry_in']]},",
|
||||
f" width: {form['width']},",
|
||||
f" scc: SccEffect::{SCC[form['scc']]},",
|
||||
f" vcc: MaskEffect::{MASK[form['vcc']]},",
|
||||
f" exec: MaskEffect::{MASK[form['exec']]},",
|
||||
f" wave: Wave::{WAVE[form['wave']]},",
|
||||
f" operands: OperandRule::{OPERAND_RULES[form['operands']]['rust']},",
|
||||
f" spec: &[{spec}],",
|
||||
f" verify: &[{verify}],",
|
||||
" },",
|
||||
]
|
||||
out += ["];", ""]
|
||||
return "\n".join(out)
|
||||
|
||||
|
||||
def _render_enum(rule_name, forms, snapshot, positions):
|
||||
enum = OPERAND_RULES[rule_name]["enum"]
|
||||
family = forms[0]["family"]
|
||||
encoding = snapshot["encodings"][_family_encoding(family)]
|
||||
mask = encoding["identifier_mask"]
|
||||
out = [
|
||||
"",
|
||||
f"/// {family} operations declared in the semantic registry (operand rule `{rule_name}`).",
|
||||
"#[derive(Clone, Copy, Debug, Eq, PartialEq)]",
|
||||
f"pub enum {enum} {{",
|
||||
]
|
||||
for form in forms:
|
||||
carry = " plus SCC" if form["carry_in"] == "scc" else ""
|
||||
out += [
|
||||
f" /// `{form['name'].lower()}` ({family} opcode {form['opcode']}): "
|
||||
f"{form['signedness']} {form['operation']}{carry}, SCC = {form['scc']}.",
|
||||
f" {form['variant']},",
|
||||
]
|
||||
out += [
|
||||
"}",
|
||||
"",
|
||||
f"impl {enum} {{",
|
||||
" /// Every operation, in registry order.",
|
||||
f" pub const ALL: [Self; {len(forms)}] = [",
|
||||
]
|
||||
out += [f" Self::{form['variant']}," for form in forms]
|
||||
out += [
|
||||
" ];",
|
||||
"",
|
||||
f" /// Selects the operation from a first instruction word (mask 0x{mask:09_x}).",
|
||||
" 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,",
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
" /// Lower-case mnemonic.",
|
||||
" pub const fn mnemonic(self) -> &'static str {",
|
||||
" 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 += [
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
" /// The validated registry row.",
|
||||
" pub fn semantics(self) -> &'static FormSemantics {",
|
||||
" &FORMS[match self {",
|
||||
]
|
||||
out += [f" Self::{form['variant']} => {positions[form['name']]}," for form in forms]
|
||||
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) {",
|
||||
" 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"
|
||||
call = f"primitive::{function}(src0, src1, {argument})"
|
||||
else:
|
||||
call = f"primitive::{function}(src0, src1)"
|
||||
out.append(f" Self::{form['variant']} => {call},")
|
||||
out += [" }", " }", "}"]
|
||||
return out
|
||||
|
||||
|
||||
def _display(path):
|
||||
try:
|
||||
return path.resolve().relative_to(ROOT)
|
||||
except ValueError:
|
||||
return path
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
parser.add_argument("mode", nargs="?", choices=("generate", "validate"))
|
||||
parser.add_argument("--check", action="store_true", help="fail if the committed file is stale")
|
||||
parser.add_argument("--registry", type=Path, default=REGISTRY)
|
||||
parser.add_argument("--snapshot", type=Path, default=SNAPSHOT)
|
||||
parser.add_argument("--output", type=Path, default=RUST)
|
||||
arguments = parser.parse_args()
|
||||
if bool(arguments.mode) == arguments.check:
|
||||
parser.error("choose exactly one of generate, validate or --check")
|
||||
registry = load_registry(arguments.registry)
|
||||
snapshot = load_snapshot(arguments.snapshot)
|
||||
errors = validate(registry, snapshot)
|
||||
if errors:
|
||||
for error in errors:
|
||||
print(f"error: {error}", file=sys.stderr)
|
||||
return 1
|
||||
count = len(registry["form"])
|
||||
if arguments.mode == "validate":
|
||||
print(f"registry valid: {count} forms")
|
||||
return 0
|
||||
text = render(registry, snapshot)
|
||||
if arguments.check:
|
||||
current = arguments.output.read_text(encoding="utf-8") if arguments.output.exists() else ""
|
||||
if current != text:
|
||||
print(f"{_display(arguments.output)} is stale; run generate", file=sys.stderr)
|
||||
return 1
|
||||
print(f"registry valid and generated code current: {count} forms")
|
||||
return 0
|
||||
arguments.output.write_text(text, encoding="utf-8")
|
||||
print(f"wrote {_display(arguments.output)}: {count} forms")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,232 @@
|
||||
# Declarative semantic registry for gfx1030 (AMD RDNA 2) instruction forms.
|
||||
#
|
||||
# Data only: no code strings, no expressions. Every value is a member of a closed
|
||||
# vocabulary that crates/isa/generate_semantics.py validates and turns into static
|
||||
# Rust tables (crates/isa/src/semantics_gen.rs). Identity, family, opcode and
|
||||
# operand facts are cross-checked against the pinned AMD XML snapshot
|
||||
# (crates/isa/data/rdna2.jsonl); behaviour comes from the public AMD guide cited
|
||||
# per form, never from the mnemonic. See docs/shaders/semantic-registry.md.
|
||||
#
|
||||
# Independence: the reference interpreter (crates/ref) and the second
|
||||
# interpreter (tests/validation/independent_ref.rs) never read this file.
|
||||
|
||||
schema = 1
|
||||
architecture = "gfx1030"
|
||||
# Must equal the "sha256" of the source line in crates/isa/data/rdna2.jsonl.
|
||||
source_sha256 = "d671ecbc36543674ab59e9b2feffd56718fd2137e7ad913c314f2e2508b9f4f7"
|
||||
|
||||
# Named public documents that spec references point at.
|
||||
[documents.guide]
|
||||
title = "AMD RDNA 2 Instruction Set Architecture Reference Guide"
|
||||
file = "rdna2-shader-instruction-set-architecture.pdf"
|
||||
pages = 291
|
||||
|
||||
[documents.xml]
|
||||
title = "AMD RDNA 2 machine-readable ISA (pinned XML)"
|
||||
file = "amdgpu_isa_rdna2.xml"
|
||||
|
||||
# Operand rules shared by a family. A rule names its destination and source
|
||||
# classes; the decoder implements each rule once (rules are not per opcode).
|
||||
[operand_rules.sop2_sgpr]
|
||||
family = "SOP2"
|
||||
dst = { field = "SDST", class = "sgpr", min = 0, max = 105 }
|
||||
src = [
|
||||
{ field = "SSRC0", class = "scalar_source" },
|
||||
{ field = "SSRC1", class = "scalar_source" },
|
||||
]
|
||||
# scalar_source = normal SGPR s0-s105, inline integer -16..64, or a literal word.
|
||||
max_literals = 1
|
||||
# Encodings this rule rejects, so they stay unsupported rather than guessed.
|
||||
unsupported = [
|
||||
"dst_vcc", "dst_exec", "dst_ttmp", "dst_m0", "dst_null",
|
||||
"src_vcc", "src_exec", "src_m0", "src_ttmp", "src_float_inline",
|
||||
"src_special", "two_literals",
|
||||
]
|
||||
|
||||
# ---- SOP2 32-bit integer and logical forms (migrated from #229/#230) ----
|
||||
# Field meanings:
|
||||
# name XML instruction name (stable identity)
|
||||
# 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
|
||||
# signedness unsigned | signed | bitwise (bitwise iff a logical operation)
|
||||
# carry_in none | scc (scc only for unsigned add/sub)
|
||||
# width operand and result width in bits
|
||||
# scc carry_out | borrow | signed_overflow | nonzero
|
||||
# vcc, exec unchanged (stated, not implied)
|
||||
# wave any | wave32
|
||||
# operands a key of [operand_rules]
|
||||
# spec references; at least one guide section with a page
|
||||
# verify evidence required before the form counts as verified
|
||||
|
||||
[[form]]
|
||||
name = "S_ADD_U32"
|
||||
family = "SOP2"
|
||||
opcode = 0
|
||||
variant = "AddU32"
|
||||
operation = "add"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "carry_out"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 101 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_SUB_U32"
|
||||
family = "SOP2"
|
||||
opcode = 1
|
||||
variant = "SubU32"
|
||||
operation = "sub"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "borrow"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 101 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_ADD_I32"
|
||||
family = "SOP2"
|
||||
opcode = 2
|
||||
variant = "AddI32"
|
||||
operation = "add"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "signed_overflow"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 101 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_SUB_I32"
|
||||
family = "SOP2"
|
||||
opcode = 3
|
||||
variant = "SubI32"
|
||||
operation = "sub"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "signed_overflow"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 101 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_ADDC_U32"
|
||||
family = "SOP2"
|
||||
opcode = 4
|
||||
variant = "AddcU32"
|
||||
operation = "add"
|
||||
signedness = "unsigned"
|
||||
carry_in = "scc"
|
||||
width = 32
|
||||
scc = "carry_out"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 102 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_SUBB_U32"
|
||||
family = "SOP2"
|
||||
opcode = 5
|
||||
variant = "SubbU32"
|
||||
operation = "sub"
|
||||
signedness = "unsigned"
|
||||
carry_in = "scc"
|
||||
width = 32
|
||||
scc = "borrow"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 102 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_AND_B32"
|
||||
family = "SOP2"
|
||||
opcode = 14
|
||||
variant = "AndB32"
|
||||
operation = "and"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [{ document = "guide", section = "12.1", page = 102 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_OR_B32"
|
||||
family = "SOP2"
|
||||
opcode = 16
|
||||
variant = "OrB32"
|
||||
operation = "or"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [{ document = "guide", section = "12.1", page = 102 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_XOR_B32"
|
||||
family = "SOP2"
|
||||
opcode = 18
|
||||
variant = "XorB32"
|
||||
operation = "xor"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [{ document = "guide", section = "12.1", page = 102 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
+7
-83
@@ -3,18 +3,22 @@
|
||||
use std::fmt;
|
||||
|
||||
pub mod meta;
|
||||
pub mod primitive;
|
||||
mod rdna2;
|
||||
pub mod semantics;
|
||||
#[rustfmt::skip]
|
||||
mod rdna2_meta;
|
||||
#[rustfmt::skip]
|
||||
mod semantics_gen;
|
||||
pub use rdna2::{
|
||||
BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_ADD_I32, S_ADD_U32, S_ADDC_U32,
|
||||
S_AND_B32, S_BRANCH, S_CBRANCH_EXECZ, S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_CMP_EQ_U32, S_ENDPGM,
|
||||
S_MOV_B32, S_OR_B32, S_SUB_I32, S_SUB_U32, S_SUBB_U32, S_WAITCNT, S_WAITCNT_VSCNT, S_XOR_B32,
|
||||
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,
|
||||
};
|
||||
pub use semantics_gen::ScalarAluOp;
|
||||
|
||||
/// SGPR index of `vcc_lo`, the Wave32 vector condition code.
|
||||
pub const VCC_LO: u8 = 106;
|
||||
@@ -164,86 +168,6 @@ impl VectorCompareOp {
|
||||
}
|
||||
}
|
||||
|
||||
/// SOP2 32-bit integer operations in the supported scalar subset.
|
||||
///
|
||||
/// SCC behaviour follows the pinned AMD RDNA 2 XML descriptions: additions
|
||||
/// store the carry-out, subtractions the borrow, ADDC and SUBB also consume
|
||||
/// SCC as carry-in or borrow-in, signed forms store signed overflow (RDNA 2 ISA
|
||||
/// guide 12.1), and bitwise operations set SCC iff the result is nonzero. See
|
||||
/// docs/shaders/scalar-alu.md for the sources.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum ScalarAluOp {
|
||||
/// `s_add_u32`: D = S0 + S1, SCC = carry-out.
|
||||
AddU32,
|
||||
/// `s_sub_u32`: D = S0 - S1, SCC = borrow (S1 > S0).
|
||||
SubU32,
|
||||
/// `s_add_i32`: D = S0 + S1, SCC = signed overflow.
|
||||
AddI32,
|
||||
/// `s_sub_i32`: D = S0 - S1, SCC = signed overflow.
|
||||
SubI32,
|
||||
/// `s_addc_u32`: D = S0 + S1 + SCC, SCC = carry-out.
|
||||
AddcU32,
|
||||
/// `s_subb_u32`: D = S0 - S1 - SCC, SCC = borrow.
|
||||
SubbU32,
|
||||
/// `s_and_b32`: D = S0 & S1, SCC = D != 0.
|
||||
AndB32,
|
||||
/// `s_or_b32`: D = S0 | S1, SCC = D != 0.
|
||||
OrB32,
|
||||
/// `s_xor_b32`: D = S0 ^ S1, SCC = D != 0.
|
||||
XorB32,
|
||||
}
|
||||
|
||||
impl ScalarAluOp {
|
||||
/// Lower-case mnemonic.
|
||||
pub fn mnemonic(self) -> &'static str {
|
||||
match self {
|
||||
Self::AddU32 => "s_add_u32",
|
||||
Self::SubU32 => "s_sub_u32",
|
||||
Self::AddI32 => "s_add_i32",
|
||||
Self::SubI32 => "s_sub_i32",
|
||||
Self::AddcU32 => "s_addc_u32",
|
||||
Self::SubbU32 => "s_subb_u32",
|
||||
Self::AndB32 => "s_and_b32",
|
||||
Self::OrB32 => "s_or_b32",
|
||||
Self::XorB32 => "s_xor_b32",
|
||||
}
|
||||
}
|
||||
|
||||
/// The 32-bit result and the new SCC, with `carry_in` the SCC read by
|
||||
/// ADDC and SUBB (ignored by the other operations).
|
||||
pub fn evaluate(self, src0: u32, src1: u32, carry_in: bool) -> (u32, bool) {
|
||||
let carry = u32::from(carry_in && self.reads_scc());
|
||||
match self {
|
||||
Self::AddU32 | Self::AddcU32 => {
|
||||
let (partial, first) = src0.overflowing_add(src1);
|
||||
let (value, second) = partial.overflowing_add(carry);
|
||||
(value, first || second)
|
||||
}
|
||||
Self::SubU32 | Self::SubbU32 => {
|
||||
let (partial, first) = src0.overflowing_sub(src1);
|
||||
let (value, second) = partial.overflowing_sub(carry);
|
||||
(value, first || second)
|
||||
}
|
||||
Self::AddI32 => {
|
||||
let (value, overflow) = (src0 as i32).overflowing_add(src1 as i32);
|
||||
(value as u32, overflow)
|
||||
}
|
||||
Self::SubI32 => {
|
||||
let (value, overflow) = (src0 as i32).overflowing_sub(src1 as i32);
|
||||
(value as u32, overflow)
|
||||
}
|
||||
Self::AndB32 => (src0 & src1, src0 & src1 != 0),
|
||||
Self::OrB32 => (src0 | src1, src0 | src1 != 0),
|
||||
Self::XorB32 => (src0 ^ src1, src0 ^ src1 != 0),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the operation reads SCC as a carry-in or borrow-in.
|
||||
pub fn reads_scc(self) -> bool {
|
||||
matches!(self, Self::AddcU32 | Self::SubbU32)
|
||||
}
|
||||
}
|
||||
|
||||
/// Output targeted by a supported uncompressed four-component export.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum ExportTarget {
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
//! Reusable integer semantic primitives selected by the generated registry dispatch.
|
||||
//!
|
||||
//! Each function implements one closed [`crate::semantics::Operation`] at one
|
||||
//! signedness, with the condition-code rule the RDNA 2 guide gives for it
|
||||
//! (section 5.3, "Scalar Condition Code", and the SOP2 pseudocode in 12.1).
|
||||
//! Forms share a primitive only when their declared operation, signedness and
|
||||
//! SCC effect are identical; the generator never selects one by mnemonic.
|
||||
|
||||
/// Unsigned `a + b + carry_in` and the carry-out of bit 31.
|
||||
pub const fn add_carry_u32(a: u32, b: u32, carry_in: bool) -> (u32, bool) {
|
||||
let (partial, first) = a.overflowing_add(b);
|
||||
let (value, second) = partial.overflowing_add(carry_in as u32);
|
||||
(value, first || second)
|
||||
}
|
||||
|
||||
/// Unsigned `a - b - borrow_in` and the borrow (`b + borrow_in > a`).
|
||||
pub const fn sub_borrow_u32(a: u32, b: u32, borrow_in: bool) -> (u32, bool) {
|
||||
let (partial, first) = a.overflowing_sub(b);
|
||||
let (value, second) = partial.overflowing_sub(borrow_in as u32);
|
||||
(value, first || second)
|
||||
}
|
||||
|
||||
/// Two's-complement `a + b` and whether the exact sum leaves the i32 range.
|
||||
pub const fn add_overflow_i32(a: u32, b: u32) -> (u32, bool) {
|
||||
let (value, overflow) = (a as i32).overflowing_add(b as i32);
|
||||
(value as u32, overflow)
|
||||
}
|
||||
|
||||
/// Two's-complement `a - b` and whether the exact difference leaves the i32 range.
|
||||
pub const fn sub_overflow_i32(a: u32, b: u32) -> (u32, bool) {
|
||||
let (value, overflow) = (a as i32).overflowing_sub(b as i32);
|
||||
(value as u32, overflow)
|
||||
}
|
||||
|
||||
/// Bitwise AND and whether the result is nonzero.
|
||||
pub const fn and_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
|
||||
let value = a & b;
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Bitwise OR and whether the result is nonzero.
|
||||
pub const fn or_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
|
||||
let value = a | b;
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Bitwise XOR and whether the result is nonzero.
|
||||
pub const fn xor_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
|
||||
let value = a ^ b;
|
||||
(value, value != 0)
|
||||
}
|
||||
@@ -50,51 +50,6 @@ pub const S_CMP_EQ_U32: Opcode = Opcode {
|
||||
bits: 0xbf060000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const S_ADD_U32: Opcode = Opcode {
|
||||
mask: 0xff800000,
|
||||
bits: 0x80000000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const S_SUB_U32: Opcode = Opcode {
|
||||
mask: 0xff800000,
|
||||
bits: 0x80800000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const S_ADD_I32: Opcode = Opcode {
|
||||
mask: 0xff800000,
|
||||
bits: 0x81000000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const S_SUB_I32: Opcode = Opcode {
|
||||
mask: 0xff800000,
|
||||
bits: 0x81800000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const S_ADDC_U32: Opcode = Opcode {
|
||||
mask: 0xff800000,
|
||||
bits: 0x82000000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const S_SUBB_U32: Opcode = Opcode {
|
||||
mask: 0xff800000,
|
||||
bits: 0x82800000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const S_AND_B32: Opcode = Opcode {
|
||||
mask: 0xff800000,
|
||||
bits: 0x87000000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const S_OR_B32: Opcode = Opcode {
|
||||
mask: 0xff800000,
|
||||
bits: 0x88000000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const S_XOR_B32: Opcode = Opcode {
|
||||
mask: 0xff800000,
|
||||
bits: 0x89000000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const S_CBRANCH_SCC0: Opcode = Opcode {
|
||||
mask: 0xffff0000,
|
||||
bits: 0xbf840000,
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
//! Typed vocabulary of the declarative semantic registry (`crates/isa/semantics/rdna2.toml`).
|
||||
//!
|
||||
//! The registry is data. `crates/isa/generate_semantics.py` validates it against
|
||||
//! this closed vocabulary and the pinned AMD XML snapshot, then emits
|
||||
//! `semantics_gen.rs`: the typed operation enums, their opcode dispatch and one
|
||||
//! static [`FormSemantics`] row per form. Nothing here interprets metadata at run
|
||||
//! time; the decoder and translator call the generated `const fn`s and `match`es.
|
||||
//!
|
||||
//! The reference interpreter (`crates/ref`) and the independent interpreter
|
||||
//! (`tests/validation/independent_ref.rs`) must not use this module.
|
||||
|
||||
use crate::meta::EncodingFamily;
|
||||
|
||||
pub use crate::semantics_gen::{FORM_IDS, FORMS, GENERATED_SCHEMA};
|
||||
|
||||
/// Version of the registry schema this crate was generated against.
|
||||
pub const SCHEMA: u32 = 1;
|
||||
|
||||
/// Reusable semantic primitive selected by a form. Closed: the generator rejects
|
||||
/// any other name, and each primitive has one implementation in `primitive.rs`.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum Operation {
|
||||
/// Integer addition.
|
||||
Add,
|
||||
/// Integer subtraction.
|
||||
Sub,
|
||||
/// Bitwise AND.
|
||||
And,
|
||||
/// Bitwise OR.
|
||||
Or,
|
||||
/// Bitwise exclusive OR.
|
||||
Xor,
|
||||
}
|
||||
|
||||
/// How the operands are interpreted. `Bitwise` exactly when the operation is logical.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum Signedness {
|
||||
/// Unsigned integers.
|
||||
Unsigned,
|
||||
/// Two's-complement integers.
|
||||
Signed,
|
||||
/// Untyped bits.
|
||||
Bitwise,
|
||||
}
|
||||
|
||||
/// Extra input consumed by the operation.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum CarryIn {
|
||||
/// No carry or borrow input.
|
||||
None,
|
||||
/// SCC as carry-in (add) or borrow-in (sub).
|
||||
Scc,
|
||||
}
|
||||
|
||||
/// What a form writes to SCC.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum SccEffect {
|
||||
/// SCC is not written.
|
||||
Unchanged,
|
||||
/// Unsigned carry-out of the top bit.
|
||||
CarryOut,
|
||||
/// Unsigned borrow (subtrahend plus borrow-in exceeds the minuend).
|
||||
Borrow,
|
||||
/// Two's-complement overflow of the exact result.
|
||||
SignedOverflow,
|
||||
/// The result is not zero.
|
||||
Nonzero,
|
||||
}
|
||||
|
||||
/// What a form writes to VCC or EXEC. Stage A forms leave both unchanged.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum MaskEffect {
|
||||
/// Not written.
|
||||
Unchanged,
|
||||
}
|
||||
|
||||
/// Wave-size restriction.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum Wave {
|
||||
/// Behaviour does not depend on the wave size.
|
||||
Any,
|
||||
/// Only Wave32 behaviour is declared; Wave64 stays unsupported.
|
||||
Wave32,
|
||||
}
|
||||
|
||||
/// Shared operand rule. The decoder implements each rule once.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
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,
|
||||
}
|
||||
|
||||
/// Evidence a form needs before it counts as verified.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum Evidence {
|
||||
/// `crates/ref` lockstep reference.
|
||||
Reference,
|
||||
/// `tests/validation/independent_ref.rs`.
|
||||
Independent,
|
||||
/// Native Metal known-answer runs.
|
||||
Metal,
|
||||
/// LLVM assembler/disassembler encoding agreement.
|
||||
LlvmEncoding,
|
||||
}
|
||||
|
||||
/// Public document a [`SpecRef`] points at.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum Document {
|
||||
/// AMD RDNA 2 ISA reference guide (PDF).
|
||||
Guide,
|
||||
/// Pinned AMD machine-readable XML.
|
||||
Xml,
|
||||
}
|
||||
|
||||
/// One public specification reference.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct SpecRef {
|
||||
/// Source document.
|
||||
pub document: Document,
|
||||
/// Section number, for example `"12.1"`.
|
||||
pub section: &'static str,
|
||||
/// Page in the document, 0 when not paginated.
|
||||
pub page: u16,
|
||||
}
|
||||
|
||||
/// One validated registry row, emitted as a static table by the generator.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct FormSemantics {
|
||||
/// XML instruction name, the stable form identity.
|
||||
pub name: &'static str,
|
||||
/// Encoding family (matches [`crate::meta::FORMS`]).
|
||||
pub family: EncodingFamily,
|
||||
/// Opcode within the family.
|
||||
pub opcode: u16,
|
||||
/// Primitive.
|
||||
pub operation: Operation,
|
||||
/// Operand interpretation.
|
||||
pub signedness: Signedness,
|
||||
/// Carry or borrow input.
|
||||
pub carry_in: CarryIn,
|
||||
/// Operand and result width in bits.
|
||||
pub width: u8,
|
||||
/// SCC write.
|
||||
pub scc: SccEffect,
|
||||
/// VCC write.
|
||||
pub vcc: MaskEffect,
|
||||
/// EXEC write.
|
||||
pub exec: MaskEffect,
|
||||
/// Wave-size restriction.
|
||||
pub wave: Wave,
|
||||
/// Operand rule.
|
||||
pub operands: OperandRule,
|
||||
/// Public references.
|
||||
pub spec: &'static [SpecRef],
|
||||
/// Required evidence.
|
||||
pub verify: &'static [Evidence],
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
// @generated by crates/isa/generate_semantics.py from crates/isa/semantics/rdna2.toml.
|
||||
// Do not edit. Regenerate: python3 crates/isa/generate_semantics.py generate
|
||||
|
||||
use crate::meta::EncodingFamily;
|
||||
use crate::primitive;
|
||||
use crate::semantics::{
|
||||
CarryIn, Document, Evidence, FormSemantics, MaskEffect, Operation, OperandRule, SccEffect,
|
||||
Signedness, SpecRef, Wave,
|
||||
};
|
||||
|
||||
/// Registry schema of the generated tables.
|
||||
pub const GENERATED_SCHEMA: u32 = 1;
|
||||
|
||||
/// SOP2 operations declared in the semantic registry (operand rule `sop2_sgpr`).
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum ScalarAluOp {
|
||||
/// `s_add_u32` (SOP2 opcode 0): unsigned add, SCC = carry_out.
|
||||
AddU32,
|
||||
/// `s_sub_u32` (SOP2 opcode 1): unsigned sub, SCC = borrow.
|
||||
SubU32,
|
||||
/// `s_add_i32` (SOP2 opcode 2): signed add, SCC = signed_overflow.
|
||||
AddI32,
|
||||
/// `s_sub_i32` (SOP2 opcode 3): signed sub, SCC = signed_overflow.
|
||||
SubI32,
|
||||
/// `s_addc_u32` (SOP2 opcode 4): unsigned add plus SCC, SCC = carry_out.
|
||||
AddcU32,
|
||||
/// `s_subb_u32` (SOP2 opcode 5): unsigned sub plus SCC, SCC = borrow.
|
||||
SubbU32,
|
||||
/// `s_and_b32` (SOP2 opcode 14): bitwise and, SCC = nonzero.
|
||||
AndB32,
|
||||
/// `s_or_b32` (SOP2 opcode 16): bitwise or, SCC = nonzero.
|
||||
OrB32,
|
||||
/// `s_xor_b32` (SOP2 opcode 18): bitwise xor, SCC = nonzero.
|
||||
XorB32,
|
||||
}
|
||||
|
||||
impl ScalarAluOp {
|
||||
/// Every operation, in registry order.
|
||||
pub const ALL: [Self; 9] = [
|
||||
Self::AddU32,
|
||||
Self::SubU32,
|
||||
Self::AddI32,
|
||||
Self::SubI32,
|
||||
Self::AddcU32,
|
||||
Self::SubbU32,
|
||||
Self::AndB32,
|
||||
Self::OrB32,
|
||||
Self::XorB32,
|
||||
];
|
||||
|
||||
/// Selects the operation from a first instruction word (mask 0xff80_0000).
|
||||
pub const fn from_word(word: u32) -> Option<Self> {
|
||||
match word & 0xff80_0000 {
|
||||
0x8000_0000 => Some(Self::AddU32),
|
||||
0x8080_0000 => Some(Self::SubU32),
|
||||
0x8100_0000 => Some(Self::AddI32),
|
||||
0x8180_0000 => Some(Self::SubI32),
|
||||
0x8200_0000 => Some(Self::AddcU32),
|
||||
0x8280_0000 => Some(Self::SubbU32),
|
||||
0x8700_0000 => Some(Self::AndB32),
|
||||
0x8800_0000 => Some(Self::OrB32),
|
||||
0x8900_0000 => Some(Self::XorB32),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Lower-case mnemonic.
|
||||
pub const fn mnemonic(self) -> &'static str {
|
||||
match self {
|
||||
Self::AddU32 => "s_add_u32",
|
||||
Self::SubU32 => "s_sub_u32",
|
||||
Self::AddI32 => "s_add_i32",
|
||||
Self::SubI32 => "s_sub_i32",
|
||||
Self::AddcU32 => "s_addc_u32",
|
||||
Self::SubbU32 => "s_subb_u32",
|
||||
Self::AndB32 => "s_and_b32",
|
||||
Self::OrB32 => "s_or_b32",
|
||||
Self::XorB32 => "s_xor_b32",
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the operation reads SCC as a carry-in or borrow-in.
|
||||
pub const fn reads_scc(self) -> bool {
|
||||
match self {
|
||||
Self::AddU32 => false,
|
||||
Self::SubU32 => false,
|
||||
Self::AddI32 => false,
|
||||
Self::SubI32 => false,
|
||||
Self::AddcU32 => true,
|
||||
Self::SubbU32 => true,
|
||||
Self::AndB32 => false,
|
||||
Self::OrB32 => false,
|
||||
Self::XorB32 => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The validated registry row.
|
||||
pub fn semantics(self) -> &'static FormSemantics {
|
||||
&FORMS[match self {
|
||||
Self::AddU32 => 0,
|
||||
Self::SubU32 => 1,
|
||||
Self::AddI32 => 2,
|
||||
Self::SubI32 => 3,
|
||||
Self::AddcU32 => 4,
|
||||
Self::SubbU32 => 5,
|
||||
Self::AndB32 => 6,
|
||||
Self::OrB32 => 7,
|
||||
Self::XorB32 => 8,
|
||||
}]
|
||||
}
|
||||
|
||||
/// 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) {
|
||||
match self {
|
||||
Self::AddU32 => primitive::add_carry_u32(src0, src1, false),
|
||||
Self::SubU32 => primitive::sub_borrow_u32(src0, src1, false),
|
||||
Self::AddI32 => primitive::add_overflow_i32(src0, src1),
|
||||
Self::SubI32 => primitive::sub_overflow_i32(src0, src1),
|
||||
Self::AddcU32 => primitive::add_carry_u32(src0, src1, carry_in),
|
||||
Self::SubbU32 => primitive::sub_borrow_u32(src0, src1, carry_in),
|
||||
Self::AndB32 => primitive::and_nonzero_b32(src0, src1),
|
||||
Self::OrB32 => primitive::or_nonzero_b32(src0, src1),
|
||||
Self::XorB32 => primitive::xor_nonzero_b32(src0, src1),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Identity of every registry form, in registry order.
|
||||
pub const FORM_IDS: [(&str, EncodingFamily); 9] = [
|
||||
("S_ADD_U32", EncodingFamily::Sop2),
|
||||
("S_SUB_U32", EncodingFamily::Sop2),
|
||||
("S_ADD_I32", EncodingFamily::Sop2),
|
||||
("S_SUB_I32", EncodingFamily::Sop2),
|
||||
("S_ADDC_U32", EncodingFamily::Sop2),
|
||||
("S_SUBB_U32", EncodingFamily::Sop2),
|
||||
("S_AND_B32", EncodingFamily::Sop2),
|
||||
("S_OR_B32", EncodingFamily::Sop2),
|
||||
("S_XOR_B32", EncodingFamily::Sop2),
|
||||
];
|
||||
|
||||
/// One validated row per registry form, in registry order.
|
||||
pub static FORMS: [FormSemantics; 9] = [
|
||||
FormSemantics {
|
||||
name: "S_ADD_U32",
|
||||
family: EncodingFamily::Sop2,
|
||||
opcode: 0,
|
||||
operation: Operation::Add,
|
||||
signedness: Signedness::Unsigned,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
scc: SccEffect::CarryOut,
|
||||
vcc: MaskEffect::Unchanged,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Any,
|
||||
operands: OperandRule::Sop2Sgpr,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 101 }, SpecRef { document: Document::Guide, section: "5.3", page: 33 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "S_SUB_U32",
|
||||
family: EncodingFamily::Sop2,
|
||||
opcode: 1,
|
||||
operation: Operation::Sub,
|
||||
signedness: Signedness::Unsigned,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
scc: SccEffect::Borrow,
|
||||
vcc: MaskEffect::Unchanged,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Any,
|
||||
operands: OperandRule::Sop2Sgpr,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 101 }, SpecRef { document: Document::Guide, section: "5.3", page: 33 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "S_ADD_I32",
|
||||
family: EncodingFamily::Sop2,
|
||||
opcode: 2,
|
||||
operation: Operation::Add,
|
||||
signedness: Signedness::Signed,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
scc: SccEffect::SignedOverflow,
|
||||
vcc: MaskEffect::Unchanged,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Any,
|
||||
operands: OperandRule::Sop2Sgpr,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 101 }, SpecRef { document: Document::Guide, section: "5.3", page: 33 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "S_SUB_I32",
|
||||
family: EncodingFamily::Sop2,
|
||||
opcode: 3,
|
||||
operation: Operation::Sub,
|
||||
signedness: Signedness::Signed,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
scc: SccEffect::SignedOverflow,
|
||||
vcc: MaskEffect::Unchanged,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Any,
|
||||
operands: OperandRule::Sop2Sgpr,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 101 }, SpecRef { document: Document::Guide, section: "5.3", page: 33 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "S_ADDC_U32",
|
||||
family: EncodingFamily::Sop2,
|
||||
opcode: 4,
|
||||
operation: Operation::Add,
|
||||
signedness: Signedness::Unsigned,
|
||||
carry_in: CarryIn::Scc,
|
||||
width: 32,
|
||||
scc: SccEffect::CarryOut,
|
||||
vcc: MaskEffect::Unchanged,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Any,
|
||||
operands: OperandRule::Sop2Sgpr,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 102 }, SpecRef { document: Document::Guide, section: "5.3", page: 33 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "S_SUBB_U32",
|
||||
family: EncodingFamily::Sop2,
|
||||
opcode: 5,
|
||||
operation: Operation::Sub,
|
||||
signedness: Signedness::Unsigned,
|
||||
carry_in: CarryIn::Scc,
|
||||
width: 32,
|
||||
scc: SccEffect::Borrow,
|
||||
vcc: MaskEffect::Unchanged,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Any,
|
||||
operands: OperandRule::Sop2Sgpr,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 102 }, SpecRef { document: Document::Guide, section: "5.3", page: 33 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "S_AND_B32",
|
||||
family: EncodingFamily::Sop2,
|
||||
opcode: 14,
|
||||
operation: Operation::And,
|
||||
signedness: Signedness::Bitwise,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
scc: SccEffect::Nonzero,
|
||||
vcc: MaskEffect::Unchanged,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Any,
|
||||
operands: OperandRule::Sop2Sgpr,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 102 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "S_OR_B32",
|
||||
family: EncodingFamily::Sop2,
|
||||
opcode: 16,
|
||||
operation: Operation::Or,
|
||||
signedness: Signedness::Bitwise,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
scc: SccEffect::Nonzero,
|
||||
vcc: MaskEffect::Unchanged,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Any,
|
||||
operands: OperandRule::Sop2Sgpr,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 102 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "S_XOR_B32",
|
||||
family: EncodingFamily::Sop2,
|
||||
opcode: 18,
|
||||
operation: Operation::Xor,
|
||||
signedness: Signedness::Bitwise,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
scc: SccEffect::Nonzero,
|
||||
vcc: MaskEffect::Unchanged,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Any,
|
||||
operands: OperandRule::Sop2Sgpr,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 102 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,60 @@
|
||||
//! 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};
|
||||
|
||||
#[test]
|
||||
fn generated_tables_match_the_schema_and_the_metadata_forms() {
|
||||
assert_eq!(GENERATED_SCHEMA, SCHEMA);
|
||||
assert_eq!(FORM_IDS.len(), FORMS.len());
|
||||
for (row, (name, family)) in FORMS.iter().zip(FORM_IDS) {
|
||||
assert_eq!((row.name, row.family), (name, family));
|
||||
let meta = META_FORMS
|
||||
.iter()
|
||||
.find(|form| form.name == row.name && form.family == row.family)
|
||||
.unwrap_or_else(|| panic!("{} is not an identified form", row.name));
|
||||
assert_eq!(meta.opcode, row.opcode, "{}", row.name);
|
||||
}
|
||||
}
|
||||
|
||||
#[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);
|
||||
}
|
||||
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);
|
||||
selected += 1;
|
||||
}
|
||||
None => assert!(
|
||||
FORMS.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.
|
||||
for meta in META_FORMS
|
||||
.iter()
|
||||
.filter(|form| form.family != EncodingFamily::Sop2 && form.bytes == 4)
|
||||
{
|
||||
assert_eq!(
|
||||
ScalarAluOp::from_word(meta.bits as u32),
|
||||
None,
|
||||
"{}",
|
||||
meta.name
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -47,8 +47,8 @@ unsafe impl Sync for JitMemory {}
|
||||
impl JitMemory {
|
||||
/// Allocate a new JIT memory region using `MAP_JIT`.
|
||||
pub fn new(capacity: usize) -> Result<Self, JitError> {
|
||||
let page_size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) as usize };
|
||||
let aligned_capacity = (capacity + page_size - 1) & !(page_size - 1);
|
||||
let page_size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
|
||||
let aligned_capacity = aligned_capacity(capacity, page_size)?;
|
||||
|
||||
let ptr = unsafe {
|
||||
libc::mmap(
|
||||
@@ -98,10 +98,7 @@ impl JitMemory {
|
||||
/// Automatically manages `pthread_jit_write_protect_np`, copies bytes,
|
||||
/// flushes data cache and invalidates instruction cache.
|
||||
pub fn emit_block(&mut self, instructions: &[u32]) -> Result<*const u8, JitError> {
|
||||
let bytes_len = instructions.len() * 4;
|
||||
if self.used + bytes_len > self.capacity {
|
||||
return Err(JitError::CapacityExceeded);
|
||||
}
|
||||
let bytes_len = emit_len(self.used, instructions.len(), self.capacity)?;
|
||||
|
||||
let emit_offset = self.used;
|
||||
let dst_ptr = unsafe { self.ptr.as_ptr().add(emit_offset) };
|
||||
@@ -131,6 +128,27 @@ impl JitMemory {
|
||||
}
|
||||
}
|
||||
|
||||
/// Round `capacity` up to a whole number of pages, rejecting an invalid page size
|
||||
/// (`sysconf` failure, zero or not a power of two) and arithmetic overflow.
|
||||
fn aligned_capacity(capacity: usize, page_size: libc::c_long) -> Result<usize, JitError> {
|
||||
let page_size = usize::try_from(page_size)
|
||||
.ok()
|
||||
.filter(|p| p.is_power_of_two())
|
||||
.ok_or(JitError::AllocationFailed(libc::EINVAL))?;
|
||||
capacity
|
||||
.checked_add(page_size - 1)
|
||||
.map(|c| c & !(page_size - 1))
|
||||
.ok_or(JitError::CapacityExceeded)
|
||||
}
|
||||
|
||||
/// Byte length of `count` 4-byte instructions, if they fit after `used` bytes.
|
||||
fn emit_len(used: usize, count: usize, capacity: usize) -> Result<usize, JitError> {
|
||||
count
|
||||
.checked_mul(4)
|
||||
.filter(|len| used.checked_add(*len).is_some_and(|end| end <= capacity))
|
||||
.ok_or(JitError::CapacityExceeded)
|
||||
}
|
||||
|
||||
impl Drop for JitMemory {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
@@ -138,3 +156,68 @@ impl Drop for JitMemory {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn capacity_rounds_up_to_whole_pages() {
|
||||
assert_eq!(aligned_capacity(1, 16384), Ok(16384));
|
||||
assert_eq!(aligned_capacity(16384, 16384), Ok(16384));
|
||||
assert_eq!(aligned_capacity(16385, 16384), Ok(32768));
|
||||
assert_eq!(aligned_capacity(0, 4096), Ok(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_page_size_is_rejected() {
|
||||
for page in [-1, 0, 3, 12288] {
|
||||
assert_eq!(
|
||||
aligned_capacity(4096, page),
|
||||
Err(JitError::AllocationFailed(libc::EINVAL)),
|
||||
"page size {page}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn capacity_rounding_overflow_is_rejected() {
|
||||
assert_eq!(
|
||||
aligned_capacity(usize::MAX, 16384),
|
||||
Err(JitError::CapacityExceeded)
|
||||
);
|
||||
assert_eq!(
|
||||
aligned_capacity(usize::MAX - 16382, 16384),
|
||||
Err(JitError::CapacityExceeded)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn emit_length_is_checked() {
|
||||
assert_eq!(emit_len(0, 4, 16), Ok(16));
|
||||
assert_eq!(emit_len(4, 3, 16), Ok(12));
|
||||
assert_eq!(emit_len(4, 4, 16), Err(JitError::CapacityExceeded));
|
||||
// count * 4 overflows usize.
|
||||
assert_eq!(
|
||||
emit_len(0, usize::MAX / 2, usize::MAX),
|
||||
Err(JitError::CapacityExceeded)
|
||||
);
|
||||
// used + len overflows usize.
|
||||
assert_eq!(
|
||||
emit_len(usize::MAX - 3, 2, usize::MAX),
|
||||
Err(JitError::CapacityExceeded)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn emit_past_capacity_fails_and_leaves_usage_unchanged() {
|
||||
let mut jit = JitMemory::new(1).expect("MAP_JIT allocation");
|
||||
let words = jit.capacity() / 4;
|
||||
assert!(jit.emit_block(&vec![0xD503_201F; words]).is_ok()); // NOP fills the page
|
||||
assert_eq!(
|
||||
jit.emit_block(&[0xD503_201F]),
|
||||
Err(JitError::CapacityExceeded)
|
||||
);
|
||||
assert_eq!(jit.used(), jit.capacity());
|
||||
}
|
||||
}
|
||||
+90
-66
@@ -226,57 +226,102 @@ impl GuestMemory {
|
||||
true
|
||||
}
|
||||
|
||||
/// Write raw bytes into guest memory at the specified address, checking permissions.
|
||||
pub fn write_bytes(&mut self, address: u64, src: &[u8]) -> Result<(), MemoryError> {
|
||||
for region in &mut self.regions {
|
||||
if region.contains(address, src.len()) {
|
||||
if !region.permissions.write {
|
||||
return Err(MemoryError::PermissionViolation {
|
||||
address,
|
||||
required: "write",
|
||||
});
|
||||
}
|
||||
let offset = (address - region.base) as usize;
|
||||
region.data[offset..offset + src.len()].copy_from_slice(src);
|
||||
return Ok(());
|
||||
/// Resolve `[address, address + len)` to `(region index, offset, length)` pieces.
|
||||
///
|
||||
/// An access may span adjacent regions, as it would span adjacent pages, but every
|
||||
/// byte must be mapped and every region must grant `required` (`None` bypasses
|
||||
/// permission checks for the loader). The whole range is checked before any byte
|
||||
/// is copied, so a failed access never partially reads or writes.
|
||||
fn resolve(
|
||||
&self,
|
||||
address: u64,
|
||||
len: usize,
|
||||
required: Option<&'static str>,
|
||||
) -> Result<Vec<(usize, usize, usize)>, MemoryError> {
|
||||
let end = address
|
||||
.checked_add(len as u64)
|
||||
.ok_or(MemoryError::Overflow)?;
|
||||
if len == 0 {
|
||||
return if self.regions.iter().any(|r| r.contains(address, 0)) {
|
||||
Ok(Vec::new())
|
||||
} else {
|
||||
Err(MemoryError::UnmappedAddress(address))
|
||||
};
|
||||
}
|
||||
let mut pieces = Vec::new();
|
||||
let mut cursor = address;
|
||||
for (index, region) in self.regions.iter().enumerate() {
|
||||
let region_end = region.base + region.data.len() as u64;
|
||||
if region_end <= cursor {
|
||||
continue;
|
||||
}
|
||||
if region.base > cursor {
|
||||
break;
|
||||
}
|
||||
let permitted = match required {
|
||||
None => true,
|
||||
Some("read") => region.permissions.read,
|
||||
Some("write") => region.permissions.write,
|
||||
Some(_) => region.permissions.execute,
|
||||
};
|
||||
if let (false, Some(required)) = (permitted, required) {
|
||||
return Err(MemoryError::PermissionViolation { address, required });
|
||||
}
|
||||
let take = (end.min(region_end) - cursor) as usize;
|
||||
pieces.push((index, (cursor - region.base) as usize, take));
|
||||
cursor += take as u64;
|
||||
if cursor == end {
|
||||
return Ok(pieces);
|
||||
}
|
||||
}
|
||||
Err(MemoryError::UnmappedAddress(address))
|
||||
}
|
||||
|
||||
fn read_checked(
|
||||
&self,
|
||||
address: u64,
|
||||
dst: &mut [u8],
|
||||
required: Option<&'static str>,
|
||||
) -> Result<(), MemoryError> {
|
||||
let mut done = 0;
|
||||
for (index, offset, take) in self.resolve(address, dst.len(), required)? {
|
||||
dst[done..done + take]
|
||||
.copy_from_slice(&self.regions[index].data[offset..offset + take]);
|
||||
done += take;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_checked(
|
||||
&mut self,
|
||||
address: u64,
|
||||
src: &[u8],
|
||||
required: Option<&'static str>,
|
||||
) -> Result<(), MemoryError> {
|
||||
let mut done = 0;
|
||||
for (index, offset, take) in self.resolve(address, src.len(), required)? {
|
||||
self.regions[index].data[offset..offset + take]
|
||||
.copy_from_slice(&src[done..done + take]);
|
||||
done += take;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write raw bytes into guest memory at the specified address, checking permissions.
|
||||
pub fn write_bytes(&mut self, address: u64, src: &[u8]) -> Result<(), MemoryError> {
|
||||
self.write_checked(address, src, Some("write"))
|
||||
}
|
||||
|
||||
/// Read raw bytes from guest memory at the specified address, checking permissions.
|
||||
pub fn read_bytes(&self, address: u64, dst: &mut [u8]) -> Result<(), MemoryError> {
|
||||
for region in &self.regions {
|
||||
if region.contains(address, dst.len()) {
|
||||
if !region.permissions.read {
|
||||
return Err(MemoryError::PermissionViolation {
|
||||
address,
|
||||
required: "read",
|
||||
});
|
||||
}
|
||||
let offset = (address - region.base) as usize;
|
||||
dst.copy_from_slice(®ion.data[offset..offset + dst.len()]);
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
Err(MemoryError::UnmappedAddress(address))
|
||||
self.read_checked(address, dst, Some("read"))
|
||||
}
|
||||
|
||||
/// Read an instruction byte from guest memory, verifying execute permission.
|
||||
pub fn fetch_instruction_byte(&self, address: u64) -> Result<u8, MemoryError> {
|
||||
for region in &self.regions {
|
||||
if region.contains(address, 1) {
|
||||
if !region.permissions.execute {
|
||||
return Err(MemoryError::PermissionViolation {
|
||||
address,
|
||||
required: "execute",
|
||||
});
|
||||
}
|
||||
let offset = (address - region.base) as usize;
|
||||
return Ok(region.data[offset]);
|
||||
}
|
||||
}
|
||||
Err(MemoryError::UnmappedAddress(address))
|
||||
let mut buf = [0u8; 1];
|
||||
self.read_checked(address, &mut buf, Some("execute"))?;
|
||||
Ok(buf[0])
|
||||
}
|
||||
|
||||
/// Read a 64-bit integer (little endian) from guest memory.
|
||||
@@ -288,14 +333,9 @@ impl GuestMemory {
|
||||
|
||||
/// Read a 64-bit integer ignoring region read permissions (e.g. loader/relocation phase).
|
||||
pub fn read_u64_bypass(&self, address: u64) -> Result<u64, MemoryError> {
|
||||
for region in &self.regions {
|
||||
if region.contains(address, 8) {
|
||||
let offset = (address - region.base) as usize;
|
||||
let buf: [u8; 8] = region.data[offset..offset + 8].try_into().unwrap();
|
||||
return Ok(u64::from_le_bytes(buf));
|
||||
}
|
||||
}
|
||||
Err(MemoryError::UnmappedAddress(address))
|
||||
let mut buf = [0u8; 8];
|
||||
self.read_checked(address, &mut buf, None)?;
|
||||
Ok(u64::from_le_bytes(buf))
|
||||
}
|
||||
|
||||
/// Write a 64-bit integer (little endian) to guest memory.
|
||||
@@ -305,15 +345,7 @@ impl GuestMemory {
|
||||
|
||||
/// Write a 64-bit integer ignoring region write permissions (e.g. loader/relocation phase).
|
||||
pub fn write_u64_bypass(&mut self, address: u64, value: u64) -> Result<(), MemoryError> {
|
||||
let bytes = value.to_le_bytes();
|
||||
for region in &mut self.regions {
|
||||
if region.contains(address, 8) {
|
||||
let offset = (address - region.base) as usize;
|
||||
region.data[offset..offset + 8].copy_from_slice(&bytes);
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
Err(MemoryError::UnmappedAddress(address))
|
||||
self.write_checked(address, &value.to_le_bytes(), None)
|
||||
}
|
||||
|
||||
/// Read a 32-bit integer (little endian) from guest memory.
|
||||
@@ -330,15 +362,7 @@ impl GuestMemory {
|
||||
|
||||
/// Write a 32-bit integer ignoring region write permissions (e.g. loader/relocation phase).
|
||||
pub fn write_u32_bypass(&mut self, address: u64, value: u32) -> Result<(), MemoryError> {
|
||||
let bytes = value.to_le_bytes();
|
||||
for region in &mut self.regions {
|
||||
if region.contains(address, 4) {
|
||||
let offset = (address - region.base) as usize;
|
||||
region.data[offset..offset + 4].copy_from_slice(&bytes);
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
Err(MemoryError::UnmappedAddress(address))
|
||||
self.write_checked(address, &value.to_le_bytes(), None)
|
||||
}
|
||||
|
||||
/// Read a single byte from guest memory.
|
||||
|
||||
+91
-51
@@ -91,6 +91,17 @@ pub const IMAGE_SCN_MEM_WRITE: u32 = 0x80000000;
|
||||
// Standard Constants
|
||||
pub const IMAGE_FILE_MACHINE_AMD64: u16 = 0x8664;
|
||||
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;
|
||||
|
||||
fn read_u16(bytes: &[u8], at: usize) -> u16 {
|
||||
u16::from_le_bytes([bytes[at], bytes[at + 1]])
|
||||
}
|
||||
|
||||
fn read_u32(bytes: &[u8], at: usize) -> u32 {
|
||||
u32::from_le_bytes(bytes[at..at + 4].try_into().unwrap())
|
||||
}
|
||||
|
||||
impl ParsedPe {
|
||||
/// Parse PE32+ headers from an in-memory byte slice.
|
||||
@@ -105,80 +116,82 @@ impl ParsedPe {
|
||||
}
|
||||
|
||||
let e_lfanew = u32::from_le_bytes(bytes[0x3C..0x40].try_into().unwrap()) as usize;
|
||||
if bytes.len() < e_lfanew + 24 {
|
||||
let coff_offset = e_lfanew.checked_add(4).ok_or(PeError::TooSmall)?;
|
||||
if bytes.len() < coff_offset.checked_add(20).ok_or(PeError::TooSmall)? {
|
||||
return Err(PeError::TooSmall);
|
||||
}
|
||||
|
||||
// 2. PE Signature
|
||||
if &bytes[e_lfanew..e_lfanew + 4] != b"PE\0\0" {
|
||||
if &bytes[e_lfanew..coff_offset] != b"PE\0\0" {
|
||||
return Err(PeError::InvalidPeSignature);
|
||||
}
|
||||
|
||||
// 3. COFF File Header
|
||||
let coff_offset = e_lfanew + 4;
|
||||
let machine = u16::from_le_bytes(bytes[coff_offset..coff_offset + 2].try_into().unwrap());
|
||||
let machine = read_u16(bytes, coff_offset);
|
||||
if machine != IMAGE_FILE_MACHINE_AMD64 {
|
||||
return Err(PeError::UnsupportedMachine(machine));
|
||||
}
|
||||
let number_of_sections = read_u16(bytes, coff_offset + 2);
|
||||
let time_date_stamp = read_u32(bytes, coff_offset + 4);
|
||||
let size_of_optional_header = usize::from(read_u16(bytes, coff_offset + 16));
|
||||
|
||||
let number_of_sections =
|
||||
u16::from_le_bytes(bytes[coff_offset + 2..coff_offset + 4].try_into().unwrap());
|
||||
let time_date_stamp =
|
||||
u32::from_le_bytes(bytes[coff_offset + 4..coff_offset + 8].try_into().unwrap());
|
||||
let size_of_optional_header = u16::from_le_bytes(
|
||||
bytes[coff_offset + 16..coff_offset + 18]
|
||||
.try_into()
|
||||
.unwrap(),
|
||||
) as usize;
|
||||
|
||||
// 4. Optional Header (PE32+ is required)
|
||||
// 4. Optional Header (PE32+ is required). The fixed PE32+ fields end at
|
||||
// NumberOfRvaAndSizes (offset 108, 4 bytes); a shorter header is malformed.
|
||||
let opt_offset = coff_offset + 20;
|
||||
if bytes.len() < opt_offset + size_of_optional_header {
|
||||
let section_table_offset = opt_offset + size_of_optional_header;
|
||||
if bytes.len() < opt_offset + 2 {
|
||||
return Err(PeError::TooSmall);
|
||||
}
|
||||
|
||||
let magic = u16::from_le_bytes(bytes[opt_offset..opt_offset + 2].try_into().unwrap());
|
||||
let magic = read_u16(bytes, opt_offset);
|
||||
if magic != PE32_PLUS_MAGIC {
|
||||
return Err(PeError::InvalidMagic(magic));
|
||||
}
|
||||
if size_of_optional_header < PE32_PLUS_MIN_OPTIONAL_HEADER
|
||||
|| bytes.len() < section_table_offset
|
||||
{
|
||||
return Err(PeError::TooSmall);
|
||||
}
|
||||
|
||||
let entry_point_rva =
|
||||
u32::from_le_bytes(bytes[opt_offset + 16..opt_offset + 20].try_into().unwrap());
|
||||
let entry_point_rva = read_u32(bytes, opt_offset + 16);
|
||||
let image_base =
|
||||
u64::from_le_bytes(bytes[opt_offset + 24..opt_offset + 32].try_into().unwrap());
|
||||
let section_alignment =
|
||||
u32::from_le_bytes(bytes[opt_offset + 32..opt_offset + 36].try_into().unwrap());
|
||||
let file_alignment =
|
||||
u32::from_le_bytes(bytes[opt_offset + 36..opt_offset + 40].try_into().unwrap());
|
||||
let size_of_image =
|
||||
u32::from_le_bytes(bytes[opt_offset + 56..opt_offset + 60].try_into().unwrap());
|
||||
let size_of_headers =
|
||||
u32::from_le_bytes(bytes[opt_offset + 60..opt_offset + 64].try_into().unwrap());
|
||||
let section_alignment = read_u32(bytes, opt_offset + 32);
|
||||
let file_alignment = read_u32(bytes, opt_offset + 36);
|
||||
let size_of_image = read_u32(bytes, opt_offset + 56);
|
||||
let size_of_headers = read_u32(bytes, opt_offset + 60);
|
||||
|
||||
// 5. Section Headers
|
||||
let mut sections = Vec::with_capacity(number_of_sections as usize);
|
||||
let section_table_offset = opt_offset + size_of_optional_header;
|
||||
let section_header_size = 40;
|
||||
|
||||
if bytes.len() < section_table_offset + (number_of_sections as usize * section_header_size)
|
||||
{
|
||||
let table_end = usize::from(number_of_sections)
|
||||
.checked_mul(SECTION_HEADER_SIZE)
|
||||
.and_then(|len| section_table_offset.checked_add(len))
|
||||
.ok_or(PeError::InvalidSectionHeaders)?;
|
||||
if bytes.len() < table_end {
|
||||
return Err(PeError::InvalidSectionHeaders);
|
||||
}
|
||||
|
||||
for i in 0..number_of_sections as usize {
|
||||
let offset = section_table_offset + i * section_header_size;
|
||||
let sec_bytes = &bytes[offset..offset + section_header_size];
|
||||
|
||||
let mut sections = Vec::with_capacity(usize::from(number_of_sections));
|
||||
for sec_bytes in bytes[section_table_offset..table_end].chunks_exact(SECTION_HEADER_SIZE) {
|
||||
// Section name (up to 8 bytes UTF-8 or null-padded ASCII)
|
||||
let name_raw = &sec_bytes[0..8];
|
||||
let name_len = name_raw.iter().position(|&b| b == 0).unwrap_or(8);
|
||||
let name = String::from_utf8_lossy(&name_raw[..name_len]).into_owned();
|
||||
|
||||
let virtual_size = u32::from_le_bytes(sec_bytes[8..12].try_into().unwrap());
|
||||
let virtual_address = u32::from_le_bytes(sec_bytes[12..16].try_into().unwrap());
|
||||
let raw_data_size = u32::from_le_bytes(sec_bytes[16..20].try_into().unwrap());
|
||||
let raw_data_ptr = u32::from_le_bytes(sec_bytes[20..24].try_into().unwrap());
|
||||
let characteristics = u32::from_le_bytes(sec_bytes[36..40].try_into().unwrap());
|
||||
let virtual_size = read_u32(sec_bytes, 8);
|
||||
let virtual_address = read_u32(sec_bytes, 12);
|
||||
let raw_data_size = read_u32(sec_bytes, 16);
|
||||
let raw_data_ptr = read_u32(sec_bytes, 20);
|
||||
let characteristics = read_u32(sec_bytes, 36);
|
||||
|
||||
// The mapped range must fit in the 32-bit RVA space, and raw data must be in the file.
|
||||
virtual_address
|
||||
.checked_add(virtual_size.max(raw_data_size))
|
||||
.ok_or(PeError::InvalidSectionHeaders)?;
|
||||
if raw_data_size > 0 {
|
||||
let raw_end = u64::from(raw_data_ptr) + u64::from(raw_data_size);
|
||||
if raw_end > bytes.len() as u64 {
|
||||
return Err(PeError::InvalidSectionHeaders);
|
||||
}
|
||||
}
|
||||
|
||||
let permissions = MemoryPermissions {
|
||||
read: (characteristics & IMAGE_SCN_MEM_READ) != 0,
|
||||
@@ -197,6 +210,32 @@ impl ParsedPe {
|
||||
});
|
||||
}
|
||||
|
||||
// Mapped section ranges must not overlap. Zero-sized sections map nothing.
|
||||
let mut ranges: Vec<(u32, u32)> = sections
|
||||
.iter()
|
||||
.map(|s| {
|
||||
(
|
||||
s.virtual_address,
|
||||
s.virtual_address + s.virtual_size.max(s.raw_data_size),
|
||||
)
|
||||
})
|
||||
.filter(|(start, end)| start < end)
|
||||
.collect();
|
||||
ranges.sort_unstable();
|
||||
if ranges.windows(2).any(|w| w[1].0 < w[0].1) {
|
||||
return Err(PeError::InvalidSectionHeaders);
|
||||
}
|
||||
|
||||
// The entry point must lie inside an executable section.
|
||||
let entry_ok = sections.iter().any(|s| {
|
||||
s.permissions.execute
|
||||
&& entry_point_rva >= s.virtual_address
|
||||
&& entry_point_rva - s.virtual_address < s.virtual_size.max(s.raw_data_size)
|
||||
});
|
||||
if !entry_ok {
|
||||
return Err(PeError::InvalidEntryPoint);
|
||||
}
|
||||
|
||||
Ok(ParsedPe {
|
||||
machine,
|
||||
number_of_sections,
|
||||
@@ -214,13 +253,12 @@ impl ParsedPe {
|
||||
/// Translate a Relative Virtual Address (RVA) to a raw file offset.
|
||||
pub fn rva_to_file_offset(&self, rva: u32) -> Option<usize> {
|
||||
for sec in &self.sections {
|
||||
let start = sec.virtual_address;
|
||||
let size = std::cmp::max(sec.virtual_size, sec.raw_data_size);
|
||||
if rva >= start && rva < start + size {
|
||||
let diff = (rva - start) as usize;
|
||||
if diff < sec.raw_data_size as usize {
|
||||
return Some(sec.raw_data_ptr as usize + diff);
|
||||
}
|
||||
// Sections are public and may not come from `parse`, so stay checked here.
|
||||
let Some(diff) = rva.checked_sub(sec.virtual_address) else {
|
||||
continue;
|
||||
};
|
||||
if diff < sec.virtual_size.max(sec.raw_data_size) && diff < sec.raw_data_size {
|
||||
return (sec.raw_data_ptr as usize).checked_add(diff as usize);
|
||||
}
|
||||
}
|
||||
None
|
||||
@@ -245,7 +283,9 @@ impl ParsedPe {
|
||||
|
||||
let initial_data = if sec.raw_data_size > 0 && sec.raw_data_ptr > 0 {
|
||||
let start = sec.raw_data_ptr as usize;
|
||||
let end = start + sec.raw_data_size as usize;
|
||||
let end = start
|
||||
.checked_add(sec.raw_data_size as usize)
|
||||
.ok_or(PeError::InvalidSectionHeaders)?;
|
||||
bytes
|
||||
.get(start..end)
|
||||
.ok_or(PeError::InvalidSectionHeaders)?
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Guest memory boundary regression tests (#82).
|
||||
//!
|
||||
//! Expected behavior follows x86-64 data access rules: an access is valid when
|
||||
//! every byte it touches is mapped with the required permission, whether or not
|
||||
//! it is aligned or crosses into an adjacent mapping. A faulting access changes
|
||||
//! nothing.
|
||||
|
||||
use xenora_loader::{GuestMemory, MemoryError, MemoryPermissions as P};
|
||||
|
||||
const A: u64 = 0x10_0000;
|
||||
|
||||
fn two_regions(first: P, second: P) -> GuestMemory {
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region_with_data(A, 0x1000, first, &[0x11; 0x1000])
|
||||
.unwrap();
|
||||
m.map_region_with_data(A + 0x1000, 0x1000, second, &[0x22; 0x1000])
|
||||
.unwrap();
|
||||
m
|
||||
}
|
||||
|
||||
fn bypass_bytes(m: &GuestMemory, at: u64) -> u64 {
|
||||
m.read_u64_bypass(at).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn permissions_are_enforced_per_access_kind() {
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region(A, 0x1000, P::NO_ACCESS).unwrap();
|
||||
m.map_region(A + 0x1000, 0x1000, P::READ_ONLY).unwrap();
|
||||
m.map_region(A + 0x2000, 0x1000, P::READ_WRITE).unwrap();
|
||||
let violation = |address, required| MemoryError::PermissionViolation { address, required };
|
||||
assert_eq!(m.read_u8(A), Err(violation(A, "read")));
|
||||
assert_eq!(
|
||||
m.write_u8(A + 0x1000, 1),
|
||||
Err(violation(A + 0x1000, "write"))
|
||||
);
|
||||
assert_eq!(
|
||||
m.fetch_instruction_byte(A + 0x2000),
|
||||
Err(violation(A + 0x2000, "execute"))
|
||||
);
|
||||
assert!(m.read_u8(A + 0x1000).is_ok());
|
||||
assert!(m.write_u8(A + 0x2000, 1).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn region_end_is_exclusive() {
|
||||
let m = two_regions(P::READ_ONLY, P::NO_ACCESS);
|
||||
assert!(m.read_u32(A + 0xFFC).is_ok());
|
||||
assert!(matches!(
|
||||
m.read_u32(A + 0xFFD),
|
||||
Err(MemoryError::PermissionViolation { .. })
|
||||
));
|
||||
let mut lone = GuestMemory::new();
|
||||
lone.map_region(A, 0x1000, P::READ_ONLY).unwrap();
|
||||
assert_eq!(
|
||||
lone.read_u32(A + 0xFFD),
|
||||
Err(MemoryError::UnmappedAddress(A + 0xFFD))
|
||||
);
|
||||
assert_eq!(
|
||||
lone.read_u8(A - 1),
|
||||
Err(MemoryError::UnmappedAddress(A - 1))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unaligned_accesses_succeed_inside_a_region() {
|
||||
let mut m = two_regions(P::READ_WRITE, P::READ_WRITE);
|
||||
m.write_u64(A + 3, 0x0102_0304_0506_0708).unwrap();
|
||||
assert_eq!(m.read_u64(A + 3), Ok(0x0102_0304_0506_0708));
|
||||
assert_eq!(m.read_u16(A + 3), Ok(0x0708));
|
||||
assert_eq!(m.read_u32(A + 5), Ok(0x0304_0506));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn access_spanning_adjacent_permitted_regions_succeeds() {
|
||||
let mut m = two_regions(P::READ_WRITE, P::READ_WRITE);
|
||||
m.write_u64(A + 0xFFC, 0x8877_6655_4433_2211).unwrap();
|
||||
assert_eq!(m.read_u64(A + 0xFFC), Ok(0x8877_6655_4433_2211));
|
||||
assert_eq!(m.read_u32(A + 0xFFC), Ok(0x4433_2211)); // low half in the first region
|
||||
assert_eq!(m.read_u32(A + 0x1000), Ok(0x8877_6655)); // high half in the second
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spanning_into_a_gap_fails_without_partial_write() {
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region_with_data(A, 0x1000, P::READ_WRITE, &[0x11; 0x1000])
|
||||
.unwrap();
|
||||
m.map_region(A + 0x2000, 0x1000, P::READ_WRITE).unwrap();
|
||||
assert_eq!(
|
||||
m.write_u64(A + 0xFFC, u64::MAX),
|
||||
Err(MemoryError::UnmappedAddress(A + 0xFFC))
|
||||
);
|
||||
assert_eq!(m.read_u32(A + 0xFFC), Ok(0x1111_1111));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spanning_into_a_forbidden_region_fails_atomically() {
|
||||
let mut m = two_regions(P::READ_WRITE, P::READ_ONLY);
|
||||
assert_eq!(
|
||||
m.write_u64(A + 0xFFC, u64::MAX),
|
||||
Err(MemoryError::PermissionViolation {
|
||||
address: A + 0xFFC,
|
||||
required: "write"
|
||||
})
|
||||
);
|
||||
assert_eq!(bypass_bytes(&m, A + 0xFFC), 0x2222_2222_1111_1111);
|
||||
|
||||
let m = two_regions(P::READ_EXECUTE, P::READ_WRITE);
|
||||
assert!(m.read_u64(A + 0xFFC).is_ok());
|
||||
assert!(m.fetch_instruction_byte(A + 0xFFF).is_ok());
|
||||
assert!(m.fetch_instruction_byte(A + 0x1000).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loader_bypass_ignores_permissions_but_not_mapping() {
|
||||
let mut m = two_regions(P::READ_ONLY, P::NO_ACCESS);
|
||||
m.write_u64_bypass(A + 0xFFC, 0x0A0B_0C0D_0E0F_1011)
|
||||
.unwrap();
|
||||
assert_eq!(m.read_u64_bypass(A + 0xFFC), Ok(0x0A0B_0C0D_0E0F_1011));
|
||||
m.write_u32_bypass(A, 7).unwrap();
|
||||
assert_eq!(m.read_u32(A), Ok(7));
|
||||
assert_eq!(
|
||||
m.write_u64_bypass(A + 0x1FFC, 0),
|
||||
Err(MemoryError::UnmappedAddress(A + 0x1FFC))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn address_overflow_is_reported() {
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region(u64::MAX - 0xFFF, 0xFFF, P::READ_WRITE)
|
||||
.unwrap();
|
||||
assert_eq!(m.read_u64(u64::MAX - 3), Err(MemoryError::Overflow));
|
||||
assert_eq!(
|
||||
m.write_u64_bypass(u64::MAX - 3, 0),
|
||||
Err(MemoryError::Overflow)
|
||||
);
|
||||
assert_eq!(
|
||||
m.map_region(u64::MAX, 2, P::READ_WRITE),
|
||||
Err(MemoryError::Overflow)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_mappings_are_rejected_and_adjacent_ones_accepted() {
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region(A, 0x1000, P::READ_WRITE).unwrap();
|
||||
assert_eq!(
|
||||
m.map_region(A + 0xFFF, 0x10, P::READ_WRITE),
|
||||
Err(MemoryError::OverlappingRegion {
|
||||
base: A + 0xFFF,
|
||||
size: 0x10
|
||||
})
|
||||
);
|
||||
assert!(m.map_region(A + 0x1000, 0x10, P::READ_WRITE).is_ok());
|
||||
assert!(m.map_region(A - 0x10, 0x10, P::READ_WRITE).is_ok());
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Malformed-input regression tests for the PE32+ parser (#79).
|
||||
//!
|
||||
//! Every image here is built byte by byte from the Microsoft PE/COFF
|
||||
//! specification layout: DOS header with e_lfanew at 0x3C, "PE\0\0", the
|
||||
//! 20-byte COFF header, the PE32+ optional header (112 fixed bytes before the
|
||||
//! data directories) and 40-byte section headers.
|
||||
|
||||
use xenora_loader::{ParsedPe, PeError, PeSection};
|
||||
|
||||
const RX: u32 = 0x6000_0020; // code | execute | read
|
||||
const R: u32 = 0x4000_0040; // initialized data | read
|
||||
|
||||
struct Sec {
|
||||
va: u32,
|
||||
vsize: u32,
|
||||
raw_ptr: u32,
|
||||
raw_size: u32,
|
||||
flags: u32,
|
||||
}
|
||||
|
||||
/// A two-section image: .text at RVA 0x1000 (file 0x200) and .rdata at RVA 0x2000 (file 0x400).
|
||||
fn valid_sections() -> Vec<Sec> {
|
||||
vec![
|
||||
Sec {
|
||||
va: 0x1000,
|
||||
vsize: 0x100,
|
||||
raw_ptr: 0x200,
|
||||
raw_size: 0x200,
|
||||
flags: RX,
|
||||
},
|
||||
Sec {
|
||||
va: 0x2000,
|
||||
vsize: 0x80,
|
||||
raw_ptr: 0x400,
|
||||
raw_size: 0x200,
|
||||
flags: R,
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
fn build(opt_size: u16, entry: u32, secs: &[Sec]) -> Vec<u8> {
|
||||
let mut pe = vec![0u8; 0x600];
|
||||
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(&(secs.len() as u16).to_le_bytes());
|
||||
pe[coff + 16..coff + 18].copy_from_slice(&opt_size.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(&entry.to_le_bytes());
|
||||
pe[opt + 24..opt + 32].copy_from_slice(&0x1_4000_0000u64.to_le_bytes());
|
||||
pe[opt + 32..opt + 36].copy_from_slice(&0x1000u32.to_le_bytes());
|
||||
pe[opt + 36..opt + 40].copy_from_slice(&0x200u32.to_le_bytes());
|
||||
pe[opt + 56..opt + 60].copy_from_slice(&0x3000u32.to_le_bytes());
|
||||
pe[opt + 60..opt + 64].copy_from_slice(&0x200u32.to_le_bytes());
|
||||
let table = opt + usize::from(opt_size);
|
||||
for (i, s) in secs.iter().enumerate() {
|
||||
let h = table + i * 40;
|
||||
pe[h..h + 5].copy_from_slice(b".sect");
|
||||
pe[h + 8..h + 12].copy_from_slice(&s.vsize.to_le_bytes());
|
||||
pe[h + 12..h + 16].copy_from_slice(&s.va.to_le_bytes());
|
||||
pe[h + 16..h + 20].copy_from_slice(&s.raw_size.to_le_bytes());
|
||||
pe[h + 20..h + 24].copy_from_slice(&s.raw_ptr.to_le_bytes());
|
||||
pe[h + 36..h + 40].copy_from_slice(&s.flags.to_le_bytes());
|
||||
}
|
||||
pe
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn valid_image_parses_maps_and_translates() {
|
||||
let bytes = build(112, 0x1010, &valid_sections());
|
||||
let pe = ParsedPe::parse(&bytes).expect("valid image");
|
||||
assert_eq!(pe.entry_point_rva, 0x1010);
|
||||
assert_eq!(pe.sections.len(), 2);
|
||||
assert_eq!(pe.rva_to_file_offset(0x1010), Some(0x210));
|
||||
assert_eq!(pe.rva_to_file_offset(0x2004), Some(0x404));
|
||||
assert_eq!(pe.rva_to_file_offset(0x3000), None);
|
||||
let loaded = pe.load_into_memory(&bytes).expect("load");
|
||||
assert_eq!(loaded.entry_point, 0x1_4000_1010);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn optional_header_with_data_directories_is_accepted() {
|
||||
let bytes = build(240, 0x1000, &valid_sections());
|
||||
assert!(ParsedPe::parse(&bytes).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repository_fixtures_still_parse_and_load() {
|
||||
let root = concat!(env!("CARGO_MANIFEST_DIR"), "/../..");
|
||||
for path in [
|
||||
"fixtures/pe/trusted-runner.exe",
|
||||
"experiments/x1/fixtures/x2.exe",
|
||||
"experiments/x1/fixtures/x3.exe",
|
||||
"experiments/x1/fixtures/x4-17.exe",
|
||||
"experiments/x1/fixtures/x4-93.exe",
|
||||
"experiments/x1/fixtures/x5.exe",
|
||||
"experiments/x1/fixtures/x6.exe",
|
||||
] {
|
||||
let bytes = std::fs::read(format!("{root}/{path}")).expect(path);
|
||||
let pe = ParsedPe::parse(&bytes).unwrap_or_else(|e| panic!("{path}: {e}"));
|
||||
pe.load_into_memory(&bytes)
|
||||
.unwrap_or_else(|e| panic!("{path}: {e}"));
|
||||
}
|
||||
}
|
||||
|
||||
/// Reproducer from #79: 90 bytes, SizeOfOptionalHeader = 2, file ends after the magic.
|
||||
#[test]
|
||||
fn truncated_optional_header_is_rejected_not_panicking() {
|
||||
let mut bytes = vec![0u8; 90];
|
||||
bytes[0..2].copy_from_slice(b"MZ");
|
||||
bytes[0x3C..0x40].copy_from_slice(&0x40u32.to_le_bytes());
|
||||
bytes[0x40..0x44].copy_from_slice(b"PE\0\0");
|
||||
bytes[0x44..0x46].copy_from_slice(&0x8664u16.to_le_bytes());
|
||||
bytes[0x54..0x56].copy_from_slice(&2u16.to_le_bytes());
|
||||
bytes[0x58..0x5A].copy_from_slice(&0x020Bu16.to_le_bytes());
|
||||
assert_eq!(ParsedPe::parse(&bytes).unwrap_err(), PeError::TooSmall);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn optional_header_shorter_than_pe32_plus_fixed_fields_is_rejected() {
|
||||
for opt_size in [24u16, 64, 111] {
|
||||
let bytes = build(opt_size, 0x1000, &valid_sections());
|
||||
assert_eq!(
|
||||
ParsedPe::parse(&bytes).unwrap_err(),
|
||||
PeError::TooSmall,
|
||||
"{opt_size}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn e_lfanew_past_end_of_file_is_rejected() {
|
||||
let mut bytes = build(112, 0x1000, &valid_sections());
|
||||
bytes[0x3C..0x40].copy_from_slice(&u32::MAX.to_le_bytes());
|
||||
assert_eq!(ParsedPe::parse(&bytes).unwrap_err(), PeError::TooSmall);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn section_table_past_end_of_file_is_rejected() {
|
||||
let mut bytes = build(112, 0x1000, &valid_sections());
|
||||
bytes[0x46..0x48].copy_from_slice(&u16::MAX.to_le_bytes());
|
||||
assert_eq!(
|
||||
ParsedPe::parse(&bytes).unwrap_err(),
|
||||
PeError::InvalidSectionHeaders
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn section_range_overflowing_rva_space_is_rejected() {
|
||||
let mut secs = valid_sections();
|
||||
secs[1].va = 0xFFFF_F000;
|
||||
secs[1].vsize = 0x2000;
|
||||
let bytes = build(112, 0x1000, &secs);
|
||||
assert_eq!(
|
||||
ParsedPe::parse(&bytes).unwrap_err(),
|
||||
PeError::InvalidSectionHeaders
|
||||
);
|
||||
}
|
||||
|
||||
/// Reproducer from #79: lookup over a section whose end overflows u32 must not panic or wrap.
|
||||
#[test]
|
||||
fn rva_lookup_with_overflowing_section_returns_none() {
|
||||
let bytes = build(112, 0x1000, &valid_sections());
|
||||
let mut pe = ParsedPe::parse(&bytes).unwrap();
|
||||
pe.sections.insert(
|
||||
0,
|
||||
PeSection {
|
||||
name: "wrap".into(),
|
||||
virtual_address: 0xFFFF_FF00,
|
||||
virtual_size: 0x200,
|
||||
raw_data_ptr: 0x200,
|
||||
raw_data_size: 0x200,
|
||||
characteristics: R,
|
||||
permissions: pe.sections[1].permissions,
|
||||
},
|
||||
);
|
||||
// A wrapped end (0xFFFF_FF00 + 0x200 = 0x100) would wrongly capture RVA 0x80.
|
||||
assert_eq!(pe.rva_to_file_offset(0x80), None);
|
||||
assert_eq!(pe.rva_to_file_offset(0xFFFF_FF10), Some(0x210));
|
||||
assert_eq!(pe.rva_to_file_offset(0x1004), Some(0x204));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_sections_are_rejected() {
|
||||
let mut secs = valid_sections();
|
||||
secs[1].va = 0x1100; // .text maps 0x1000..0x1200 (raw size wins)
|
||||
let bytes = build(112, 0x1000, &secs);
|
||||
assert_eq!(
|
||||
ParsedPe::parse(&bytes).unwrap_err(),
|
||||
PeError::InvalidSectionHeaders
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adjacent_sections_are_accepted() {
|
||||
let mut secs = valid_sections();
|
||||
secs[1].va = 0x1200;
|
||||
let bytes = build(112, 0x1000, &secs);
|
||||
assert!(ParsedPe::parse(&bytes).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncated_section_data_is_rejected() {
|
||||
let mut secs = valid_sections();
|
||||
secs[1].raw_size = 0x201; // file is 0x600 bytes; 0x400 + 0x201 runs one byte past the end
|
||||
let bytes = build(112, 0x1000, &secs);
|
||||
assert_eq!(
|
||||
ParsedPe::parse(&bytes).unwrap_err(),
|
||||
PeError::InvalidSectionHeaders
|
||||
);
|
||||
|
||||
secs[1].raw_size = 0x200;
|
||||
secs[1].raw_ptr = u32::MAX;
|
||||
let bytes = build(112, 0x1000, &secs);
|
||||
assert_eq!(
|
||||
ParsedPe::parse(&bytes).unwrap_err(),
|
||||
PeError::InvalidSectionHeaders
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entry_point_outside_executable_section_is_rejected() {
|
||||
// Past the end of .text's mapped range, in non-executable .rdata, and outside every section.
|
||||
for entry in [0x1200, 0x2000, 0x0, u32::MAX] {
|
||||
let bytes = build(112, entry, &valid_sections());
|
||||
assert_eq!(
|
||||
ParsedPe::parse(&bytes).unwrap_err(),
|
||||
PeError::InvalidEntryPoint,
|
||||
"entry {entry:#x}"
|
||||
);
|
||||
}
|
||||
// Last byte of .text is still inside it.
|
||||
assert!(ParsedPe::parse(&build(112, 0x11FF, &valid_sections())).is_ok());
|
||||
}
|
||||
+9
-7
@@ -10,21 +10,24 @@ either path. The [changelog](../CHANGELOG.md) records notable changes.
|
||||
|
||||
## Architecture and technical design
|
||||
|
||||
- [Interface contracts](interfaces.md) — Shader inputs, guest services, native command submission, and synthetic textures.
|
||||
- [Interface contracts](interfaces.md) — Translated shader stages, guest services, native command submission, and synthetic textures.
|
||||
- [Fixture memory model](adr/0003-demo-memory-model.md) and [CPU boundary](adr/0004-cpu-boundary.md) — Buffer bindings, guest address translation, and dependency direction.
|
||||
|
||||
## Native Metal graphics
|
||||
|
||||
- [Translated offscreen stages](interfaces.md#translated-offscreen-stages) — Translated vertex and pixel stages for the bounded gfx1030 subset.
|
||||
- [Blend and depth passes](interfaces.md) — Native blend and depth graphics passes with per-draw state.
|
||||
- [Apple GPU evidence](research/apple-gpu.md) and [host lab record](research/host-lab.md) — Observed behavior and historical floating-point results.
|
||||
|
||||
## RDNA 2 decoding and shader translation
|
||||
|
||||
- [Instruction coverage](shaders/instruction-coverage.md) — Desktop gfx1030 instruction forms, operand limits, and CPU and GPU results.
|
||||
- [Semantic coverage](shaders/semantic-coverage.md) — Generated per-family counts of identified, declared, decoded, lowered and verified gfx1030 forms.
|
||||
- [SOP2 scalar ALU](shaders/scalar-alu.md) — Supported scalar add, subtract and bitwise forms, their SCC rules and sources.
|
||||
- [Semantic registry](shaders/semantic-registry.md) — How to add an instruction form: registry fields, validation, generation and the independence rule.
|
||||
- [VOPC integer compares](shaders/vector-compare.md) — Wave32 compare forms, the VCC/EXEC contract, runtime `s_cbranch_vccz` and the Metal mapping.
|
||||
- [Metal Shading Language generation](shaders/msl.md) and [independent CPU reference](shaders/reference-interpreter.md) — Translation rules and separate CPU execution models.
|
||||
|
||||
## Native Metal backend
|
||||
|
||||
- [Compute interface](interfaces.md#gfx1030-compute-fixtures) — Resource limits, dispatch, completion, and profiling.
|
||||
- [Apple GPU evidence](research/apple-gpu.md) and [host lab record](research/host-lab.md) — Observed behavior and historical floating-point results.
|
||||
|
||||
## Guest CPU and runtime experiments
|
||||
|
||||
- [Guest experiment guide](../experiments/x1/README.md) — Bounded x86-64 execution, executable loading, experimental services, native compute, and offscreen rendering.
|
||||
@@ -36,7 +39,6 @@ either path. The [changelog](../CHANGELOG.md) records notable changes.
|
||||
- [Engineering progress](progress.md) — Verification commands, metric definitions, and open release gates.
|
||||
- [Test inventory comparison](testing/test-inventory.md) — Detect missing or newly ignored Cargo tests across commits.
|
||||
- [Persistent resource and translated rendering acceptance](testing/x9-acceptance.md) — Pinned upstream tests, native ARM64 results and unsupported cases.
|
||||
|
||||
- [Baseline acceptance](testing/phase-02-baseline.md), [Phase 01 assurance](testing/phase01-assurance.md), and [independent reviews](testing/review-log.md) — Candidate-specific results and release findings.
|
||||
- [Mutation testing](testing/mutation.md) and [benchmark protocol](testing/benchmarks.md) — Test sensitivity, benchmark inputs, and timing requirements.
|
||||
|
||||
|
||||
@@ -186,3 +186,24 @@ multiply forms. The graphics ABI also supports register and finite
|
||||
literal moves. Unsupported stage instructions or export combinations
|
||||
fail explicitly. The Xbox graphics ABI, hardware-specific floating-point
|
||||
modes, image instructions, and additional varyings remain unsupported.
|
||||
|
||||
## Graphics draw and blend contracts
|
||||
|
||||
`NativeCompute::render_indexed` issues one real `drawIndexedPrimitives` call
|
||||
per draw (up to 16) on a 16- or 32-bit index buffer with a start index and a
|
||||
signed base vertex, into an offscreen RGBA8 target. A draw can sample an
|
||||
original BC1 texture uploaded natively. Before encoding anything it rejects
|
||||
malformed draws; execution checks each draw in turn.
|
||||
|
||||
`NativeCompute::render_blend` draws up to 16 flat-coloured triangles in order
|
||||
into an offscreen RGBA8 target. Each draw has its own colour write mask and
|
||||
either blending disabled or separate RGB and alpha blend factors and
|
||||
operations. Colours are compared per channel against expectations derived
|
||||
independently from the public Metal blend equations.
|
||||
|
||||
`NativeCompute::render_depth` draws up to 16 triangles in order with an
|
||||
optional `Depth32Float` attachment, a chosen clear depth and a per-draw depth
|
||||
compare function. Colour and the stored depth are both read back.
|
||||
|
||||
These passes are checked on the GPU with Metal validation against expectations
|
||||
derived independently from the public semantics; synthetic fixtures only.
|
||||
+9
-15
@@ -1,12 +1,16 @@
|
||||
# Engineering progress
|
||||
|
||||
**NOT RELEASE-READY.** The three-fixture demo checkpoint was pushed at `96cff7c66e55f1e4693ace19577c207795258d5c` and its [Native Rust checks](https://github.com/ranveersoni98/Xenora/actions/runs/45001680455) passed. See the [current assurance report](testing/phase01-assurance.md) for candidate evidence and the [historical engineering report](testing/phase01-checkpoint.md) for the initial checkpoint.
|
||||
Xenora is an experimental research project. Verified work is restricted to
|
||||
independently authored synthetic programs and shaders; commercial game
|
||||
execution and authentic Xbox startup are unsupported. Progress is measured by
|
||||
reproducible tests, not by estimated game compatibility percentages.
|
||||
|
||||
## Reading the progress graphic
|
||||
|
||||
- **Decoded forms** counts rows marked decoded in the [status registry](status.toml), out of all rows in that reviewed gfx1030 instruction inventory.
|
||||
- **Accepted Metal forms** counts rows with accepted native fixture readback, over the same inventory. See the [form-by-form results](shaders/instruction-coverage.md) and [implementation checkpoint](testing/phase-02-baseline.md#implementation-checkpoint) for class A evidence from Apple M5. Arithmetic shift has its own [fixture record](../fixtures/rdna2/ashr.md); its CPU path now has explicit checkpoints, a positive-value control and independent-oracle coverage, while its native readback remains local evidence with independent acceptance open.
|
||||
- **Accepted guest milestones** counts the recorded fixture demonstrations for native guest instruction execution (X1), executable loading (X2), guest-to-GPU command submission (X3), and guest-driven Metal rendering (X4), out of those four milestones. See the [guest acceptance record](testing/phase-02-baseline.md#track-b--guest-execution).
|
||||
- **Accepted Metal forms** counts rows with accepted native fixture readback, over the same inventory. See the [form-by-form results](shaders/instruction-coverage.md) and [implementation checkpoint](testing/phase-02-baseline.md#implementation-checkpoint) for class A evidence from Apple M5.
|
||||
|
||||
## Feature status
|
||||
|
||||
<!-- status:features:start -->
|
||||
| Feature | Target | Implementation | Correctness | Hardware | Evidence | Limits |
|
||||
@@ -35,18 +39,8 @@ scripts/audit/claims.sh
|
||||
scripts/audit/dependencies.sh
|
||||
```
|
||||
|
||||
The independent CPU validation tests are part of the workspace. The native suite and optional LLVM oracle run separately so CPU-only CI can report them accurately. Final local logs are under ignored `artifacts/phase01/`. Keep the historical lab and candidate logs separate.
|
||||
|
||||
## Dual-track execution
|
||||
|
||||
The [dual-track baseline](testing/phase-02-baseline.md) records Phase 02
|
||||
GPU prerequisites and the separate guest execution milestones.
|
||||
The independent CPU validation tests are part of the workspace. The native suite and optional LLVM oracle run separately so CPU-only CI can report them accurately. Final local logs are under ignored `artifacts/`. Keep the historical lab and candidate logs separate.
|
||||
|
||||
## Remaining work
|
||||
|
||||
See the [assurance checkpoint](testing/phase01-assurance.md) for the original gate ledger and commands, and the [independent review](testing/review-log.md#phase-01-evidence-recheck-at-4b9a4ce) for later findings.
|
||||
|
||||
1. The independent reference (G5), LLVM decoder comparison (G6), and mutation testing (G7) passed at the Phase 01 candidate. The [integrated review](testing/mutation.md#integrated-source-campaign-at-4b9a4ce) confirmed 359 of 361 non-equivalent source mutants killed, all 44 independent-oracle kills and all 12 native semantic kills. The form-by-form validation report is in the [validation inventory](../tests/validation/README.md).
|
||||
2. Parser fuzzing (G9) passed for the Phase 01 candidate. Native decoder and reference runs at `4b9a4ce` exited 0 after 123,522,954 and 240,077,291 executions respectively, each in 601 seconds. The fixture run at `aff46b0` exited 0 after 244,422,168 executions in 601 seconds. The fuzz source, dependencies, script and fixture inputs are identical between these commits. Logs and executable hashes are under `artifacts/g9/4b9a4ce-20261123T041525Z/`. Phase 02 source changes require their own assurance.
|
||||
3. Finish benchmark corpus and protocol coverage before rerunning on AC and an idle system. Preserve the [exploratory battery and AC records](testing/benchmarks.md).
|
||||
4. Close independent claims, status, history and review findings against the integrated candidate. Verify the [runtime redistribution blockers](licenses.md#runtime-redistribution-review) before closing the redistribution gate (G11).
|
||||
See the [current limitations](../README.md#current-limitations) for the outstanding items. The active research steps are: finish the remaining RDNA2 wave execution and mesh stages, translated texture sampling, broader resource binding and synchronization. Close independent claims, status, history and review findings against the current candidates, and verify the [runtime redistribution blockers](licenses.md#runtime-redistribution-review) before closing the redistribution gate (G11).
|
||||
@@ -16,6 +16,18 @@ operands, writes a normal SGPR (s0-s105) and sets SCC.
|
||||
| `s_xor_b32` | S0 ^ S1 | D != 0 |
|
||||
|
||||
Sources are normal SGPRs, inline integers (-16 to 64) or one literal word.
|
||||
|
||||
These nine 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
|
||||
contradictions (for example a carry-in on a bitwise form, or a signed form whose
|
||||
SCC is a carry). It then generates `crates/isa/src/semantics_gen.rs`, which holds
|
||||
the decoder's opcode dispatch and `ScalarAluOp`'s mnemonic, SCC read and
|
||||
evaluation through the shared primitives in `crates/isa/src/primitive.rs`. Run
|
||||
`python3 crates/isa/generate_semantics.py validate`, `generate` or `--check`
|
||||
(Python 3.11 or newer). The reference and independent interpreters do not use
|
||||
the registry.
|
||||
`v_mov_b32_e32` may read a normal SGPR, so the results can reach vector code.
|
||||
|
||||
## Sources
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
# gfx1030 semantic coverage
|
||||
|
||||
<!-- Generated by scripts/audit/semantic_coverage.py. -->
|
||||
|
||||
Identified forms come from the AMD RDNA 2 instruction snapshot. Declared forms
|
||||
come from the semantic registry. Decoder support is the decoder's hand-written
|
||||
list plus the registry forms compiled into crates/isa/src/semantics_gen.rs.
|
||||
|
||||
The status inventory records LLVM three-way encoding checks, intermediate
|
||||
representation (IR) and Metal Shading Language (MSL) lowering, and fixture
|
||||
verification. IR and MSL share the inventory's lowering field. Reference
|
||||
verification requires an implemented reference and verified CPU fixture.
|
||||
Metal verification requires a verified GPU fixture. Both also require a decoding row. Local readbacks pending
|
||||
acceptance remain outside the verified count. All results concern synthetic fixtures.
|
||||
|
||||
| Family | Identified | Encoding-validated | Declared | Decoder-supported | IR | MSL | Reference-verified | Metal-verified | Unsupported operand variants |
|
||||
| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
|
||||
| DS | 123 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||
| EXP | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 |
|
||||
| FLAT | 54 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||
| GLOBAL | 57 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||
| MIMG | 130 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 |
|
||||
| MTBUF | 16 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||
| 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 |
|
||||
| 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 |
|
||||
| VOP1 | 81 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 |
|
||||
| VOP2 | 47 | 8 | 0 | 8 | 8 | 8 | 7 | 7 | 0 |
|
||||
| VOP3 | 416 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 |
|
||||
| VOP3P | 29 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||
| VOP3SDST | 10 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||
| VOPC | 190 | 12 | 0 | 12 | 12 | 12 | 0 | 0 | 0 |
|
||||
| **Total** | 1465 | 42 | 9 | 46 | 42 | 42 | 18 | 18 | 12 |
|
||||
|
||||
## Unsupported operand variants
|
||||
|
||||
The table counts distinct variant names per family across registry operand rules.
|
||||
|
||||
| Family | Operand rule | Unsupported variants |
|
||||
| --- | --- | --- |
|
||||
| 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` |
|
||||
@@ -0,0 +1,214 @@
|
||||
# Adding an instruction through the semantic registry
|
||||
|
||||
The semantic registry is a data file that declares what each supported gfx1030
|
||||
instruction form does. A generator checks it and turns it into Rust tables that
|
||||
the decoder uses. This page explains where entries live, what each field means,
|
||||
how to check and regenerate the tables, and what the generator does not do for
|
||||
you.
|
||||
|
||||
The registry covers the nine SOP2 forms listed in [SOP2 scalar ALU](scalar-alu.md).
|
||||
|
||||
## Files
|
||||
|
||||
| File | Role |
|
||||
| --- | --- |
|
||||
| `crates/isa/semantics/rdna2.toml` | The registry. Data only: every value comes from a closed vocabulary. |
|
||||
| `crates/isa/generate_semantics.py` | Validates the registry and writes the Rust tables. Python 3.11 or newer, standard library only. |
|
||||
| `crates/isa/data/rdna2.jsonl` | Pinned snapshot of the AMD machine-readable ISA XML, used to cross-check identity and operands. |
|
||||
| `crates/isa/src/semantics_gen.rs` | Generated output. Never edit it by hand. |
|
||||
| `crates/isa/src/semantics.rs` | The Rust types the generated tables use (`FormSemantics`, `Operation`, `SccEffect` and so on). |
|
||||
| `crates/isa/src/primitive.rs` | The shared integer primitives that the generated `evaluate` calls. |
|
||||
| `tests/semantics_generator/` | Unit tests for the generator. |
|
||||
|
||||
## Fields
|
||||
|
||||
The top of the file holds:
|
||||
|
||||
- `schema`: must be `1`.
|
||||
- `architecture`: must be `"gfx1030"`.
|
||||
- `source_sha256`: must equal the `sha256` on the `source` line of
|
||||
`crates/isa/data/rdna2.jsonl`, so the registry is always checked against the
|
||||
snapshot it was written for.
|
||||
- `[documents.<name>]`: the public documents that spec references cite. Only
|
||||
`guide` (the AMD RDNA 2 ISA reference guide) and `xml` (the AMD
|
||||
machine-readable ISA) are allowed, and each must match the title and file
|
||||
pinned in the generator, so a citation cannot point at another file.
|
||||
- `[operand_rules.<name>]`: an operand rule shared by a whole family. The
|
||||
decoder implements each rule once, and the generator only accepts a rule
|
||||
whose declaration matches the decoder's implementation exactly. Today there
|
||||
is one rule, `sop2_sgpr`: an SGPR destination `s0`-`s105`, two scalar sources
|
||||
(an SGPR, an inline integer -16 to 64, or a literal word) and at most one
|
||||
literal. Its `unsupported` list names the encodings the rule rejects, which
|
||||
stay unsupported instead of being guessed. The list must name exactly the
|
||||
encodings the decoder rejects.
|
||||
|
||||
Each `[[form]]` entry has exactly these fields. A missing or unknown field is an
|
||||
error.
|
||||
|
||||
| Field | Meaning | Allowed values |
|
||||
| --- | --- | --- |
|
||||
| `name` | XML instruction name, the form's stable identity | upper-case, e.g. `S_ADD_U32` |
|
||||
| `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`) |
|
||||
| `width` | Operand and result width in bits | `32` |
|
||||
| `scc` | What the form writes to SCC | `carry_out`, `borrow`, `signed_overflow`, `nonzero`, `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` |
|
||||
| `spec` | References `{ document, section, page }` | at least one `guide` reference with a page above 0 |
|
||||
| `verify` | Evidence the form needs before it counts as verified | `reference`, `independent`, `metal`, `llvm_encoding` |
|
||||
|
||||
The `operation` and `signedness` pair picks one primitive, and that primitive
|
||||
fixes the `scc` value:
|
||||
|
||||
| `operation` / `signedness` | Required `scc` | Primitive | Reads carry-in |
|
||||
| --- | --- | --- | --- |
|
||||
| `add` / `unsigned` | `carry_out` | `add_carry_u32` | allowed |
|
||||
| `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 |
|
||||
|
||||
Behaviour is chosen only from these declared fields, never from the mnemonic.
|
||||
|
||||
## What the validator checks
|
||||
|
||||
`validate` reports every error it finds, not only the first (a form with a missing field is not checked further). Besides the
|
||||
vocabularies above, it rejects:
|
||||
|
||||
- contradictions: a declared `scc` or `carry_in` that the primitive does not
|
||||
have, `bitwise` on an arithmetic operation or the reverse;
|
||||
- duplicates: the same `name`, the same `(family, opcode)` or the same
|
||||
`variant` declared twice;
|
||||
- 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
|
||||
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;
|
||||
- operand rules the decoder does not implement, or whose declaration differs
|
||||
from the implemented one;
|
||||
- wrong types: a float width, a boolean schema, an opcode or page outside
|
||||
0-65535, or a reserved variant name such as `Self`.
|
||||
|
||||
CI runs `generate_semantics.py --check`, `scripts/audit/semantic_coverage.py
|
||||
--check` and both Python test suites next to the existing
|
||||
`generate_rdna2_meta.py --check`. Both scripts stop with a clear message on
|
||||
Python older than 3.11.
|
||||
|
||||
## What the generator does not do
|
||||
|
||||
- **The XML gives identity and encodings only.** The snapshot confirms the
|
||||
name, family, opcode, operand fields, widths, number formats and whether SCC
|
||||
is read or written. It says nothing about the arithmetic. Behaviour comes from
|
||||
the AMD guide, cited in `spec`, through the closed primitive table.
|
||||
- **It does not invent behaviour.** A form whose operation, signedness or
|
||||
operand rule is not already implemented is rejected. Adding a new operation
|
||||
means hand-writing a primitive in `primitive.rs`, a variant in
|
||||
`semantics.rs` and a row in the generator's vocabulary tables, reviewed like
|
||||
any other code.
|
||||
- **Undeclared forms stay unsupported.** The generated `from_word` returns
|
||||
`None` for every opcode not in the registry, and the decoder reports
|
||||
`UnsupportedOpcode`. Nothing falls back to a guess or a no-op.
|
||||
- **It does not write tests or reference semantics.** The reference
|
||||
interpreter (`crates/ref`) and the independent interpreter
|
||||
(`tests/validation/independent_ref.rs`) never read the registry or the
|
||||
generated code, and their known-answer tests are written by hand from the
|
||||
guide. That independence is what lets them catch a wrong registry entry; keep
|
||||
it when you add a form. Agreement with these references is agreement with a
|
||||
reading of the public AMD guide, not with Xbox hardware.
|
||||
|
||||
## Commands
|
||||
|
||||
Run these from the repository root. `python3` must be 3.11 or newer.
|
||||
|
||||
```sh
|
||||
# Check the registry only.
|
||||
python3 crates/isa/generate_semantics.py validate
|
||||
|
||||
# Validate, then rewrite crates/isa/src/semantics_gen.rs.
|
||||
python3 crates/isa/generate_semantics.py generate
|
||||
|
||||
# Validate and regenerate in memory; exit 1 if the committed file is stale. Never writes.
|
||||
python3 crates/isa/generate_semantics.py --check
|
||||
|
||||
# Generator unit tests.
|
||||
python3 -m unittest discover -s tests/semantics_generator
|
||||
|
||||
# The XML metadata tables the registry is cross-checked against are still current.
|
||||
python3 crates/isa/generate_rdna2_meta.py --check
|
||||
|
||||
# Rust tests of the generated tables and the decoder that uses them.
|
||||
cargo test --locked -p xenora-isa -p xenora-decoder
|
||||
|
||||
# Independent CPU validation.
|
||||
cargo test --locked -p xenora-semantic-review
|
||||
|
||||
# Native GPU correctness on Apple silicon.
|
||||
scripts/test-gpu.sh
|
||||
```
|
||||
|
||||
The LLVM encoding corpus check needs an LLVM build with the AMDGPU target:
|
||||
|
||||
```sh
|
||||
python3 crates/isa/tests/llvm/corpus.py --llvm-bin /path/to/llvm/bin --check
|
||||
```
|
||||
|
||||
## Worked example: `s_addc_u32`
|
||||
|
||||
`s_addc_u32` adds two 32-bit sources plus SCC and writes the carry-out of
|
||||
bit 31 to SCC (guide section 12.1, page 102; SCC rules in section 5.3, page 33).
|
||||
Its registry entry is:
|
||||
|
||||
```toml
|
||||
[[form]]
|
||||
name = "S_ADDC_U32"
|
||||
family = "SOP2"
|
||||
opcode = 4
|
||||
variant = "AddcU32"
|
||||
operation = "add"
|
||||
signedness = "unsigned"
|
||||
carry_in = "scc"
|
||||
width = 32
|
||||
scc = "carry_out"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 102 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
```
|
||||
|
||||
How each field is checked:
|
||||
|
||||
1. The XML snapshot has a default `ENC_SOP2` variant named `S_ADDC_U32` with
|
||||
opcode 4, so `name`, `family` and `opcode` agree.
|
||||
2. That XML variant reads and writes SCC, which matches `carry_in = "scc"` and
|
||||
an `scc` other than `unchanged`.
|
||||
3. `add` / `unsigned` selects `add_carry_u32`, which requires
|
||||
`scc = "carry_out"` and accepts a carry-in.
|
||||
4. The XML `SDST`, `SSRC0` and `SSRC1` operands are 32-bit `FMT_NUM_U32`
|
||||
fields, which matches `width = 32`, `unsigned` and the `sop2_sgpr` rule.
|
||||
|
||||
From this entry the generator emits, in `semantics_gen.rs`, the `AddcU32`
|
||||
variant of `ScalarAluOp`, its `from_word` arm (`0x8200_0000`), the mnemonic
|
||||
`s_addc_u32`, `reads_scc() == true`, an `evaluate` arm that calls
|
||||
`primitive::add_carry_u32(src0, src1, carry_in)`, and a `FormSemantics` row.
|
||||
|
||||
To add a form the same way:
|
||||
|
||||
1. Confirm its behaviour in the AMD guide and note the section and page.
|
||||
2. Check that an existing primitive and operand rule cover it. If not, the
|
||||
form needs hand-written code first (see above).
|
||||
3. Add a `[[form]]` entry and run `validate` until it reports no errors.
|
||||
4. Run `generate` and commit the registry and `semantics_gen.rs` together.
|
||||
5. Add known-answer tests to the reference and independent interpreters by
|
||||
hand, then run every command in [Commands](#commands).
|
||||
@@ -0,0 +1,326 @@
|
||||
"""Generate the gfx1030 semantic coverage report from the checked-in inventories."""
|
||||
|
||||
import argparse
|
||||
from collections import Counter, defaultdict
|
||||
import difflib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import runpy
|
||||
import sys
|
||||
try:
|
||||
import tomllib
|
||||
except ModuleNotFoundError: # pragma: no cover - depends on the interpreter
|
||||
sys.exit("semantic_coverage.py needs Python 3.11 or newer (tomllib)")
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
SNAPSHOT = Path("crates/isa/data/rdna2.jsonl")
|
||||
REGISTRY = Path("crates/isa/semantics/rdna2.toml")
|
||||
DECODER = Path("crates/decoder/src/lib.rs")
|
||||
GENERATED = Path("crates/isa/src/semantics_gen.rs")
|
||||
STATUS = Path("docs/status.toml")
|
||||
REPORT = Path("docs/shaders/semantic-coverage.md")
|
||||
|
||||
DECODER_HEADER = re.compile(
|
||||
r'const HANDWRITTEN_FORMS: \[\(&str, EncodingFamily\); (\d+)\] = \['
|
||||
)
|
||||
# The decoder's full list is its hand-written forms plus every registry form.
|
||||
DECODER_TOTAL = re.compile(
|
||||
r'pub const SEMANTIC_FORMS: \[\(&str, EncodingFamily\); '
|
||||
r'HANDWRITTEN_FORMS\.len\(\) \+ FORM_IDS\.len\(\)\] ='
|
||||
)
|
||||
DECODER_ENTRY = re.compile(r'\("([A-Z0-9_]+)", EncodingFamily::([A-Za-z0-9]+)\),')
|
||||
STATUS_ALIASES = {
|
||||
"s_waitcnt vmcnt(0)": ("SOPP", "S_WAITCNT"),
|
||||
"s_waitcnt_vscnt null, 0": ("SOPK", "S_WAITCNT_VSCNT"),
|
||||
}
|
||||
COLUMNS = (
|
||||
"Identified", "Encoding-validated", "Declared", "Decoder-supported",
|
||||
"IR", "MSL", "Reference-verified", "Metal-verified", "Unsupported operand variants",
|
||||
)
|
||||
|
||||
|
||||
def load_snapshot(root):
|
||||
# Reuse the metadata generator's base-form rules, including literal-only
|
||||
# forms and the relative moves whose base condition is not "default".
|
||||
metadata = runpy.run_path(str(root / "crates/isa/generate_rdna2_meta.py"))
|
||||
encodings = metadata["BASE_ENCODINGS"] | metadata["EXTENSIONS"]
|
||||
snapshot = (root / SNAPSHOT).read_text(encoding="utf-8")
|
||||
variants = []
|
||||
for number, line in enumerate(snapshot.splitlines(), 1):
|
||||
location = f"{SNAPSHOT}:{number}"
|
||||
try:
|
||||
row = json.loads(line)
|
||||
except ValueError as error:
|
||||
raise ValueError(f"{location}: {error}") from error
|
||||
if not isinstance(row, dict):
|
||||
raise ValueError(f"{location}: expected an object")
|
||||
kind = row.get("kind")
|
||||
if kind == "variant":
|
||||
if (
|
||||
not isinstance(row.get("encoding"), str) or row["encoding"] not in encodings
|
||||
or any(not isinstance(row.get(key), str) or not row[key]
|
||||
for key in ("instruction", "condition"))
|
||||
or type(row.get("opcode")) is not int
|
||||
):
|
||||
raise ValueError(f"{location}: invalid variant {row!r}")
|
||||
variants.append((location, row))
|
||||
elif kind not in ("source", "encoding", "operand_type", "data_format"):
|
||||
raise ValueError(f"{location}: unknown row kind {kind!r}")
|
||||
try:
|
||||
_, _, forms = metadata["forms_from_snapshot"](snapshot)
|
||||
except (SystemExit, ValueError, KeyError, IndexError, TypeError) as error:
|
||||
raise ValueError(f"{SNAPSHOT}: {error}") from error
|
||||
identified = {(form["encoding"].upper(), form["name"]): form["opcode"] for form in forms}
|
||||
if not identified or len(identified) != len(forms):
|
||||
raise ValueError(f"{SNAPSHOT}: expected unique, nonempty base forms")
|
||||
for location, row in variants:
|
||||
encoding = row["encoding"]
|
||||
base, _ = metadata["EXTENSIONS"].get(encoding, (encoding, None))
|
||||
key = (metadata["BASE_ENCODINGS"][base].upper(), row["instruction"])
|
||||
if key not in identified:
|
||||
raise ValueError(f"{location}: cannot map {encoding} variant to base form {key}")
|
||||
return identified
|
||||
|
||||
|
||||
def parse_decoder(source):
|
||||
lines = source.splitlines()
|
||||
if sum(bool(DECODER_TOTAL.fullmatch(line.strip())) for line in lines) != 1:
|
||||
raise ValueError(f"{DECODER}: expected SEMANTIC_FORMS = hand-written + registry forms")
|
||||
starts = [i for i, line in enumerate(lines)
|
||||
if re.match(r"\s*const HANDWRITTEN_FORMS\b", line)]
|
||||
if len(starts) != 1:
|
||||
raise ValueError(f"{DECODER}: expected one HANDWRITTEN_FORMS declaration")
|
||||
start = starts[0]
|
||||
header = DECODER_HEADER.fullmatch(lines[start].strip())
|
||||
if not header:
|
||||
raise ValueError(f"{DECODER}:{start + 1}: unrecognized SEMANTIC_FORMS declaration")
|
||||
|
||||
forms = set()
|
||||
for number, line in enumerate(lines[start + 1:], start + 2):
|
||||
line = line.partition("//")[0].strip()
|
||||
if line == "];":
|
||||
if len(forms) != int(header[1]):
|
||||
raise ValueError(f"{DECODER}:{number}: SEMANTIC_FORMS length mismatch")
|
||||
return forms
|
||||
if not line:
|
||||
continue
|
||||
entry = DECODER_ENTRY.fullmatch(line)
|
||||
if not entry:
|
||||
raise ValueError(f"{DECODER}:{number}: unrecognized SEMANTIC_FORMS entry {line!r}")
|
||||
key = (entry[2].upper(), entry[1])
|
||||
if key in forms:
|
||||
raise ValueError(f"{DECODER}:{number}: duplicate form {key}")
|
||||
forms.add(key)
|
||||
raise ValueError(f"{DECODER}: unterminated SEMANTIC_FORMS")
|
||||
|
||||
|
||||
GENERATED_HEADER = re.compile(r"pub const FORM_IDS: \[\(&str, EncodingFamily\); (\d+)\] = \[")
|
||||
|
||||
|
||||
def parse_generated(source):
|
||||
"""Registry forms compiled into the decoder, read from the generated FORM_IDS table."""
|
||||
lines = source.splitlines()
|
||||
starts = [i for i, line in enumerate(lines) if GENERATED_HEADER.fullmatch(line.strip())]
|
||||
if len(starts) != 1:
|
||||
raise ValueError(f"{GENERATED}: expected one FORM_IDS declaration")
|
||||
forms = set()
|
||||
rows = 0
|
||||
for number, line in enumerate(lines[starts[0] + 1:], starts[0] + 2):
|
||||
line = line.strip()
|
||||
if line == "];":
|
||||
if rows != len(forms):
|
||||
raise ValueError(f"{GENERATED}:{number}: duplicate FORM_IDS entry")
|
||||
if len(forms) != int(GENERATED_HEADER.fullmatch(lines[starts[0]].strip())[1]):
|
||||
raise ValueError(f"{GENERATED}:{number}: FORM_IDS length mismatch")
|
||||
return forms
|
||||
entry = DECODER_ENTRY.fullmatch(line)
|
||||
if not entry:
|
||||
raise ValueError(f"{GENERATED}:{number}: unrecognized FORM_IDS entry {line!r}")
|
||||
forms.add((entry[2].upper(), entry[1]))
|
||||
rows += 1
|
||||
raise ValueError(f"{GENERATED}: unterminated FORM_IDS")
|
||||
|
||||
|
||||
def read_declarations(registry, identified):
|
||||
if type(registry.get("schema")) is not int or registry["schema"] != 1:
|
||||
raise ValueError(f"{REGISTRY}: expected schema 1")
|
||||
families = {family for family, _ in identified}
|
||||
rules = {}
|
||||
for name, rule in registry["operand_rules"].items():
|
||||
location = f"{REGISTRY}: operand_rules.{name}"
|
||||
family = rule["family"]
|
||||
unsupported = rule["unsupported"]
|
||||
if family not in families:
|
||||
raise ValueError(f"{location}: unknown family {family!r}")
|
||||
if not isinstance(unsupported, list) or any(
|
||||
not isinstance(variant, str) or not re.fullmatch(r"[a-zA-Z0-9_]+", variant)
|
||||
for variant in unsupported
|
||||
):
|
||||
raise ValueError(f"{location}: invalid unsupported list")
|
||||
rules[name] = (family, set(unsupported))
|
||||
|
||||
declared = set()
|
||||
for form in registry["form"]:
|
||||
key = (form["family"], form["name"])
|
||||
if key not in identified:
|
||||
raise ValueError(f"{REGISTRY}: unknown form {key}")
|
||||
if type(form["opcode"]) is not int or form["opcode"] != identified[key]:
|
||||
raise ValueError(f"{REGISTRY}: opcode mismatch for {key}")
|
||||
if key in declared:
|
||||
raise ValueError(f"{REGISTRY}: duplicate form {key}")
|
||||
rule = form["operands"]
|
||||
if rule not in rules or rules[rule][0] != key[0]:
|
||||
raise ValueError(f"{REGISTRY}: invalid operand rule {rule!r} for {key}")
|
||||
declared.add(key)
|
||||
return declared, rules
|
||||
|
||||
|
||||
def status_form(row, identified):
|
||||
name = row["form"]
|
||||
if not isinstance(name, str) or not isinstance(row["encoding"], str):
|
||||
raise ValueError(f"{STATUS}: invalid form or encoding in {row!r}")
|
||||
families = {family for family, _ in identified}
|
||||
family_hint = row["encoding"].split(",", 1)[0].strip().upper()
|
||||
if name in STATUS_ALIASES:
|
||||
candidates = [STATUS_ALIASES[name]]
|
||||
else:
|
||||
mnemonic = name.upper()
|
||||
eligible = families
|
||||
if mnemonic.endswith("_E32"):
|
||||
mnemonic = mnemonic.removesuffix("_E32")
|
||||
eligible = families & {"VOP1", "VOP2", "VOPC"}
|
||||
elif mnemonic.endswith("_E64"):
|
||||
mnemonic = mnemonic.removesuffix("_E64")
|
||||
eligible = families & {"VOP3", "VOP3SDST"}
|
||||
candidates = sorted((family, mnemonic) for family in eligible
|
||||
if (family, mnemonic) in identified)
|
||||
if family_hint in families:
|
||||
candidates = [key for key in candidates if key[0] == family_hint]
|
||||
if len(candidates) != 1 or candidates[0] not in identified:
|
||||
raise ValueError(f"{STATUS}: cannot uniquely map {name!r} ({candidates})")
|
||||
return candidates[0]
|
||||
|
||||
|
||||
def collect_coverage(identified, registry, decoder, status):
|
||||
declared, rules = read_declarations(registry, identified)
|
||||
unknown = decoder.difference(identified)
|
||||
if unknown:
|
||||
raise ValueError(f"{DECODER}: unknown forms {sorted(unknown)}")
|
||||
|
||||
encoded, lowered, reference, metal = set(), set(), set(), set()
|
||||
seen = set()
|
||||
for row in status["instruction"]:
|
||||
key = status_form(row, identified)
|
||||
if key in seen:
|
||||
raise ValueError(f"{STATUS}: duplicate evidence for {key}")
|
||||
seen.add(key)
|
||||
for field in ("llvm", "lowering", "reference", "cpu", "gpu"):
|
||||
if field in row and not isinstance(row[field], str):
|
||||
raise ValueError(f"{STATUS}: {key} has invalid {field} evidence")
|
||||
if row.get("llvm") == "three-way passed":
|
||||
encoded.add(key)
|
||||
lowering = row.get("lowering", "").strip().lower()
|
||||
# This status schema uses one field for the IR-to-MSL path. A
|
||||
# compile-time resolution also implements that path for the form.
|
||||
if (
|
||||
lowering.startswith(("msl ", "resolved ", "verified ", "constant or ", "per-thread "))
|
||||
and not re.search(r"\b(?:stub|placeholder|planned|unsupported|pending|todo|unimplemented|not implemented|not yet)\b", lowering)
|
||||
):
|
||||
lowered.add(key)
|
||||
elif lowering:
|
||||
raise ValueError(f"{STATUS}: {key} has unrecognized lowering {row['lowering']!r}")
|
||||
# Verified evidence also requires the status row to say the form decodes.
|
||||
decodes = row.get("decoded") is True
|
||||
if decodes and row.get("reference") == "implemented" and row.get("cpu") == "fixture verified":
|
||||
reference.add(key)
|
||||
if decodes and row.get("gpu") in {"fixture verified", "fixture verified on Apple M5"}:
|
||||
metal.add(key)
|
||||
|
||||
counts = [Counter(family for family, _ in forms) for forms in (
|
||||
identified, encoded, declared, decoder, lowered, lowered, reference, metal,
|
||||
)]
|
||||
unsupported = defaultdict(set)
|
||||
for family, variants in rules.values():
|
||||
unsupported[family].update(variants)
|
||||
return {
|
||||
family: (*[count[family] for count in counts], len(unsupported[family]))
|
||||
for family in sorted(counts[0])
|
||||
}, rules
|
||||
|
||||
|
||||
def render_report(counts, rules):
|
||||
lines = [
|
||||
"# gfx1030 semantic coverage",
|
||||
"",
|
||||
"<!-- Generated by scripts/audit/semantic_coverage.py. -->",
|
||||
"",
|
||||
"Identified forms come from the AMD RDNA 2 instruction snapshot. Declared forms",
|
||||
"come from the semantic registry. Decoder support is the decoder's hand-written",
|
||||
"list plus the registry forms compiled into crates/isa/src/semantics_gen.rs.",
|
||||
"",
|
||||
"The status inventory records LLVM three-way encoding checks, intermediate",
|
||||
"representation (IR) and Metal Shading Language (MSL) lowering, and fixture",
|
||||
"verification. IR and MSL share the inventory's lowering field. Reference",
|
||||
"verification requires an implemented reference and verified CPU fixture.",
|
||||
"Metal verification requires a verified GPU fixture. Both also require a decoding row. Local readbacks pending",
|
||||
"acceptance remain outside the verified count. All results concern synthetic fixtures.",
|
||||
"",
|
||||
"| Family | " + " | ".join(COLUMNS) + " |",
|
||||
"| --- |" + " ---: |" * len(COLUMNS),
|
||||
]
|
||||
for family, values in counts.items():
|
||||
lines.append(f"| {family} | " + " | ".join(map(str, values)) + " |")
|
||||
lines.append("| **Total** | " + " | ".join(map(str, map(sum, zip(*counts.values())))) + " |")
|
||||
lines.extend([
|
||||
"",
|
||||
"## Unsupported operand variants",
|
||||
"",
|
||||
"The table counts distinct variant names per family across registry operand rules.",
|
||||
"",
|
||||
"| Family | Operand rule | Unsupported variants |",
|
||||
"| --- | --- | --- |",
|
||||
])
|
||||
for family, name, variants in sorted((family, name, variants)
|
||||
for name, (family, variants) in rules.items()):
|
||||
names = ", ".join(f"`{variant}`" for variant in sorted(variants))
|
||||
lines.append(f"| {family} | `{name}` | {names or 'None listed'} |")
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--check", action="store_true", help="compare without writing")
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
identified = load_snapshot(ROOT)
|
||||
registry = tomllib.loads((ROOT / REGISTRY).read_text(encoding="utf-8"))
|
||||
decoder = parse_decoder((ROOT / DECODER).read_text(encoding="utf-8")) | parse_generated(
|
||||
(ROOT / GENERATED).read_text(encoding="utf-8"))
|
||||
status = tomllib.loads((ROOT / STATUS).read_text(encoding="utf-8"))
|
||||
report = render_report(*collect_coverage(identified, registry, decoder, status)).encode()
|
||||
path = ROOT / REPORT
|
||||
if not args.check:
|
||||
path.write_bytes(report)
|
||||
print(f"Wrote {REPORT}")
|
||||
return 0
|
||||
committed = path.read_bytes() if path.exists() else b""
|
||||
if committed == report:
|
||||
print(f"{REPORT} is up to date")
|
||||
return 0
|
||||
before = committed.decode("utf-8", errors="replace").splitlines(keepends=True)
|
||||
after = report.decode().splitlines(keepends=True)
|
||||
diff = list(difflib.unified_diff(before, after, fromfile=str(REPORT),
|
||||
tofile="regenerated", n=0))
|
||||
print(f"{REPORT} differs from the regenerated report", file=sys.stderr)
|
||||
for line in diff[:12]:
|
||||
print(line.rstrip("\n"), file=sys.stderr)
|
||||
if len(diff) > 12:
|
||||
print("…", file=sys.stderr)
|
||||
except (OSError, ValueError, KeyError, TypeError, AttributeError) as error:
|
||||
print(f"semantic_coverage: {error}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,117 @@
|
||||
import unittest
|
||||
|
||||
from audit import semantic_coverage as coverage
|
||||
|
||||
|
||||
class SemanticCoverageTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.identified = {("SOP2", "S_ADD_U32"): 0, ("SOP2", "S_SUB_U32"): 1}
|
||||
self.registry = {
|
||||
"schema": 1,
|
||||
"form": [{
|
||||
"family": "SOP2", "name": "S_ADD_U32", "opcode": 0,
|
||||
"operands": "scalar", "verify": ["metal", "reference", "llvm_encoding"],
|
||||
}],
|
||||
"operand_rules": {
|
||||
"scalar": {"family": "SOP2", "unsupported": ["two_literals"]},
|
||||
},
|
||||
}
|
||||
|
||||
def counts(self, *rows):
|
||||
counts, _ = coverage.collect_coverage(
|
||||
self.identified, self.registry, {("SOP2", "S_SUB_U32")},
|
||||
{"instruction": list(rows)},
|
||||
)
|
||||
return dict(zip(coverage.COLUMNS, counts["SOP2"]))
|
||||
|
||||
def test_declared_without_metal_evidence_is_not_metal_verified(self):
|
||||
counts = self.counts()
|
||||
self.assertEqual(counts["Declared"], 1)
|
||||
self.assertEqual(counts["Metal-verified"], 0)
|
||||
self.assertEqual(counts["Reference-verified"], 0)
|
||||
self.assertEqual(counts["Encoding-validated"], 0)
|
||||
|
||||
def test_status_evidence_counts_for_handwritten_form(self):
|
||||
counts = self.counts({
|
||||
"form": "s_sub_u32", "encoding": "SOP2, scalar operands",
|
||||
"llvm": "three-way passed", "lowering": "resolved scalar state and SCC",
|
||||
"reference": "implemented", "cpu": "fixture verified",
|
||||
"gpu": "fixture verified on Apple M5", "decoded": True,
|
||||
})
|
||||
self.assertEqual(counts, {
|
||||
"Identified": 2, "Encoding-validated": 1, "Declared": 1,
|
||||
"Decoder-supported": 1, "IR": 1, "MSL": 1, "Reference-verified": 1,
|
||||
"Metal-verified": 1, "Unsupported operand variants": 1,
|
||||
})
|
||||
|
||||
def test_pending_readback_does_not_count(self):
|
||||
counts = self.counts({
|
||||
"form": "s_add_u32", "encoding": "SOP2", "lowering": "resolved scalar state and SCC",
|
||||
"reference": "implemented", "cpu": "local known-answer test passed",
|
||||
"gpu": "local Apple M5 readback passed; acceptance pending",
|
||||
})
|
||||
self.assertEqual(counts["Metal-verified"], 0)
|
||||
self.assertEqual(counts["Reference-verified"], 0)
|
||||
self.assertEqual(counts["IR"], 1)
|
||||
|
||||
def test_verified_evidence_needs_a_decoding_row(self):
|
||||
counts = self.counts({
|
||||
"form": "s_sub_u32", "encoding": "SOP2", "reference": "implemented",
|
||||
"cpu": "fixture verified", "gpu": "fixture verified", "decoded": False,
|
||||
})
|
||||
self.assertEqual(counts["Reference-verified"], 0)
|
||||
self.assertEqual(counts["Metal-verified"], 0)
|
||||
|
||||
def test_declared_but_not_compiled_is_not_decoder_supported(self):
|
||||
# S_ADD_U32 is declared in the registry but absent from the compiled tables.
|
||||
self.assertEqual(self.counts()["Decoder-supported"], 1)
|
||||
|
||||
def test_generated_table_parser(self):
|
||||
source = (
|
||||
"pub const FORM_IDS: [(&str, EncodingFamily); 1] = [\n"
|
||||
' ("S_ADD_U32", EncodingFamily::Sop2),\n];'
|
||||
)
|
||||
self.assertEqual(coverage.parse_generated(source), {("SOP2", "S_ADD_U32")})
|
||||
with self.assertRaisesRegex(ValueError, "length mismatch"):
|
||||
coverage.parse_generated(source.replace("; 1]", "; 2]"))
|
||||
duplicated = source.replace("; 1]", "; 2]").replace(
|
||||
' ("S_ADD_U32", EncodingFamily::Sop2),\n',
|
||||
' ("S_ADD_U32", EncodingFamily::Sop2),\n' * 2,
|
||||
)
|
||||
with self.assertRaisesRegex(ValueError, "duplicate FORM_IDS entry"):
|
||||
coverage.parse_generated(duplicated)
|
||||
|
||||
def test_stub_or_unrecognized_lowering_fails(self):
|
||||
for lowering in ("stub", "MSL placeholder add", "MSL unimplemented", "something new"):
|
||||
with self.assertRaisesRegex(ValueError, "unrecognized lowering"):
|
||||
self.counts({"form": "s_add_u32", "encoding": "SOP2", "lowering": lowering})
|
||||
|
||||
def test_status_suffix_disambiguates_encoding(self):
|
||||
forms = {("VOP2", "V_AND_B32"): 1, ("VOP3", "V_AND_B32"): 2}
|
||||
self.assertEqual(coverage.status_form(
|
||||
{"form": "v_and_b32_e32", "encoding": "Two VGPR sources"}, forms,
|
||||
), ("VOP2", "V_AND_B32"))
|
||||
with self.assertRaisesRegex(ValueError, "cannot uniquely map"):
|
||||
coverage.status_form(
|
||||
{"form": "v_and_b32", "encoding": "Two VGPR sources"}, forms,
|
||||
)
|
||||
|
||||
def test_unknown_status_form_fails(self):
|
||||
with self.assertRaisesRegex(ValueError, "cannot uniquely map.*s_typo"):
|
||||
self.counts({"form": "s_typo", "encoding": "SOP2"})
|
||||
|
||||
def test_decoder_parser_rejects_unrecognized_entry(self):
|
||||
header = (
|
||||
"pub const SEMANTIC_FORMS: [(&str, EncodingFamily); "
|
||||
"HANDWRITTEN_FORMS.len() + FORM_IDS.len()] =\n"
|
||||
"const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 1] = ["
|
||||
)
|
||||
self.assertEqual(coverage.parse_decoder(
|
||||
f'{header}\n ("S_ADD_U32", EncodingFamily::Sop2),\n];',
|
||||
), {("SOP2", "S_ADD_U32")})
|
||||
with self.assertRaisesRegex(ValueError, "unrecognized SEMANTIC_FORMS entry"):
|
||||
coverage.parse_decoder(f"{header}\n unknown!(),\n];")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,492 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Unit tests for crates/isa/generate_semantics.py.
|
||||
|
||||
Each rejection rule is fed a small in-memory registry that breaks exactly that
|
||||
rule, checked against a tiny hand-written XML snapshot. The real registry and
|
||||
snapshot are only read, never edited. Run from the repository root:
|
||||
|
||||
python3 -m unittest discover -s tests/semantics_generator
|
||||
"""
|
||||
|
||||
import copy
|
||||
import importlib.util
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
SCRIPT = ROOT / "crates/isa/generate_semantics.py"
|
||||
|
||||
_spec = importlib.util.spec_from_file_location("generate_semantics", SCRIPT)
|
||||
gen = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(gen)
|
||||
|
||||
SHA = "0" * 64
|
||||
|
||||
# Minimal stand-in for crates/isa/data/rdna2.jsonl: the SOP2 encoding and the
|
||||
# default variants of the four forms the fixture declares (values copied from
|
||||
# the AMD XML snapshot).
|
||||
U32 = "FMT_NUM_U32"
|
||||
I32 = "FMT_NUM_I32"
|
||||
|
||||
|
||||
def _operands(data_format, scc_in=False):
|
||||
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],
|
||||
]
|
||||
if scc_in:
|
||||
rows.append(["", "FMT_NUM_B1", "OPR_SSRC_SPECIAL_SCC", 1, True, False, True, True])
|
||||
return rows
|
||||
|
||||
|
||||
def snapshot():
|
||||
sop2_base = 0x80000000
|
||||
encoding = {
|
||||
"name": "ENC_SOP2",
|
||||
"bits": 32,
|
||||
"fields": [
|
||||
["SSRC0", [[0, 8]]], ["SSRC1", [[8, 8]]], ["SDST", [[16, 7]]],
|
||||
["OP", [[23, 7]]], ["ENCODING", [[30, 2]]],
|
||||
],
|
||||
"identifier_mask": 0xFF800000,
|
||||
"identifiers": [sop2_base | (op << 23) for op in (0, 2, 4, 14)],
|
||||
}
|
||||
variants = {}
|
||||
for name, opcode, operands in (
|
||||
("S_ADD_U32", 0, _operands(U32)),
|
||||
("S_ADD_I32", 2, _operands(I32)),
|
||||
("S_ADDC_U32", 4, _operands(U32, scc_in=True)),
|
||||
("S_AND_B32", 14, _operands(U32)),
|
||||
):
|
||||
variants[(name, "ENC_SOP2")] = {
|
||||
"instruction": name, "encoding": "ENC_SOP2", "opcode": opcode, "operands": operands,
|
||||
}
|
||||
return {"source": {"sha256": SHA}, "encodings": {"ENC_SOP2": encoding}, "variants": variants}
|
||||
|
||||
|
||||
def _form(name, opcode, variant, operation, signedness, scc, carry_in="none"):
|
||||
return {
|
||||
"name": name, "family": "SOP2", "opcode": opcode, "variant": variant,
|
||||
"operation": operation, "signedness": signedness, "carry_in": carry_in,
|
||||
"width": 32, "scc": scc, "vcc": "unchanged", "exec": "unchanged", "wave": "any",
|
||||
"operands": "sop2_sgpr",
|
||||
"spec": [{"document": "guide", "section": "12.1", "page": 101}],
|
||||
"verify": ["reference", "independent"],
|
||||
}
|
||||
|
||||
|
||||
def registry():
|
||||
rule = copy.deepcopy(gen.OPERAND_RULES["sop2_sgpr"]["shape"])
|
||||
rule["unsupported"] = sorted(gen.UNSUPPORTED_COMBOS)
|
||||
return {
|
||||
"schema": 1,
|
||||
"architecture": "gfx1030",
|
||||
"source_sha256": SHA,
|
||||
"documents": copy.deepcopy(gen.PINNED_DOCUMENTS),
|
||||
"operand_rules": {"sop2_sgpr": 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"),
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def form(reg, name):
|
||||
return next(item for item in reg["form"] if item["name"] == name)
|
||||
|
||||
|
||||
class Validate(unittest.TestCase):
|
||||
def errors(self, reg, snap=None):
|
||||
return gen.validate(reg, snap if snap is not None else snapshot())
|
||||
|
||||
def rejects(self, reg, fragment, snap=None):
|
||||
errors = self.errors(reg, snap)
|
||||
self.assertTrue(
|
||||
any(fragment in error for error in errors),
|
||||
f"expected an error containing {fragment!r}, got {errors}",
|
||||
)
|
||||
|
||||
# ---- acceptance ----
|
||||
|
||||
def test_accepts_the_fixture(self):
|
||||
self.assertEqual(self.errors(registry()), [])
|
||||
|
||||
def test_accepts_the_real_registry(self):
|
||||
self.assertEqual(gen.validate(gen.load_registry(), gen.load_snapshot()), [])
|
||||
|
||||
# ---- top level ----
|
||||
|
||||
def test_rejects_wrong_schema(self):
|
||||
reg = registry()
|
||||
reg["schema"] = 2
|
||||
self.rejects(reg, "schema 2 is not 1")
|
||||
|
||||
def test_rejects_source_sha256_mismatch(self):
|
||||
reg = registry()
|
||||
reg["source_sha256"] = "f" * 64
|
||||
self.rejects(reg, "source_sha256 does not match")
|
||||
|
||||
def test_rejects_unknown_top_level_key(self):
|
||||
reg = registry()
|
||||
reg["notes"] = "x"
|
||||
self.rejects(reg, "unknown top-level keys ['notes']")
|
||||
|
||||
def test_rejects_empty_registry(self):
|
||||
reg = registry()
|
||||
reg["form"] = []
|
||||
self.rejects(reg, "declares no forms")
|
||||
|
||||
# ---- incomplete or unknown fields ----
|
||||
|
||||
def test_rejects_missing_required_field(self):
|
||||
reg = registry()
|
||||
del form(reg, "S_ADD_U32")["scc"]
|
||||
self.rejects(reg, "S_ADD_U32: incomplete, missing ['scc']")
|
||||
|
||||
def test_rejects_unknown_form_key(self):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")["expression"] = "a + b"
|
||||
self.rejects(reg, "S_ADD_U32: unknown keys ['expression']")
|
||||
|
||||
# ---- closed vocabularies ----
|
||||
|
||||
def test_rejects_unknown_operation(self):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")["operation"] = "mul"
|
||||
self.rejects(reg, "S_ADD_U32: unknown operation 'mul'")
|
||||
|
||||
def test_rejects_unknown_scc_effect(self):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")["scc"] = "overflow"
|
||||
self.rejects(reg, "S_ADD_U32: unknown scc 'overflow'")
|
||||
|
||||
def test_rejects_unknown_mask_effect(self):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")["vcc"] = "written"
|
||||
self.rejects(reg, "S_ADD_U32: unknown vcc 'written'")
|
||||
|
||||
def test_rejects_unsupported_width(self):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")["width"] = 64
|
||||
self.rejects(reg, "S_ADD_U32: width 64 is not supported")
|
||||
|
||||
def test_rejects_unknown_evidence(self):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")["verify"] = ["reference", "hardware"]
|
||||
self.rejects(reg, "S_ADD_U32: unknown verification requirement")
|
||||
|
||||
def test_rejects_empty_evidence(self):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")["verify"] = []
|
||||
self.rejects(reg, "S_ADD_U32: no verification requirement")
|
||||
|
||||
# ---- contradictions ----
|
||||
|
||||
def test_rejects_bitwise_operation_declared_signed(self):
|
||||
reg = registry()
|
||||
form(reg, "S_AND_B32")["signedness"] = "signed"
|
||||
self.rejects(reg, "S_AND_B32: signedness signed contradicts operation and")
|
||||
|
||||
def test_rejects_carry_in_on_logical_operation(self):
|
||||
reg = registry()
|
||||
form(reg, "S_AND_B32")["carry_in"] = "scc"
|
||||
self.rejects(reg, "S_AND_B32: carry_in scc contradicts and/bitwise")
|
||||
|
||||
def test_rejects_carry_out_on_signed_form(self):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_I32")["scc"] = "carry_out"
|
||||
self.rejects(reg, "S_ADD_I32: scc carry_out contradicts add/signed")
|
||||
|
||||
def test_rejects_scc_unchanged_on_a_form_that_writes_it(self):
|
||||
# Declared as preserving SCC while the primitive and the XML both write it.
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")["scc"] = "unchanged"
|
||||
self.rejects(reg, "S_ADD_U32: scc unchanged contradicts add/unsigned")
|
||||
self.rejects(reg, "S_ADD_U32: scc unchanged contradicts the XML SCC output")
|
||||
|
||||
def test_rejects_carry_in_the_xml_does_not_read(self):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")["carry_in"] = "scc"
|
||||
self.rejects(reg, "S_ADD_U32: carry_in scc contradicts the XML SCC input")
|
||||
|
||||
def test_rejects_signedness_contradicting_xml_format(self):
|
||||
reg = registry()
|
||||
f = form(reg, "S_ADD_I32")
|
||||
f["signedness"], f["scc"] = "unsigned", "carry_out"
|
||||
self.rejects(reg, "S_ADD_I32: signedness unsigned contradicts XML format FMT_NUM_I32")
|
||||
|
||||
# ---- identity against the XML snapshot ----
|
||||
|
||||
def test_rejects_opcode_mismatch(self):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")["opcode"] = 1
|
||||
self.rejects(reg, "S_ADD_U32: opcode 1 disagrees with the XML opcode 0")
|
||||
|
||||
def test_rejects_family_mismatch(self):
|
||||
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")
|
||||
|
||||
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")
|
||||
|
||||
# ---- duplicates ----
|
||||
|
||||
def test_rejects_duplicate_name(self):
|
||||
reg = registry()
|
||||
reg["form"].append(copy.deepcopy(form(reg, "S_ADD_U32")))
|
||||
self.rejects(reg, "S_ADD_U32: duplicate name S_ADD_U32")
|
||||
|
||||
def test_rejects_same_encoding_claimed_twice(self):
|
||||
reg = registry()
|
||||
twin = copy.deepcopy(form(reg, "S_ADD_U32"))
|
||||
twin["name"], twin["variant"] = "S_ADD_U32_COPY", "AddU32Copy"
|
||||
reg["form"].append(twin)
|
||||
self.rejects(reg, "S_ADD_U32_COPY: duplicate opcode ('SOP2', 0)")
|
||||
|
||||
def test_rejects_duplicate_variant(self):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_I32")["variant"] = "AddU32"
|
||||
self.rejects(reg, "S_ADD_I32: duplicate variant AddU32")
|
||||
|
||||
# ---- references ----
|
||||
|
||||
def test_rejects_missing_guide_reference(self):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")["spec"] = [{"document": "xml", "section": "1", "page": 0}]
|
||||
self.rejects(reg, "S_ADD_U32: missing a guide section and page reference")
|
||||
|
||||
def test_rejects_undeclared_document(self):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")["spec"].append({"document": "blog", "section": "1", "page": 1})
|
||||
self.rejects(reg, "S_ADD_U32: spec cites undeclared document 'blog'")
|
||||
|
||||
# ---- operand rules ----
|
||||
|
||||
def test_rejects_unknown_operand_rule_on_a_form(self):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")["operands"] = "vop2_vgpr"
|
||||
self.rejects(reg, "S_ADD_U32: unknown operand rule 'vop2_vgpr'")
|
||||
|
||||
def test_rejects_operand_rule_the_decoder_does_not_implement(self):
|
||||
reg = registry()
|
||||
reg["operand_rules"]["vop2_vgpr"] = {"family": "VOP2"}
|
||||
self.rejects(reg, "operand rule vop2_vgpr: not implemented by the decoder")
|
||||
|
||||
def test_rejects_operand_rule_shape_differing_from_the_decoder(self):
|
||||
reg = registry()
|
||||
reg["operand_rules"]["sop2_sgpr"]["max_literals"] = 2
|
||||
self.rejects(reg, "operand rule sop2_sgpr: declaration differs")
|
||||
|
||||
def test_rejects_an_incomplete_unsupported_list(self):
|
||||
reg = registry()
|
||||
reg["operand_rules"]["sop2_sgpr"]["unsupported"].remove("two_literals")
|
||||
self.rejects(
|
||||
reg, "operand rule sop2_sgpr: unsupported combos differ from those the decoder rejects"
|
||||
)
|
||||
|
||||
def test_rejects_a_citation_to_another_file(self):
|
||||
reg = registry()
|
||||
reg["documents"]["guide"]["file"] = "missing.pdf"
|
||||
self.rejects(reg, "document guide: differs from the pinned public document")
|
||||
|
||||
def test_rejects_an_unenforced_wave_restriction(self):
|
||||
reg = registry()
|
||||
reg["form"][0]["wave"] = "wave32"
|
||||
self.rejects(reg, "S_ADD_U32: wave wave32 has no decoder enforcement yet")
|
||||
|
||||
def test_rejects_a_reserved_variant(self):
|
||||
reg = registry()
|
||||
reg["form"][0]["variant"] = "Self"
|
||||
self.rejects(reg, "S_ADD_U32: variant 'Self' is reserved")
|
||||
|
||||
def test_rejects_a_boolean_schema(self):
|
||||
reg = registry()
|
||||
reg["schema"] = True
|
||||
self.rejects(reg, "schema True is not 1")
|
||||
|
||||
def test_rejects_unknown_unsupported_combo(self):
|
||||
reg = registry()
|
||||
reg["operand_rules"]["sop2_sgpr"]["unsupported"].append("dst_lds")
|
||||
self.rejects(reg, "operand rule sop2_sgpr: unknown unsupported combos ['dst_lds']")
|
||||
|
||||
def test_rejects_duplicate_unsupported_combo(self):
|
||||
reg = registry()
|
||||
reg["operand_rules"]["sop2_sgpr"]["unsupported"].append("dst_vcc")
|
||||
self.rejects(reg, "operand rule sop2_sgpr: duplicate unsupported combos")
|
||||
|
||||
# ---- remaining vocabulary, identity and reference rules ----
|
||||
|
||||
def test_rejects_wrong_architecture(self):
|
||||
reg = registry()
|
||||
reg["architecture"] = "gfx1100"
|
||||
self.rejects(reg, "architecture 'gfx1100' is not gfx1030")
|
||||
|
||||
def test_rejects_unknown_document(self):
|
||||
reg = registry()
|
||||
reg["documents"]["blog"] = {"title": "blog"}
|
||||
self.rejects(reg, "unknown document blog")
|
||||
|
||||
def test_rejects_unknown_signedness_carry_in_exec_and_wave(self):
|
||||
for key, value in (
|
||||
("signedness", "float"), ("carry_in", "vcc"), ("exec", "written"), ("wave", "wave64"),
|
||||
):
|
||||
with self.subTest(key=key):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")[key] = value
|
||||
self.rejects(reg, f"S_ADD_U32: unknown {key} {value!r}")
|
||||
|
||||
def test_rejects_invalid_name_variant_and_opcode(self):
|
||||
for key, value, fragment in (
|
||||
("name", "s_add_u32", "s_add_u32: invalid name"),
|
||||
("variant", "add_u32", "S_ADD_U32: invalid variant 'add_u32'"),
|
||||
("opcode", -1, "S_ADD_U32: invalid opcode"),
|
||||
("opcode", True, "S_ADD_U32: invalid opcode"),
|
||||
):
|
||||
with self.subTest(key=key, value=value):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")[key] = value
|
||||
self.rejects(reg, fragment)
|
||||
|
||||
def test_rejects_declaration_no_primitive_implements(self):
|
||||
reg = registry()
|
||||
form(reg, "S_AND_B32")["operation"] = "sub"
|
||||
self.rejects(reg, "S_AND_B32: no primitive implements sub/bitwise")
|
||||
|
||||
def test_rejects_duplicate_evidence(self):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")["verify"] = ["reference", "reference"]
|
||||
self.rejects(reg, "S_ADD_U32: duplicate verification requirement")
|
||||
|
||||
def test_rejects_malformed_spec_references(self):
|
||||
for ref, fragment in (
|
||||
({"document": "guide", "section": "12.1"}, "spec reference needs exactly document, section, page"),
|
||||
({"document": "guide", "section": "12.x", "page": 101}, "invalid spec section '12.x'"),
|
||||
({"document": "guide", "section": "12.1", "page": -1}, "invalid spec page"),
|
||||
):
|
||||
with self.subTest(ref=ref):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")["spec"].append(ref)
|
||||
self.rejects(reg, f"S_ADD_U32: {fragment}")
|
||||
|
||||
def test_rejects_guide_reference_without_a_page(self):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")["spec"] = [{"document": "guide", "section": "12.1", "page": 0}]
|
||||
self.rejects(reg, "S_ADD_U32: missing a guide section and page reference")
|
||||
|
||||
def test_rejects_opcode_outside_the_encoding_identifiers(self):
|
||||
snap = snapshot()
|
||||
snap["encodings"]["ENC_SOP2"]["identifiers"].remove(0x80000000 | (14 << 23))
|
||||
self.rejects(registry(), "S_AND_B32: opcode 14 is not an identifier of ENC_SOP2", snap)
|
||||
|
||||
def test_rejects_xml_operand_disagreements(self):
|
||||
cases = (
|
||||
("missing", lambda ops: ops.pop(2), "S_ADD_U32: XML has no operand SSRC1"),
|
||||
("width", lambda ops: ops[1].__setitem__(3, 64), "S_ADD_U32: SSRC0 is 64 bits in the XML"),
|
||||
("direction", lambda ops: ops[0].__setitem__(4, True),
|
||||
"S_ADD_U32: SDST direction disagrees with the XML"),
|
||||
("extra", lambda ops: ops.append(["SIMM16", U32, "OPR_SIMM16", 16, True, False, False, True]),
|
||||
"S_ADD_U32: XML operands ['SIMM16'] are not covered by rule sop2_sgpr"),
|
||||
)
|
||||
for label, change, fragment in cases:
|
||||
with self.subTest(case=label):
|
||||
snap = snapshot()
|
||||
change(snap["variants"][("S_ADD_U32", "ENC_SOP2")]["operands"])
|
||||
self.rejects(registry(), fragment, snap)
|
||||
|
||||
|
||||
def _reorder(value):
|
||||
"""Reverse the key order of every mapping, keeping list order."""
|
||||
if isinstance(value, dict):
|
||||
return {key: _reorder(value[key]) for key in reversed(list(value))}
|
||||
if isinstance(value, list):
|
||||
return [_reorder(item) for item in value]
|
||||
return value
|
||||
|
||||
|
||||
class Render(unittest.TestCase):
|
||||
def test_two_renders_are_identical(self):
|
||||
self.assertEqual(gen.render(registry(), snapshot()), gen.render(registry(), snapshot()))
|
||||
|
||||
def test_render_ignores_mapping_key_order(self):
|
||||
reg = registry()
|
||||
reordered = _reorder(reg)
|
||||
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):
|
||||
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)
|
||||
|
||||
def test_real_registry_renders_the_committed_file(self):
|
||||
text = gen.render(gen.load_registry(), gen.load_snapshot())
|
||||
self.assertEqual(text, gen.RUST.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
class CommandLine(unittest.TestCase):
|
||||
def run_cli(self, *arguments):
|
||||
return subprocess.run(
|
||||
[sys.executable, str(SCRIPT), *map(str, arguments)],
|
||||
capture_output=True, text=True, check=False,
|
||||
)
|
||||
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.dir = Path(self.tmp.name)
|
||||
|
||||
def test_check_passes_on_the_committed_file(self):
|
||||
result = self.run_cli("--check")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
|
||||
def test_check_passes_on_a_fresh_file_and_fails_on_a_stale_one(self):
|
||||
output = self.dir / "semantics_gen.rs"
|
||||
result = self.run_cli("generate", "--output", output)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
fresh = output.read_text(encoding="utf-8")
|
||||
self.assertEqual(self.run_cli("--check", "--output", output).returncode, 0)
|
||||
|
||||
output.write_text(fresh.replace("pub const GENERATED_SCHEMA: u32 = 1;", "pub const GENERATED_SCHEMA: u32 = 2;"))
|
||||
stale = self.run_cli("--check", "--output", output)
|
||||
self.assertEqual(stale.returncode, 1)
|
||||
self.assertIn("is stale", stale.stderr)
|
||||
# --check never writes.
|
||||
self.assertNotEqual(output.read_text(encoding="utf-8"), fresh)
|
||||
|
||||
def test_check_fails_when_the_generated_file_is_missing(self):
|
||||
self.assertEqual(self.run_cli("--check", "--output", self.dir / "absent.rs").returncode, 1)
|
||||
|
||||
def test_invalid_registry_fails_every_mode_without_writing(self):
|
||||
bad = self.dir / "rdna2.toml"
|
||||
text = gen.REGISTRY.read_text(encoding="utf-8")
|
||||
bad.write_text(text.replace("\nschema = 1\n", "\nschema = 2\n", 1), encoding="utf-8")
|
||||
output = self.dir / "out.rs"
|
||||
for mode in (("validate",), ("generate",), ("--check",)):
|
||||
result = self.run_cli(*mode, "--registry", bad, "--output", output)
|
||||
self.assertEqual(result.returncode, 1, mode)
|
||||
self.assertIn("error: schema 2 is not 1", result.stderr)
|
||||
self.assertFalse(output.exists())
|
||||
|
||||
def test_validate_reports_the_form_count(self):
|
||||
result = self.run_cli("validate")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(result.stdout.strip(), f"registry valid: {len(gen.load_registry()['form'])} forms")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user