mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-26 06:19:52 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
801c3e4878 |
No files matched your search
@@ -1,2 +0,0 @@
|
||||
# Every change needs a review from the maintainers team.
|
||||
* @MacosPorters/maintainers
|
||||
@@ -1,67 +0,0 @@
|
||||
name: Agent task
|
||||
description: A self-contained work item that a contributor or coding agent can claim with /claim.
|
||||
title: "task: "
|
||||
labels: [agent:ready]
|
||||
body:
|
||||
- type: dropdown
|
||||
id: area
|
||||
attributes:
|
||||
label: Area
|
||||
description: "cpu: translation, DBT, PE loading, guest startup, guest memory. gpu: RDNA2, shaders, Metal. runtime: Win32, CRT, C++ runtime, import generation, OS services, platform abstractions. shared: cross-subsystem interfaces. qa: verification, regression, security review."
|
||||
options:
|
||||
- cpu
|
||||
- gpu
|
||||
- runtime
|
||||
- shared
|
||||
- qa
|
||||
validations:
|
||||
required: true
|
||||
- type: dropdown
|
||||
id: priority
|
||||
attributes:
|
||||
label: Priority
|
||||
options:
|
||||
- critical
|
||||
- high
|
||||
- medium
|
||||
- low
|
||||
validations:
|
||||
required: true
|
||||
- type: input
|
||||
id: interface
|
||||
attributes:
|
||||
label: Interface
|
||||
description: For shared tasks, the interface name and the version or upstream commit it targets. Leave empty otherwise.
|
||||
- type: textarea
|
||||
id: goal
|
||||
attributes:
|
||||
label: Goal
|
||||
description: What must be true when the task is finished, in one or two sentences.
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: files
|
||||
attributes:
|
||||
label: Files
|
||||
description: Paths the task may edit, one per line: exact paths, directories ending in "/", or globs with * and **. Two claimed tasks never overlap.
|
||||
render: text
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: acceptance
|
||||
attributes:
|
||||
label: Acceptance command
|
||||
description: The exact command whose success proves the task is done. It must fail before the change. It is never run automatically; a maintainer must approve it with /approve-acceptance.
|
||||
render: sh
|
||||
validations:
|
||||
required: true
|
||||
- type: input
|
||||
id: depends
|
||||
attributes:
|
||||
label: Depends on
|
||||
description: Issue numbers that must be closed first, for example "#12, #15". Leave empty when none.
|
||||
- type: textarea
|
||||
id: context
|
||||
attributes:
|
||||
label: Context
|
||||
description: Specification sections, interface notes and known limits. Public sources only.
|
||||
@@ -1,8 +1,6 @@
|
||||
## Summary
|
||||
|
||||
<!-- What changes, and why? -->
|
||||
|
||||
Closes #<!-- the issue you claimed -->
|
||||
<!-- What changes, and why? Link an issue if relevant. -->
|
||||
|
||||
## Implementation and evidence
|
||||
|
||||
@@ -25,7 +23,6 @@ Closes #<!-- the issue you claimed -->
|
||||
|
||||
## Checklist
|
||||
|
||||
- [ ] I claimed the linked issue with a reply before starting, and nobody else held a live claim on it.
|
||||
- [ ] I reviewed the changes and disclosed material AI assistance below, if applicable.
|
||||
- [ ] The change preserves native ARM64 and Metal-first requirements.
|
||||
- [ ] I added relevant tests or explained why they are not applicable.
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
{
|
||||
"lease_hours": 168,
|
||||
"upstream": "MacosPorters/betterxen",
|
||||
"maintainers": [
|
||||
"Arths17"
|
||||
],
|
||||
"contributors": {}
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
name: Agent task claims
|
||||
|
||||
# Applies queue commands (/claim, /release, /reassign, /progress, /blocked,
|
||||
# /unblock, /approve-acceptance) and audits the queue hourly. Comment and issue
|
||||
# text is only parsed as data by scripts/agent_queue; it is never executed and
|
||||
# never interpolated into a shell. Not yet run on GitHub.
|
||||
#
|
||||
# Both jobs share one concurrency group, so decisions never race. GitHub keeps
|
||||
# at most one pending run per group and cancels the older pending run when a
|
||||
# newer one queues, so a run does not decide only its own comment: `replay`
|
||||
# decides every command of the last lease_hours that has no bot reply yet,
|
||||
# oldest first. The surviving run, or at the latest the hourly audit, answers
|
||||
# the commands of cancelled runs. Comments that do not start with `/` start no run.
|
||||
|
||||
on:
|
||||
issue_comment:
|
||||
types: [created]
|
||||
schedule:
|
||||
- cron: "17 * * * *"
|
||||
workflow_dispatch:
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
command:
|
||||
if: github.event_name == 'issue_comment' && !github.event.issue.pull_request && startsWith(github.event.comment.body, '/')
|
||||
runs-on: ubuntu-24.04-arm
|
||||
permissions:
|
||||
contents: read
|
||||
issues: write
|
||||
# One global group: claims are decided one at a time so file-overlap checks cannot race.
|
||||
concurrency:
|
||||
group: agent-queue
|
||||
cancel-in-progress: false
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Decide and apply
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
GH_REPO: ${{ github.repository }}
|
||||
PYTHONPATH: scripts
|
||||
run: |
|
||||
set -eu
|
||||
python3 -m agent_queue gather --repo "$GH_REPO" --no-prs --recent-commands > "$RUNNER_TEMP/state.json"
|
||||
python3 -m agent_queue replay --state "$RUNNER_TEMP/state.json" > "$RUNNER_TEMP/actions.json"
|
||||
python3 -m agent_queue apply --repo "$GH_REPO" --actions "$RUNNER_TEMP/actions.json"
|
||||
|
||||
audit:
|
||||
if: github.event_name != 'issue_comment'
|
||||
runs-on: ubuntu-24.04-arm
|
||||
permissions:
|
||||
contents: read
|
||||
issues: write
|
||||
pull-requests: read
|
||||
concurrency:
|
||||
group: agent-queue
|
||||
cancel-in-progress: false
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Decide commands whose runs were cancelled
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
GH_REPO: ${{ github.repository }}
|
||||
PYTHONPATH: scripts
|
||||
run: |
|
||||
set -eu
|
||||
python3 -m agent_queue gather --repo "$GH_REPO" --no-prs --recent-commands > "$RUNNER_TEMP/commands.json"
|
||||
python3 -m agent_queue replay --state "$RUNNER_TEMP/commands.json" > "$RUNNER_TEMP/replay.json"
|
||||
python3 -m agent_queue apply --repo "$GH_REPO" --actions "$RUNNER_TEMP/replay.json"
|
||||
- name: Lapse stale claims, flag invalid tasks, write summary
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
GH_REPO: ${{ github.repository }}
|
||||
PYTHONPATH: scripts
|
||||
run: |
|
||||
set -eu
|
||||
python3 -m agent_queue gather --repo "$GH_REPO" > "$RUNNER_TEMP/state.json"
|
||||
python3 -m agent_queue audit --state "$RUNNER_TEMP/state.json" > "$RUNNER_TEMP/actions.json"
|
||||
python3 -m agent_queue apply --repo "$GH_REPO" --actions "$RUNNER_TEMP/actions.json"
|
||||
{
|
||||
echo '## Agent queue summary'
|
||||
echo '```json'
|
||||
python3 -m agent_queue summary --state "$RUNNER_TEMP/state.json" --now "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
|
||||
echo '```'
|
||||
} >> "$GITHUB_STEP_SUMMARY"
|
||||
@@ -1,102 +0,0 @@
|
||||
name: Agent PR checks
|
||||
|
||||
# Checks pull requests against the task queue: linked claimed task, file
|
||||
# ownership, overlap with other open pull requests, and independent
|
||||
# verification. Runs on the base branch only: pull request code is never checked
|
||||
# out or executed; changed files come from the API. Not yet run on GitHub.
|
||||
#
|
||||
# Advisory: problems are reported as a warning and in the run summary, but the
|
||||
# check does not fail until a live smoke test and the migration of existing
|
||||
# issues are done (docs/coordination/agent-tasks.md). Only a comment starting
|
||||
# with /verified starts the verify job; ordinary comments start nothing.
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
types: [opened, synchronize, reopened, edited]
|
||||
issue_comment:
|
||||
types: [created]
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
check:
|
||||
if: github.event_name == 'pull_request_target'
|
||||
runs-on: ubuntu-24.04-arm
|
||||
permissions:
|
||||
contents: read
|
||||
issues: read
|
||||
pull-requests: read
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Check pull request
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
GH_REPO: ${{ github.repository }}
|
||||
PYTHONPATH: scripts
|
||||
run: |
|
||||
set -eu
|
||||
python3 -m agent_queue event --path "$GITHUB_EVENT_PATH" > "$RUNNER_TEMP/event.json"
|
||||
number=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["number"])' "$RUNNER_TEMP/event.json")
|
||||
python3 -m agent_queue gather --repo "$GH_REPO" --pr "$number" > "$RUNNER_TEMP/state.json"
|
||||
status=0
|
||||
python3 -m agent_queue pr-check --state "$RUNNER_TEMP/state.json" > "$RUNNER_TEMP/result.json" || status=$?
|
||||
{
|
||||
echo '## Agent PR check'
|
||||
echo '```json'
|
||||
cat "$RUNNER_TEMP/result.json"
|
||||
echo '```'
|
||||
} >> "$GITHUB_STEP_SUMMARY"
|
||||
# 1 means problems were found: advisory for now. Anything else is a failure of the check itself.
|
||||
if [ "$status" -eq 1 ]; then
|
||||
echo "::warning title=Agent PR check (advisory)::problems found; see the run summary"
|
||||
elif [ "$status" -ne 0 ]; then
|
||||
exit "$status"
|
||||
fi
|
||||
|
||||
verify:
|
||||
if: github.event_name == 'issue_comment' && github.event.issue.pull_request && startsWith(github.event.comment.body, '/verified')
|
||||
runs-on: ubuntu-24.04-arm
|
||||
# issues: write posts the reply.
|
||||
permissions:
|
||||
contents: read
|
||||
issues: write
|
||||
pull-requests: read
|
||||
concurrency:
|
||||
group: agent-verify-${{ github.event.issue.number }}
|
||||
cancel-in-progress: false
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Record verification and check again
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
GH_REPO: ${{ github.repository }}
|
||||
PYTHONPATH: scripts
|
||||
run: |
|
||||
set -eu
|
||||
python3 -m agent_queue event --path "$GITHUB_EVENT_PATH" > "$RUNNER_TEMP/event.json"
|
||||
number=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["number"])' "$RUNNER_TEMP/event.json")
|
||||
python3 -m agent_queue gather --repo "$GH_REPO" --pr "$number" > "$RUNNER_TEMP/state.json"
|
||||
python3 -m agent_queue decide --event "$RUNNER_TEMP/event.json" --state "$RUNNER_TEMP/state.json" > "$RUNNER_TEMP/actions.json"
|
||||
python3 -m agent_queue apply --repo "$GH_REPO" --actions "$RUNNER_TEMP/actions.json"
|
||||
# Check again only after an accepted verification of the current head: refused, stale,
|
||||
# malformed or unauthorized /verified comments get a reply and nothing else.
|
||||
if ! python3 -m agent_queue should-rerun --actions "$RUNNER_TEMP/actions.json"; then exit 0; fi
|
||||
# pull_request_target runs are recorded against the base branch, not the pull request
|
||||
# head, so the earlier check run cannot be found by head SHA. Evaluate the same check here.
|
||||
status=0
|
||||
python3 -m agent_queue pr-check --state "$RUNNER_TEMP/state.json" > "$RUNNER_TEMP/result.json" || status=$?
|
||||
{
|
||||
echo '## Agent PR check after verification'
|
||||
echo '```json'
|
||||
cat "$RUNNER_TEMP/result.json"
|
||||
echo '```'
|
||||
} >> "$GITHUB_STEP_SUMMARY"
|
||||
if [ "$status" -eq 1 ]; then
|
||||
echo "::warning title=Agent PR check (advisory)::problems found; see the run summary"
|
||||
elif [ "$status" -ne 0 ]; then
|
||||
exit "$status"
|
||||
fi
|
||||
@@ -35,42 +35,12 @@ jobs:
|
||||
run: |
|
||||
rustup toolchain install "$RUSTUP_TOOLCHAIN" --profile minimal --component rustfmt --component clippy
|
||||
rustc -vV
|
||||
- name: Install the Gate A2 C toolchain
|
||||
# crates/loader/tests/gate_a2.rs builds a hosted C program from source
|
||||
# with mingw-w64 and fails, never skips, when the compiler is missing.
|
||||
env:
|
||||
HOMEBREW_NO_AUTO_UPDATE: 1
|
||||
HOMEBREW_NO_INSTALL_CLEANUP: 1
|
||||
run: |
|
||||
brew install mingw-w64
|
||||
compiler="$(brew --prefix mingw-w64)/bin/x86_64-w64-mingw32-gcc"
|
||||
file -bL "$compiler" | grep arm64
|
||||
lipo -archs "$compiler" | grep arm64
|
||||
otool -L "$compiler"
|
||||
"$compiler" --version | head -1
|
||||
- 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
|
||||
# The generated status check must not depend on the host locale encoding.
|
||||
LC_ALL=C PYTHONCOERCECLOCALE=0 PYTHONUTF8=0 python3 scripts/audit/status.py --check
|
||||
for fixture in x2 x3 x4; do
|
||||
python3 "experiments/x1/fixtures/$fixture.py" --check || exit 1
|
||||
done
|
||||
- name: Test agent task queue
|
||||
run: |
|
||||
PYTHONPATH=scripts python3 -m unittest discover -s tests/agent_queue
|
||||
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 native audit JSON decoding
|
||||
run: python3 -m unittest discover -s tests/audit
|
||||
- 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
|
||||
@@ -82,11 +52,11 @@ jobs:
|
||||
cargo test --locked --workspace
|
||||
cargo test --locked --manifest-path experiments/x1/Cargo.toml
|
||||
scripts/audit/dependencies.sh
|
||||
LC_ALL=C PYTHONCOERCECLOCALE=0 PYTHONUTF8=0 scripts/audit/claims.sh
|
||||
scripts/audit/claims.sh
|
||||
- name: Inspect native CLI
|
||||
run: |
|
||||
cargo build --locked -p betterxen
|
||||
binary=target/aarch64-apple-darwin/debug/betterxen
|
||||
cargo build --locked -p xenora
|
||||
binary=target/aarch64-apple-darwin/debug/xenora
|
||||
file "$binary"
|
||||
test "$(lipo -archs "$binary")" = arm64
|
||||
otool -L "$binary"
|
||||
@@ -1,38 +0,0 @@
|
||||
name: PR template
|
||||
|
||||
# Fails when a pull request description does not follow
|
||||
# .github/PULL_REQUEST_TEMPLATE.md: every section present and filled in, a
|
||||
# linked issue ("Closes #N" or "No linked issue: <reason>"), and the
|
||||
# claimed-first and DCO checkboxes ticked. Runs again whenever the description
|
||||
# is edited; comments never start it. Runs on the base branch: pull request
|
||||
# code is never checked out or executed, and the description is read as data.
|
||||
#
|
||||
# To make it blocking, mark the "PR template / description" check as required
|
||||
# in the branch protection rule for main.
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
types: [opened, edited, reopened, synchronize]
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
description:
|
||||
runs-on: ubuntu-24.04-arm
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Check the description against the template
|
||||
run: |
|
||||
set -u
|
||||
status=0
|
||||
python3 scripts/pr_template_check.py --event "$GITHUB_EVENT_PATH" > "$RUNNER_TEMP/result.txt" || status=$?
|
||||
cat "$RUNNER_TEMP/result.txt"
|
||||
{ echo '## PR template'; cat "$RUNNER_TEMP/result.txt"; } >> "$GITHUB_STEP_SUMMARY"
|
||||
if [ "$status" -ne 0 ]; then
|
||||
echo "::error title=PR description does not follow the template::$(tail -n +2 "$RUNNER_TEMP/result.txt" | head -n -1 | tr '\n' ' ')"
|
||||
fi
|
||||
exit "$status"
|
||||
@@ -35,9 +35,3 @@
|
||||
|
||||
__pycache__/
|
||||
*.pyc
|
||||
/diagnostics/probe/
|
||||
/diagnostics/gta6-candidate-*/
|
||||
/diagnostics/gta6-check/
|
||||
|
||||
# Native application build output
|
||||
/app/.build/
|
||||
@@ -1,4 +1,4 @@
|
||||
# BetterXen engineering rules
|
||||
# Xenora engineering rules
|
||||
|
||||
### Native Apple Silicon
|
||||
|
||||
@@ -7,7 +7,7 @@ Never introduce Rosetta 2, x86-64 host executables, MoltenVK, Vulkan runtime dep
|
||||
- SPIR-V is permitted as a compiler intermediate representation. It does not justify a Vulkan runtime.
|
||||
- All host executables and native dependencies must support ARM64. Verify with file, lipo -archs and otool -L.
|
||||
- Never run Intel binaries through Rosetta, even temporarily. Never add a dependency that requires Rosetta to build or run. If a dependency cannot run natively, find an alternative or document the limitation.
|
||||
- The guest architecture being decoded may be x86-64, but BetterXen itself runs natively on ARM64.
|
||||
- The guest architecture being decoded may be x86-64, but Xenora itself runs natively on ARM64.
|
||||
- Support M1 through M5 and future generations through runtime capability detection. Do not assume all Apple GPUs share capabilities.
|
||||
- Use aarch64-apple-darwin as the Rust target.
|
||||
|
||||
@@ -20,7 +20,7 @@ Never introduce Rosetta 2, x86-64 host executables, MoltenVK, Vulkan runtime dep
|
||||
- Never replace GPU tests with mocks and then claim GPU support.
|
||||
- Unknown information is classified as unknown and becomes a documented research task.
|
||||
- Every hardware claim carries an evidence class (section 9). Never present a lower-class claim as if it were a higher-class one.
|
||||
- Never claim "verified on Xbox hardware". BetterXen has no Xbox hardware access. Agreement with a spec-derived reference is not agreement with Xbox hardware, and docs must say so.
|
||||
- Never claim "verified on Xbox hardware". Xenora has no Xbox hardware access. Agreement with a spec-derived reference is not agreement with Xbox hardware, and docs must say so.
|
||||
- Do not hide errors behind fallbacks. Do not translate unsupported instructions into silent no-ops. Do not weaken or delete tests to make them pass. Do not change mutation counting, tolerances or gate definitions to improve a score.
|
||||
|
||||
### Independence of verification
|
||||
@@ -32,9 +32,9 @@ Never introduce Rosetta 2, x86-64 host executables, MoltenVK, Vulkan runtime dep
|
||||
|
||||
- Use only publicly accessible documentation and authorized materials. Never obtain or use leaked SDKs, confidential Xbox documentation, restricted console tools, firmware, encryption keys, or proprietary game binaries and shader collections. Do not attempt to bypass documentation access restrictions.
|
||||
- Contributors who have seen leaked or confidential Xbox materials must not contribute. State this in CONTRIBUTING.md and require a DCO sign-off (Signed-off-by) on contributions.
|
||||
- Include a plain statement in docs/legal.md: BetterXen does not circumvent console security or DRM, does not load encrypted or protected content, and is a research project built from public documentation. Add a note that this is not legal advice and that contributors should know their local laws, including anti-circumvention provisions such as DMCA section 1201.
|
||||
- Include a plain statement in docs/legal.md: Xenora does not circumvent console security or DRM, does not load encrypted or protected content, and is a research project built from public documentation. Add a note that this is not legal advice and that contributors should know their local laws, including anti-circumvention provisions such as DMCA section 1201.
|
||||
- Before copying or adapting any upstream code: verify the exact license of that file (not just the repo), check GPL-3.0-or-later compatibility, preserve copyright notices, record source repository and exact commit, document modifications, include required attribution. Never remove upstream copyright notices. If licensing is uncertain, stop using that code until resolved.
|
||||
- Keep BetterXen's emulator implementation original. Never copy, port, translate or adapt emulator source from Leonida, KyTx, AnyPS5 or similar projects.
|
||||
- Keep Xenora's emulator implementation original. Never copy, port, translate or adapt emulator source from Leonida, KyTx, AnyPS5 or similar projects.
|
||||
- Validate the technical compatibility and safety of user-provided files. Do not ask for ownership receipts, accounts or acquisition provenance as part of file loading. Contributor provenance and licensing obligations still apply.
|
||||
- Never place restricted material in the repository or its Git history.
|
||||
- Do not push, publish, or change remote visibility without explicit user authorization. Prepare locally and report readiness.
|
||||
@@ -45,19 +45,6 @@ No AI slop (section 29).
|
||||
|
||||
Read docs/interfaces.md and docs/progress.md before implementation.
|
||||
|
||||
## Claiming work before you start
|
||||
|
||||
Several people and coding agents work on this repository at the same time. Claim an issue before you edit anything, and never take work someone else has claimed.
|
||||
|
||||
1. **Check.** Read every comment on the issue and look for open pull requests that link it. A claim is any comment in which someone says they are taking the issue, in any words (for example "I'll take this" or `/claim`). If a claim exists and is not stale (step 4), pick another issue.
|
||||
2. **Claim.** Reply on the issue in plain words, for example: "I'm taking this. Plan: …". No command, label or bot step is needed. The earliest claim wins. Claim one issue per comment.
|
||||
3. **Stay in scope.** If the issue lists files, edit only those, and ask on the issue before widening the list. Do not start work that edits the same files as another claimed issue.
|
||||
4. **Stale claims.** A claim is stale when the claimer has not opened a pull request for the issue within about one week (7 days) of the claim. Only then may someone else take it, by replying on the issue, for example: "Taking this over: @name's claim from <date> has no pull request after 7 days." A claim with an open pull request is never stale; ask the claimer or the maintainer instead.
|
||||
5. **Release.** If you stop working on an issue, say so on the issue so others can take it.
|
||||
6. **Link.** Put `Closes #<n>` in the pull request description.
|
||||
|
||||
A coding agent claims in the name of the person it works for and follows the same rules. It must read the comments before claiming, and must never claim over, remove or ignore another person's claim. The optional task-queue commands in `docs/coordination/agent-tasks.md` do not replace these rules: a plain-reply claim counts even though the bot does not track it.
|
||||
|
||||
## Changelog maintenance
|
||||
|
||||
- At the start of every engineering task, read `CHANGELOG.md` alongside the relevant project documentation. Review the existing `[Unreleased]` entries before implementation to avoid duplicating completed work.
|
||||
@@ -91,14 +78,10 @@ A coding agent claims in the name of the person it works for and follows the sam
|
||||
- Run source mutation on decoder/shader/ref: `scripts/mutation.sh` (R2 owns triage)
|
||||
- Check generated status tables: `python3 scripts/audit/status.py --check`.
|
||||
- Check claims and dependency direction: `scripts/audit/claims.sh` and `scripts/audit/dependencies.sh`
|
||||
- Fuzz one target at a time: `scripts/fuzz.sh <instruction_stream|fixture|reference|runtime_services>` (600 seconds by default). `runtime_services` drives the standard guest service registry.
|
||||
- Fuzz one CPU-only parser at a time: `scripts/fuzz.sh <instruction_stream|fixture|reference>` (600 seconds by default).
|
||||
|
||||
Keep generated and gate logs under ignored `artifacts/`. Use at most four Cargo build jobs across two simultaneous CPU-heavy jobs, with one GPU job and one fuzz or mutation campaign at a time.
|
||||
|
||||
Do not add AI attribution or Co-authored-by trailers to commits.
|
||||
Never commit or push without explicit permission.
|
||||
Preserve the configured Git author and committer identity.
|
||||
|
||||
## Ownership
|
||||
|
||||
Xbox and claims owns public console research. ISA owns the decoder and oracle fixtures. Compiler owns the parser, IR and MSL. Metal owns the native GPU backend. Testing owns the independent reference and fixture validation. Infrastructure owns shared Cargo configuration, policies and the CPU boundary. R1 independently audits claims and release evidence. R2 independently validates semantic expectations and mutation results.
|
||||
-342
@@ -9,343 +9,8 @@ exact revision and known limitations.
|
||||
Guest execution uses original, purpose-built test programs. Commercial Xbox game execution
|
||||
remains unsupported.
|
||||
|
||||
### Changed
|
||||
- Replaced the active phase plan and README X1–X25 roadmap with one native macOS workload sequence and added a pinned PortWatch ecosystem review linked to eight contributor follow-ups. The plan distinguishes existing synthetic execution from future Xbox compatibility; no new runtime behavior, execution result or independent acceptance is claimed.
|
||||
- TLS setup now copies templates from 64 KiB up to 1 MiB straight into the zeroed thread data block, after checking that every template byte is readable, instead of staging them in a second buffer (#111). The pointer array and data block layout, the TLS index write and the error for an unreadable template are unchanged, and nothing is mapped when the template cannot be read. On an Apple M2 Pro, median setup time for original synthetic templates over 31 interleaved samples fell by 21.7 % at 64 KiB, 19.0 % at 256 KiB and 14.2 % at 768 KiB. Smaller and larger templates keep the single staged read and showed no change beyond run-to-run variation.
|
||||
- Removed the contributor avatar section from the README.
|
||||
- Added `.github/CODEOWNERS` so pull requests request review from the `MacosPorters/maintainers` team. With the `main` branch rule that requires code-owner review, a maintainer must approve each change before it merges.
|
||||
- Repaired destination issue links in 20 migrated PR descriptions while retaining the imported text, attribution and contributor certifications. Template and review requirements remain in place.
|
||||
- Moved 163 unused migration PR refs from branches to verified archive tags, retaining the 22 open-PR branches. Historical refs no longer clutter the branch list or produce recent-push PR prompts.
|
||||
- Renamed the project branding and native app and primary CLI package/binary to BetterXen (`betterxen`), and updated active repository links to `MacosPorters/betterxen`. Legacy `xenora-*` library packages and synthetic guest ABI names remain for compatibility. Upstream licenses, notices and historical evidence are retained.
|
||||
- Guest `strlen`, `strnlen`, `wcslen` and `wcsnlen` scan memory in 256-unit blocks, falling back to single units at mapping boundaries so faults still report the first inaccessible unit. On Apple M2 Pro the 63-byte `strlen` workload went from 1,990 ns to 223 ns per call (median of 10 batches, on a machine that was not idle).
|
||||
- The native ARM64 DBT now runs the 32- and 64-bit register and immediate forms of ADC and SBB itself instead of falling back to the shared interpreter (#195). The guest CF is moved into the host carry before ADCS or SBCS, inverted for SBB because SBCS subtracts NOT C while SBB subtracts CF. Memory forms and 8- and 16-bit forms still use the shared semantics. `tests/x86_carry_chain.rs` runs 256-bit add and subtract chains of 64- and 32-bit limbs, in one block and split one block per limb, against widening `u128`/`i128` reference arithmetic in both engines, plus immediate 128-bit increments and decrements and the `sbb reg, reg` carry mask. Locally verified on Apple M5 only.
|
||||
- Removed the temporary region-list allocation from each instruction-byte fetch while preserving lookup order, execute-permission checks and error behavior (part of #104).
|
||||
- Release and bench builds now use fat link-time optimization with one codegen unit (#116). On a local Apple M5, `dbt_bench` medians over five alternating runs dropped by about 6 % for the interpreter (903 to 845 µs) and about 9 % for cold DBT (1.155 to 1.046 ms), while warm DBT (cache hits) became about 2 % slower (21.83-22.08 to 22.29-22.54 µs over four further runs). The `xenora` binary shrank from 2.73 to 2.11 MB. A clean release build of the workspace takes about 14 s instead of 6 s. Debug and test builds are unchanged.
|
||||
- The ARM64 assembler loads 64-bit constants with the fewest MOVZ or MOVN plus MOVK instructions (#92). It no longer emits MOVK for zero halfwords and starts from MOVN when more halfwords are 0xFFFF than zero, so small negative values take one instruction instead of four. On Apple M5 the DBT benchmark emits 245,168 instead of 290,184 native bytes for its 626 blocks (-15.5%) and the 1,048 integer fixture instructions 128,724 instead of 145,732 (-11.7%); benchmark run times did not change measurably. New tests check the sequences against LLVM encodings and execute 1,056 of them on the host through the JIT.
|
||||
- Resolve the tiled BC1 mip and array layer once per linearization and copy contiguous block runs within each tile row. Partial edge blocks are retained and padding slots are skipped. Closes #349.
|
||||
- Changed the default report folder of `xenora probe` and `xenora imports sync` to `diagnostics/probe`, which Git ignores (#364). Anyone relying on the earlier default has to pass `--report`.
|
||||
- Relocation reports now build their type histogram once per image, avoiding a tree lookup for every entry. Target checks and fixup order are unchanged; synthetic regressions and an opt-in relocation timing test cover the change (#109).
|
||||
- Moved the six supported gfx1030 SOPP compute control forms into the semantic registry, preserving instruction decoding and shader lowering. Part of #215.
|
||||
- Moved gfx1030 `s_mov_b32` (SOP1) into the semantic registry, preserving its existing decode domain and shader output. The move operand rule retains explicit VCC and EXEC half destinations. Part of #215.
|
||||
- Moved the six hand-written gfx1030 VOP2 logical and shift forms (`v_and_b32`, `v_or_b32`, `v_xor_b32`, `v_lshlrev_b32`, `v_lshrrev_b32`, `v_ashrrev_i32`, AMD guide section 12.7) into the semantic registry under a new VGPR-only operand rule `vop2_vgpr2`, with no behaviour change: a sweep of 132,608 VOP2, VOP1 and SOP1 words decodes to the same text, length and error before and after, the MSL goldens are unchanged, and the runtime-region allowlist admits exactly the same six forms. The per-lane `VectorBinary` gained `And`, `Or`, `Xor` and the three shifts (count masked to S0[4:0]); 6 hand-written instruction variants and their decoder and lowering arms are gone (17 hand-written forms remain). Part of #215.
|
||||
- Added non-blocking Metal compute submission through `submit_words` and `wait`, with completion-aware resource retirement and a sixteen-dispatch in-flight limit. Synchronous calls keep their existing behavior. The benchmark reports the host submission split and compares synchronous and pipelined batches.
|
||||
- Reuse up to 16 native Metal compute pipelines per context for repeated shader source and entry points. Pending dispatches retain their pipelines through completion, including after eviction. Dispatch profiles report zero library and pipeline setup time when a cached pipeline is reused. Closes #132.
|
||||
- Avoided resolver allocations for permitted guest data reads and writes contained in one mapping, preserving checked fallback for split spans and faults (#105).
|
||||
- Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits.
|
||||
|
||||
### Fixed
|
||||
- Restored the DBT benchmark report-test fixture after the cache-invalidation counter was added. Its existing percentile, JSON and comparison tests now run in ordinary workspace CI instead of requiring a separate benchmark test-harness command.
|
||||
- DBT cache hits now compare an executable-generation token instead of rereading every instruction byte. Address-space or executable-memory changes trigger byte and execute-permission revalidation before a translation can be reused; changed code is retranslated. Ordinary data writes retain the fast path. Tests cover cloned spaces, loader bypass writes, split writes, remapping and bounded cache exhaustion. Same-dispatch self-modification and discarded-code reclamation remain unsupported.
|
||||
- Gate A2 checks the cross-compiler driver before invoking it, then checks its helpers before fixture compilation. CI also verifies the driver architecture before requesting its version.
|
||||
- Non-canonical 64-bit guest data addresses now raise `#GP` instead of a memory fault in both the interpreter and native DBT, including accesses that cross the canonical-address boundary. The synthetic architectural test is enabled again.
|
||||
- An instruction longer than 15 bytes now stops both engines with a general-protection fault instead of an illegal-instruction exit (#384; Intel SDM Vol. 3A, 7.15). The decoder still stops before fetching a 16th byte, and the DBT translates the faulting instruction on its own so the instructions before it in a block complete first. The `defect_overlong_instruction` known answer from #155 is now verified, with three more cases.
|
||||
- Made the native semantic-review timeout in `scripts/test-gpu.sh` configurable with `XENORA_SEMANTIC_TIMEOUT` and raised its default from 120 to 300 seconds, so cold Apple Silicon runs do not fail while the expanded Metal known-answer suite is still progressing.
|
||||
- Added a Python 3 fallback for `timeout` in `scripts/test-gpu.sh`, so the native Metal suite runs on stock macOS without GNU coreutils while preserving bounded execution and the usual timeout exit status.
|
||||
|
||||
### Added
|
||||
- Recorded the migrated PR integration decisions, native verification and scope exclusions in the testing documentation.
|
||||
- Added `xenora-bench startup` (#178), which measures Metal startup in fresh processes and in repeated
|
||||
submissions within one process, phase by phase (launch, device and queue, translation, library, pipeline,
|
||||
submission, GPU, readback), with median, p90, p99 and maximum. Every sample must produce the fixture's
|
||||
expected output, or the run stops without writing results. `docs/testing/benchmarks.md` records one
|
||||
release run on an Apple M4: a fresh process took about 43 ms (median), 36 ms of it creating the Metal
|
||||
device and queue, while repeated runs in one process needed about 0.2 ms of host submission. Measurement
|
||||
only; nothing was optimized.
|
||||
- Added an opt-in, budgeted staged upload for RGBA8 textures (#144). `MetalRgba8Texture::upload_staged` fills a
|
||||
Private-storage texture through one reused Shared staging buffer that never exceeds a `StagingBudget`. It
|
||||
copies whole-row bands with a blit encoder and reuses the buffer only after the previous command buffer has
|
||||
completed with status Completed. `plan_staged_upload` rejects missing, duplicate or out-of-range mip levels,
|
||||
wrong mip sizes, short row pitches or byte buffers, and budgets smaller than one row, all before any Metal
|
||||
object is created. A blit `read_back` returns any mip as tight RGBA8 bytes. On one Apple M4 under Metal API
|
||||
validation, readback matched independently built patterns for every level of a padded 37×19, six-level
|
||||
texture under four budgets, and matched the existing direct `upload`. Staging is slower than the direct path
|
||||
(2048² with 12 mips, release build: 2.1 ms direct, 2.7 ms with a 4 MiB budget, 17.8 ms with 256 KiB), so
|
||||
`upload` and its callers are unchanged. Not yet independently accepted.
|
||||
- The gfx1030 identification benchmark fixture now runs as an ordinary integration test, so workspace tests check LLVM-derived names, families, lengths and byte boundaries without invoking a timing run.
|
||||
- Added a CPU benchmark for gfx1030 metadata identification (#173). It verifies instruction boundaries on a mixed-family stream assembled with LLVM and reports first-pass and repeated-pass throughput.
|
||||
- Added a Win64 ABI regression showing that a service may write the caller-allocated shadow space. Existing negative controls cover nonvolatile XMM-register corruption; the unchanged-home-slot test now describes its handler rather than implying an ABI preservation requirement.
|
||||
- Added a BetterXen development phase plan based on current source, pending PRs and existing acceptance records, linked from both contributor entry points. It separates baseline reconciliation, hosted C execution, guest threading, translated rendering, application integration and measured optimization; no new runtime or compatibility acceptance is claimed.
|
||||
- Added `tests/runtime_clock.rs`, which reads the performance counter, its frequency, both tick counts, the unbiased interrupt time and the system time from one injected clock and checks that they report the same elapsed time in their own units, after a host advance and after a guest `Sleep`, and that none of them decreases up to and past the end of the clock (#204). Expected values are worked out by hand from the documented units. Timed waits still return without consuming clock time.
|
||||
- Added opt-in shader IR constant folding (`CompileOptions::fold_constants` / `compile_with`) for pure vector unary and binary ops whose operands are already constants (#141). Floating-point ops still use the exact positive-normal rules; loads, stores, lane masks, merges and branches are never folded. Default `compile` keeps the historical IR. Covered by hand-computed known-answer compiler tests (shifts by 32/33, ashr, min_i32 vs min_u32, mul_hi_i32_i24, ffbh_i32, exact float fold, load-derived float non-fold, and verify rejection of inexact constant float add) with a fold-on versus fold-off check, plus an MSL template drift check over every foldable op.
|
||||
- Added opt-in shader IR common-subexpression elimination (`CompileOptions::eliminate_common_subexpressions` / `compile_with`) that reuses the first result of an equivalent pure vector unary or binary (#142). Equivalence is the same operation and the same operand values in the same order; constant operands match by bit pattern. Loads, stores, constant definitions, lane masks, merges, branches and other side-effecting or execution-mask-dependent ops are left in place. The pass runs after constant folding, so folded results stay constants and a later pure op on two equal folded constants can still be reused. Default `compile` keeps the historical IR. Covered by hand-derived known-answer compiler tests for reuse (and/xor, not, exact float add), for rejected loads, swapped subtracts, lane masks, lane merges and VCC selects, and for the four combinations with constant folding (1 + 2 = 3, and 1.0 + 2.0 = 3.0), and a check that the 13 golden fixtures, none of which repeats an expression, compile unchanged with the pass on. No speedup is claimed.
|
||||
- The loader now maps an image's PE headers at its image base (#333): the first `SizeOfHeaders` bytes of the file, read-only, in whole 4 KiB pages that are zero past `SizeOfHeaders`. Programs read their own headers this way; the mingw-w64 C runtime does so before `main`, and until now that read faulted. When startup relocates an image it writes the load base into the mapped `ImageBase` field after the relocations, so an entry aimed at that field cannot move it twice; this is Xenora's policy and has not been compared with Windows. A load is refused with the new `PeError::InvalidHeaderSize` when `SizeOfHeaders` is zero, ends before the section table, runs past the file, or its pages would reach into a section, and when the bytes handed to the loader are not the PE32+ headers that were parsed. The page rule refuses images with sub-page section alignment whose first section starts inside the header page, which loaded before. The header pages count toward the 256 MiB mapping budget, which is checked before anything is mapped. `ParsedPe::parse` and the static probe are unchanged. `tests/pe_headers.rs` covers guest reads at the preferred and a relocated base, a relocation aimed at `ImageBase`, the write and execute faults and each refusal with original hand-built images; the image in `pe_mapping_limits.rs` now carries a valid `SizeOfHeaders`. Awaiting independent re-review.
|
||||
- Added 35 known-answer cases for MOV with an immediate operand, opcodes C6 /0 and C7 /0 (#194), to `cpu_known_answers.rs`: byte, word, dword and qword stores through base, SIB, R12, R13, RSP and RBP addressing with 8-bit and 32-bit displacements; the imm32 sign extension of the 64-bit form; the register forms, including AH and a REX-selected SIL; unmapped and read-only store faults at each width; and #UD for reg field 1. Expected values come from the Intel SDM and were worked out by hand. The interpreter and the DBT already agreed with all of them, so this is new coverage and fixes no defect. The 16-bit forms covered are those that already run, and #118 stays open. Not compared with x86 hardware; awaiting independent review.
|
||||
- Added Win64 service-call ABI tests in `crates/loader/tests/runtime_services.rs` for #201. A dispatch-level test and a DBT guest-call test verify stack alignment before CALL and at callee entry (`RSP % 16 == 8`), accessibility of the caller-allocated 32-byte shadow space, return-value/stack/RIP return state, and preservation of RBX/RBP/RDI/RSI/R12-R15 and XMM6-XMM15 across registered service calls. Expected values are derived from the Microsoft x64 calling convention, not from current implementation behavior.
|
||||
- `dbt_bench` can compare two of its JSON documents when `XENORA_DBT_BENCH_COMPARE=<baseline.json>,<candidate.json>` is set (#114). It prints each median with its change and whether the change exceeds the larger recorded IQR, and lists changed DBT counters. It refuses, with exit status 1 and the differing field named, to compare runs from different CPUs, operating systems or architectures, with unknown host fields, or with different workloads, sample counts, debug assertions or build labels. A new optional `XENORA_DBT_BENCH_BUILD_LABEL` records build settings the benchmark cannot see, such as LTO. No benchmark runs in this mode.
|
||||
- LAHF and SAHF run in both engines, and guest CPUID reports them in leaf `8000_0001h`, ECX bit 0 (#387; Intel SDM Vol. 2A LAHF, Vol. 2B SAHF). The DBT runs them through the shared semantics. The four known answers from #155 that both engines refused are now verified, with twelve more cases, and the independent reference in `tests/x86_integer.rs` covers both instructions.
|
||||
- LOOP, LOOPE, LOOPNE and JRCXZ run in both engines (#396; Intel SDM Vol. 2A, LOOP/LOOPcc and Jcc). The count is RCX; the address-size prefix stays rejected, so JECXZ and the ECX-counted forms are still refused. The DBT runs them through the shared semantics and ends its block at each. The three known answers from #155 that both engines refused are now verified, with eleven more cases, and `tests/cpu_loop.rs` checks a loop that spans translated blocks against a step-by-step model for every count, ZF match point and step budget.
|
||||
- Added checked, per-mip copy footprints for synthetic block-compressed texture arrays. Contributors can pack tight block rows or repack entire chains with independent row and placement alignment, and pass selected BC1–BC5 levels to the existing Metal readers (#391).
|
||||
- `dbt_bench` can also write its results as one JSON document when `XENORA_DBT_BENCH_JSON=<path>` is set (#112). The document records the host CPU, OS and architecture, the git revision and whether the tree had local changes, debug assertions, the workload and sample counts, the median, minimum, maximum, p95, p99, IQR and MIPS for the interpreter and for cold and warm DBT, and the cold DBT counters. Anything the benchmark cannot determine is `null`. The text output and the timed work are unchanged.
|
||||
- Added synthetic guest handle-lifetime regression tests (#205) for capacity reuse, stale handles, duplicate rights and lifetime, wrong object types, thread pseudo handles and failed-output nonmutation. Runtime behavior is unchanged; independent acceptance is pending.
|
||||
- Added a documented independent acceptance rule for promoting AMD RDNA2 desktop GPU (gfx1030) forms from local CPU and Metal results to `fixture verified`, including clean-commit evidence, reviewer independence, raw-log location, review-log summary, failure handling and status regeneration (#302).
|
||||
- Added the VOP3A (`_e64`) encodings of eleven gfx1030 VOP2 integer forms (`v_mul_{i32_i24,hi_i32_i24,u32_u24,hi_u32_u24}`, `v_{min,max}_{i32,u32}`, `v_xnor_b32`, `v_sub_nc_u32`, `v_subrev_nc_u32`) and of the sixteen Wave32 integer compares (explicit SGPR mask destination, `s_cbranch_vccz` through `vcc_lo`, a translation error for reads of runtime-only SGPR results) as semantic-registry encoding variants, with VGPR sources only. New fixtures `vop3-integer` and `vop3-compare` with IR and MSL goldens, and an independent guide-derived oracle (`tests/validation/tests/vop3_{integer,compare}.rs`) that agrees on both reference interpreters and on native Metal. Part of #215.
|
||||
- Added `scripts/cpu-tests.sh`, which lists the default-feature workspace test targets and runs
|
||||
deterministic shards of them (`--shard K/N`), with `--check N` showing every target lands in
|
||||
exactly one shard. It does not replace `cargo test --locked --workspace` or
|
||||
`scripts/test-gpu.sh`. `docs/testing/cpu-coverage.md` records local CPU gate timings on one
|
||||
Apple M4 host (about 40 s wall time; one loader target takes about 19 s) and shows that the 2- and
|
||||
3-shard unions match the full gate's 681 passed and 34 ignored tests (#159).
|
||||
- Added guest texture binding through D3D12-style descriptor tables (#303): shader-visible CBV_SRV_UAV and sampler heaps, `CreateShaderResourceView` for one-level RGBA8 and BC1 2D textures, a point/clamp `CreateSampler`, a root signature with one pixel-stage SRV table and one sampler table, and `SetDescriptorHeaps`/`SetGraphicsRootDescriptorTable` in `crates/loader/src/graphics.rs`, plus `NativeCompute::render_rgba8_sampled_bc1`. Verified locally on an Apple M5 Pro under Metal validation: a guest draw with the translated `image_sample_lz` pixel stage matches the software reference and hand-derived images on 16 of 16 pixels for two RGBA8 textures and 64 of 64 for an 8×8 BC1 texture. A wrong descriptor slot changes the image, off-centre and out-of-range coordinates point-sample with clamping, and a rejected binding, draw shape or resource state never reaches the backend. The software reference samples BC1 with the spec-exact decoder, while Apple's hardware rounds BC1's interpolated palette entries differently (171/84 against 170/85), so the BC1 fixtures use only endpoint colours. Not yet reachable from guest imports. Not yet independently accepted.
|
||||
- Added MOVNTI, the SSE2 non-temporal store of a 32- or 64-bit general register to memory (part of #125). Both engines used to stop on it with an illegal-instruction exit. It is an ordinary store, as the other non-temporal stores already are; the register form and the 66 prefix stay rejected, and a destination that cannot be written faults without changing state. The SDM-derived case `movdqa_movaps_aligned_store_and_load` in `cpu_known_answers.rs`, which ends in a MOVNTI, moved from refused to verified, and `tests/x86/integer.txt` gains four assembled instructions checked by the text-only reference in `x86_integer.rs`. MASKMOVDQU stays rejected and SSE2 stays unreported by CPUID. Not compared with x86 hardware; awaiting independent review.
|
||||
- Added MFENCE, LFENCE and SFENCE and documented the ordering of guest memory accesses (part of #199). Both engines used to stop on a fence with an illegal-instruction exit. Each engine runs one guest instruction at a time on one host thread and completes its loads and stores before the next, so accesses are already totally ordered and the fences change nothing; `docs/cpu/instruction-registry.md` states this and that it holds only while guest threads do not run on several host threads. Five single-thread cases in `cpu_known_answers.rs` and three assembled fixtures cover them, and the memory forms that share the opcode stay rejected. SSE2 is still not reported by CPUID because other SSE2 instructions are rejected; the refused SSE2 instruction that `cpu_features.rs` holds is now MASKMOVDQU. No multi-thread behaviour is established, and nothing was compared with x86 hardware; awaiting independent review.
|
||||
- Added the accumulator short form of XCHG, opcodes 91 to 97 and 90 with REX.B, at 16, 32 and 64 bits (part of #118). Assemblers choose this form whenever one operand is the accumulator, and both engines used to stop on it with an illegal-instruction exit. A 16-bit exchange keeps the upper 48 bits of both registers, a 32-bit one clears both upper halves, and `49 90` exchanges RAX with R8 while plain `90` stays NOP. Both engines run the shared semantics; nothing is lowered to ARM64. Three SDM-derived cases already in `cpu_known_answers.rs` moved from refused to verified, and `tests/x86/integer.txt` gains 20 assembled instructions checked by the text-only reference in `x86_integer.rs`. F3 before this form, 16-bit PUSH and POP and LODSW stay rejected. Not compared with x86 hardware; awaiting independent review.
|
||||
- Added SHLD and SHRD, the double-precision shifts (`0F A4`/`0F A5` and `0F AC`/`0F AD`), for 16-, 32- and 64-bit register and memory destinations with the count in an 8-bit immediate or in CL (part of #121). The count is masked to five bits (six for 64-bit operands); a masked count of zero changes nothing, the vacated bits are filled from the source register, CF receives the last bit shifted out of the destination, ZF, SF and PF follow the result, OF is set only for a count of one (a sign change) and AF is undefined. A 16-bit count above 16 leaves the result and flags undefined in the Intel SDM; Xenora keeps every flag and writes the bits of the 32-bit concatenation, and no test relies on that. The registry gained the operand encodings `rm_reg_imm` and `rm_reg_cl`. Both engines run the shared semantics; nothing is lowered to ARM64. Eight SDM-derived cases already in `cpu_known_answers.rs` moved from refused to verified, and `tests/x86/integer.txt` gains 72 assembled SHLD and SHRD instructions, checked by a bit-at-a-time reference in `x86_integer.rs` and by the faulting read-modify-write test. Not compared with x86 hardware; awaiting independent review.
|
||||
- Added RCL and RCR, the rotates through the carry flag, for 8-, 16-, 32- and 64-bit register and memory operands with a count of one, CL or an immediate (part of #121). The count is masked to five bits (six for 64-bit operands) and then reduced modulo 9 or 17 for 8- and 16-bit operands; a masked count of zero changes nothing, CF receives the last bit rotated out, and OF is set only for a count of one. Both engines run the shared semantics; nothing is lowered to ARM64. Fourteen SDM-derived cases already in `cpu_known_answers.rs` moved from refused to verified, and its shift sweep now runs both instructions at every width, count and carry against its bit-loop model. `tests/x86/integer.txt` gains 80 assembled RCL and RCR instructions, checked by the single-step reference in `x86_integer.rs`. SHLD and SHRD stay rejected. Not compared with x86 hardware; awaiting independent review.
|
||||
- Added four Wave32 gfx1030 VOP2 select and carry forms through the semantic registry. Conditional select, add with carry and both subtract orders with borrow use a per-lane VCC bit and have a guide-derived oracle that passes on both CPU interpreters and on native Metal (local Apple M5, API and shader validation); independent acceptance is pending. Part of #215.
|
||||
- Added decoding and Metal shader translation for twelve Wave32 VOPC 16-bit integer compares (#215). The signed and unsigned forms compare the low 16 bits of each source and write the Wave32 VCC mask. CPU verification covers 1,572 compiler acceptance cases and 408 rejections from the guide-derived oracle, which also passes on native Metal (1,572 cases in 1,420 programs on a local Apple M5 under API and shader validation); acceptance is pending.
|
||||
- Added MOVS and STOS for 8- to 64-bit elements, with and without REP, and the direction flag with CLD and STD (#129). A REP form runs one element per step and stays on the instruction until RCX is zero, so every element counts against the step budget, a repeat can stop part-way and resume, a zero count touches nothing, and a fault keeps the elements already done with RSI, RDI and RCX at the one that faulted. An FS or GS override applies to the MOVS source only. Both engines run these on the shared semantics with no bulk-copy path, so large copies are slow. LODS, CMPS, SCAS, REPE, REPNE and the address-size override stay rejected. Fourteen SDM-derived cases already in `cpu_known_answers.rs` moved from refused to verified, and `tests/cpu_rep.rs` adds a byte-array model over every form, direction and count; not compared with x86 hardware and awaiting independent review.
|
||||
- Added a deterministic guest thread scheduler (first part of #323): independent CPU contexts, guarded stacks and TEBs on one host thread, with bounded turns, `CreateThread`, `ExitThread`, `TerminateThread`, `GetExitCodeThread`, `SuspendThread`, `ResumeThread` and `SwitchToThread`. With a scheduler attached, `WaitForSingleObject` and `WaitForMultipleObjects` block only the calling guest thread, with timeouts, on threads, events, semaphores and mutexes; abandoned mutexes, deadlocks and per-thread faults are reported. Guest threads never run concurrently. Critical sections, SRW locks, condition variables and `Sleep` do not block per thread yet. See `docs/runtime/threads.md`.
|
||||
- Added decoding and Metal shader translation for the sixteen Wave32 VOPC 64-bit integer compares (#215). They read VGPR pairs, known even-aligned SGPR pairs or sign-extended inline integers and write the Wave32 VCC mask. The guide-derived oracle passes on native Metal (4,640 cases in 3,818 programs on a local Apple M5 under API and shader validation); acceptance is pending.
|
||||
- Added XADD and CMPXCHG for 8- to 64-bit register and memory destinations, and the LOCK prefix on their memory forms (#198). LOCK anywhere else, CMPXCHG8B and CMPXCHG16B stay rejected. Both engines run the new forms on the shared semantics, one instruction at a time, so a locked instruction is indivisible today and LOCK changes no result; `docs/cpu/instruction-registry.md` states the ordering, alignment, compare-failure and fault rules a guest scheduler must preserve. A failed compare still writes the destination, so it faults on memory that cannot be written. Nothing is lowered to ARM64 atomic instructions, and no multi-thread behaviour is established. Fourteen SDM-derived cases already in `cpu_known_answers.rs` moved from refused to verified, with 62 LLVM-assembled fixtures and five new tests in `x86_atomic.rs`; not compared with x86 hardware and awaiting independent review.
|
||||
- Added CPUID with a fixed, host-independent guest contract (#130). It reports a synthetic processor with the vendor string `Xenora guest` and sets a feature bit only when every instruction of that feature is implemented: CMOV, POPCNT, LZCNT and long mode today. SSE and SSE2 are not reported while parts of them, such as RSQRTPS and MFENCE, are still rejected, so the table is truthful about Xenora and not a plausible hardware model. Unlisted leaves return zeros. `tests/cpu_features.rs` pins every leaf in both engines, requires each reported feature's instructions among the executed fixtures, and holds a refused witness instruction for 31 unreported features. `docs/cpu/instruction-registry.md` gives the table and the rule for reporting a new feature. Not compared with a processor; awaiting independent review.
|
||||
- Added six Wave32 gfx1030 VOP1 integer forms through the semantic registry, including bit scans and a two-register swap under EXEC (AMD RDNA 2 ISA guide section 12.8, #215). The compiler accepts 752 guide-derived cases and rejects 610 programs at the oracle’s expected offsets. Native Metal verification and independent acceptance are pending.
|
||||
- Added delay-loaded imports to the static PE probe (#244). `xenora probe --mode static` now reads the PE32+ delay-load directory and lists each delay-loaded import in `imports.csv` with its DLL, symbol or ordinal, and delay import address table slot. A new `import_table` column, inserted after `iat_rva`, marks every row `ordinary` or `delayed`; `import_kind` stays the last column. The existing totals and `missing_imports.csv` still cover ordinary imports only, and the JSON report adds `delayed_imports`, `delayed_imported_dlls_count` and `delay_import_error`. The table is bounded by the directory's declared size, which must hold the empty descriptor that ends it, and each descriptor's DLL name, import address table and import name table must be present and start in section data. A table that breaks these rules, is truncated, sets a reserved attribute bit or uses the earlier virtual-address descriptor form is reported with the entries read before the problem. `xenora imports sync` leaves delayed rows out of its backlog. Inspection stays static: nothing is bound or executed. Covered by an original fixture (`fixtures/pe/delay-imports.exe`, generated by `fixtures/pe/delay-imports.py`) whose imports were cross-checked locally with `llvm-readobj --coff-imports` from LLVM 23.1.6; awaiting independent review.
|
||||
- Added the sixteen gfx1030 SOPK integer forms through the semantic registry: `s_movk_i32`, `s_cmovk_i32`, `s_cmpk_{eq,lg,gt,ge,lt,le}_{i32,u32}`, `s_addk_i32` and `s_mulk_i32` (AMD guide sections 12.2 and 13.1.2), with SDST s0-s105 only and SIMM16 sign-extended (zero-extended for the unsigned compares). The registry gained the operand rules `sopk_sgpr` and `sopk_compare` and the operations `mov` and `cmov`; the decoder and the scalar translation fold them like SOP2 and SOPC. An independent guide-derived oracle (`tests/validation/tests/sopk.rs`, 4,184 cases and 398 rejections on both CPU interpreters and native Metal), an LLVM-assembled fixture `scalar-immediate.s` with IR and MSL goldens, and the LLVM three-way decoder check cover them (part of #215).
|
||||
- Added an independent guide-derived oracle for the Wave32 16-bit (`v_cmp_{lt..ge}_{i16,u16}_e32`) and 64-bit (`v_cmp_{f..t}_{i64,u64}_e32`) integer compares in the reference and the second interpreter (6,212 lane cases, 1,208 rejections; contract in `docs/shaders/vector-compare.md` section 2a). Part of #215.
|
||||
- Added `python3 -m qa rdna2 rank` to the read-only RDNA2 planner: it groups undeclared gfx1030 forms by the piece of work that would unlock them (an encoding variant of a declared form, a new operand rule, or a new primitive, from XML identity and operand shape only) and ranks the groups by forms per estimated cost, excluding claimed scopes, with `--no-float` to leave out floating-point groups until the FP contract exists (part of #215).
|
||||
- Added authoritative read-only x86-64 CPU inventory CLI (`python3 -m qa cpu-inventory`) over `crates/loader/x86/instructions.toml` via `generate_x86.load`, with opcode-map/prefix/operand summaries, native vs shared-semantic operation partitions from `dbt.rs`, fixture mnemonic evidence and a separate unsupported catalog. Does not count candidates as implemented. Covered by `tests/qa/test_cpu_inventory.py`.
|
||||
- Added typed runtime inventory CLI (`python3 -m qa runtime-inventory`) over `crates/loader/runtime/services.txt`, reporting implemented/partial/stub services separately from API-set aliases and leaving independently-verified empty unless recorded. Covered by `tests/qa/test_runtime_inventory.py`.
|
||||
|
||||
- Added `crates/loader/tests/cpu_known_answers.rs` (#155): 736 x86-64 cases whose results, flags, MXCSR state and faults come from the Intel SDM, with the AMD APM for some MXCSR flags, plus arithmetic, shift, packed-integer, multiply, divide and floating-point sweeps computed from the manuals' definitions. 700 cases were written before the CPU source was read; the rest and the sweeps came afterwards. The interpreter and the DBT both run them; the DBT route (ARM64 code or Rust helper) is confirmed by the fallback counter for straight-line cases and predicted for the others. 592 cases are verified, 133 use forms both engines refuse, and eleven, plus a self-modifying-code test, record open defects in five ignored tests: the reported address of a page-crossing fault, the fault class of a non-canonical address and of an instruction over 15 bytes, PE set by an exact unmasked overflow, and DBT blocks that stay cached after the guest rewrites them. Not compared with x86 hardware; awaiting independent review.
|
||||
- Added a typed runtime service registry (`crates/loader/runtime/services.txt`) and `xenora-runtime-gen`, which generates Win64 argument and result adapters, static metadata and a coverage report. It covers 20 services: 16 existing kernel32 services moved to typed handlers, and `sqrt`, `sqrtf`, `fabs` and `fabsf` with arguments and results in XMM registers. Conflicting keys, unlisted API sets, unsupported types and behaviour without an existing test are rejected. See `docs/runtime/registry.md`.
|
||||
- Added SSE and SSE2 floating point in scalar and packed, binary32 and binary64 forms: add, subtract, multiply, divide, minimum, maximum, square root, compares, COMI/UCOMI and the conversions between formats and integers (parts of #127 and #128; awaiting independent review). `crates/loader/src/softfloat.rs` computes every result exactly and rounds once, with MXCSR rounding modes, sticky flags, denormals-are-zero, flush-to-zero, tininess after rounding and x86 NaN rules; host floating point is not used because ARM64 differs. An unmasked exception exits with `SimdException` and leaves everything but MXCSR unchanged. RCP, RSQRT and MMX conversions are rejected, and no floating-point form is translated to NEON yet.
|
||||
- Added 6,824 floating-point vectors computed with exact fractions by `tests/x86/float_reference.py`, run through both engines from registers and memory and through the packed forms, and more than two million round-to-nearest results compared with the host's IEEE 754 hardware.
|
||||
- Added XMM0-XMM15 and MXCSR to the guest CPU state, and the SSE and SSE2 moves and packed integer forms: aligned, unaligned, scalar, half and non-temporal moves, MOVD/MOVQ, sign-mask extraction, bitwise operations, wrapping and saturating arithmetic, compares, minimum, maximum, average, multiplies, PSADBW, packs, unpacks, shifts, shuffles, PINSRW, PEXTRW, LDMXCSR and STMXCSR (parts of #124, #125, #126 and #128; awaiting independent review). Operations with identical NEON lane semantics are translated to ARM64; the rest call the shared semantics. Misaligned 16-byte operands and reserved MXCSR bits raise a distinct general-protection exit. MXCSR is state only: floating-point arithmetic is not implemented.
|
||||
- Added 374 LLVM-assembled vector instructions with a byte-array reference, compared with both engines over 23,936 states, plus alignment, fault, width and mixed-sequence tests.
|
||||
- Added a declarative x86-64 instruction registry (`crates/loader/x86/instructions.toml`) and its generator, `crates/loader/generate_x86.py`, with `validate`, `generate` and `--check` modes. The static probe, the interpreter and the native DBT now share one decoder driven by its tables, so instruction boundaries, rejected forms and reported support agree. Overlapping encodings, such as a sign extension claiming the MOV-immediate opcodes, fail validation. See `docs/cpu/instruction-registry.md`.
|
||||
- Added integer instructions for 8-, 16-, 32- and 64-bit register and checked memory operands: the eight ALU operations, TEST, INC, DEC, NEG, NOT, XCHG, ROL, ROR, SHL, SHR, SAR, MUL, IMUL, DIV, IDIV, CMOVcc, SETcc, BT, BTS, BTR, BTC, BSF, BSR, POPCNT, TZCNT, LZCNT, CBW/CWD families, PUSH, POP, LEAVE, RET imm16 and flag instructions, with parity and auxiliary-carry flags and a distinct divide-error exit (parts of #65, #66, #68, #70, #71, #73, #118 to #123, #194 to #196; awaiting independent review). Forms the DBT does not lower to ARM64 call the same Rust semantics and are counted.
|
||||
- Added 985 LLVM-assembled integer instructions with a bit-level reference that reads only their assembly text, compared with the interpreter and the DBT over 47,280 states, plus 4,000 random instruction sequences compared between the engines.
|
||||
- Added sixteen gfx1030 SOP2 integer forms through the semantic registry: `s_min_i32`, `s_min_u32`, `s_max_i32`, `s_max_u32`, `s_cselect_b32`, `s_bfm_b32`, `s_mul_i32`, `s_bfe_u32`, `s_bfe_i32`, `s_absdiff_i32`, `s_lshl1_add_u32` to `s_lshl4_add_u32`, `s_mul_hi_u32` and `s_mul_hi_i32` (AMD guide section 12.1). Min and max set SCC from the strict compare (a tie gives S1 and SCC 0), `s_cselect_b32` reads SCC and is refused when SCC is unset, and BFM, MUL, MUL_HI and CSELECT leave SCC unchanged. The registry gained these primitives, a `selected_src0` SCC effect, the select's SCC input and a declared `shift_amount` for the shift-and-add forms; `ScalarAluOp::evaluate` now returns an optional SCC. Both reference interpreters, written separately from the guide, run the same sixteen forms and are checked against 21,070 guide-derived cases on both CPU interpreters and on native Metal; 597 rejected programs are refused by both interpreters and by the compiler. A new LLVM-assembled fixture covers all sixteen. Part of #215.
|
||||
- Added MOVZX, MOVSX (0F B6/B7/BE/BF) and MOVSXD (63) for register and checked memory operands in the interpreter and the native DBT, with exact lengths in the static probe (parts of #65, #66, #67, #68 and #117; awaiting independent review). Covered: 16-, 32- and 64-bit destinations, AH/CH/DH/BH without REX, FS/GS bases and RIP-relative operands. Other 0x66 forms are rejected instead of running at the wrong width. Known-answer encodings come from the LLVM assembler; MOV immediates (B8-BF) have regressions proving they are never read as sign extensions.
|
||||
- Added FNINIT (`DB E3`), the one instruction a C program built with the mingw-w64 runtime needs that the decoder refused (#378, part of Gate A2). Guest state gains the x87 control, status and tag words in `CpuState::x87`, and FNINIT sets them to the Intel SDM values `037F`, `0` and `FFFF`. Both engines run the shared semantics; nothing is lowered to ARM64 and the host's floating-point state is never touched. The registry gains a form key, `rm`, that pins a register-only form to one ModRM byte, because the other bytes of `DB /4` are different instructions. No other x87 instruction exists: FNSTCW, FLDCW, FNCLEX, FWAIT and all x87 arithmetic stay rejected, there are no x87 data registers, nothing can read the three words back, and CPUID still reports no FPU. Nine SDM-derived cases in `cpu_known_answers.rs`, whose harness now starts every case with the three words away from their reset values and requires every other instruction to keep them, one assembled fixture checked by the text-only reference in `x86_integer.rs`, and a sweep of every ModRM byte under opcodes `D8` to `DF` in both engines cover it. Not compared with x86 hardware; awaiting independent review.
|
||||
- Added Phase II infrastructure CLIs under `scripts/qa` and `scripts/release` (#277): read-only RDNA2 expansion planning over live inventories, unified verification profiles with stale-evidence detection, CPU/runtime coverage scans, benchmark regression comparisons that reject incompatible identities, git rename/delete scope collision reports, and release-readiness reports with SBOM/checksum/bundle checks. Covered by `tests/qa` and `tests/release`; advisory until reviewed.
|
||||
- Added advisory infrastructure QA helpers under `scripts/qa/` and `scripts/release/` (issue #277): exit-status-preserving orchestration with JSON reports, PR scope/DCO/artifact checks, benchmark percentile analysis over existing samples, environment and repository health diagnostics, ARM64 Mach-O/bundle/codesign helpers, and checksum manifests. Covered by `tests/qa/` and `tests/release/`; checks stay advisory until reviewed.
|
||||
- Recorded agent-queue live smoke evidence for issue #180 against the disposable private repository `ranveersoni98/xenora-agent-queue-smoke`, including claim grant, overlap refusal, release, not-ready denial, progress renew and a successful audit dispatch after fixing comment-only `apply_actions` and audit permissions/argparse issues.
|
||||
- Added twelve gfx1030 VOP2 vector integer forms through the semantic registry: `v_mul_i32_i24`, `v_mul_hi_i32_i24`, `v_mul_u32_u24`, `v_mul_hi_u32_u24`, `v_min_i32`, `v_max_i32`, `v_min_u32`, `v_max_u32`, `v_xnor_b32`, `v_add_nc_u32`, `v_sub_nc_u32` and `v_subrev_nc_u32` (AMD guide section 12.7), with SRC0 a VGPR, an SGPR, `vcc_lo`, an inline integer or a literal. The registry gained a `vop2_vgpr` operand rule, the vector operations `mul24` and `mul_hi24`, a declared `source_order` for SUBREV, and a per-lane `VectorBinary` that selects one reusable MSL template per operation. Both reference interpreters, written separately from the guide, run the same twelve forms and are checked against 2,040 guide-derived cases, each asserting every lane of a 7-, 32- or 45-lane dispatch (partial, empty and full EXEC), on both CPU interpreters and on native Metal; 575 rejected programs are refused by both interpreters and by the compiler at the same word. A new LLVM-assembled fixture computes every lane from its own input. Part of #215.
|
||||
- Moved the twelve Wave32 VOPC integer compares from #239 into the semantic registry (operand rule `vopc_vcc`, `vcc = "lane_mask"`, `wave = "wave32"`) with no behaviour change, and added `v_cmp_f_i32`, `v_cmp_t_i32`, `v_cmp_f_u32` and `v_cmp_t_u32` as registry forms under the same Wave32 VCC/EXEC contract, verified by an independent guide-derived oracle (`tests/validation/tests/vopc_f_t.rs`), a new LLVM-assembled fixture and native Metal (part of #215). `v_cmpx_*`, the VOP3 encoding and Wave64 stay unsupported.
|
||||
- Split the gfx1030 semantic registry into one file per encoding family (`crates/isa/semantics/rdna2/{sop2,sopc,sop1,vop2,vopc,vop3}.toml`, included in order by `rdna2.toml`; the split left the generated tables byte-identical), and added registry encoding variants: another encoding of a declared form is pure data. `v_add_nc_u32_e64` is now the first VOP3 variant of `v_add_nc_u32` (operand rule `vop3_vgpr2`), replacing its hand-written decoder and instruction with no behaviour change (part of #215).
|
||||
- Added sixteen gfx1030 SOP2 integer forms through the semantic registry: `s_min_i32`, `s_min_u32`, `s_max_i32`, `s_max_u32`, `s_cselect_b32`, `s_bfm_b32`, `s_mul_i32`, `s_bfe_u32`, `s_bfe_i32`, `s_absdiff_i32`, `s_lshl1_add_u32` to `s_lshl4_add_u32`, `s_mul_hi_u32` and `s_mul_hi_i32` (AMD guide section 12.1). Min and max set SCC from the strict compare (a tie gives S1 and SCC 0), `s_cselect_b32` reads SCC and is refused when SCC is unset, and BFM, MUL, MUL_HI and CSELECT leave SCC unchanged. The registry gained these primitives, a `selected_src0` SCC effect, the select's SCC input and a declared `shift_amount` for the shift-and-add forms; `ScalarAluOp::evaluate` now returns an optional SCC. Both reference interpreters, written separately from the guide, run the same sixteen forms and are checked against 21,070 guide-derived cases on both CPU interpreters and on native Metal; 597 rejected programs are refused by both interpreters and by the compiler. A new LLVM-assembled fixture covers all sixteen. Part of #215.
|
||||
|
||||
- Added guest mutexes, critical sections, SRW locks, condition variables, synchronous one-time initialization, interlocked SLists, and TLS and FLS slots. Ownership is per guest thread (TEB). Calls that would have to block stop the guest with an explicit runtime-limit fault, because there is no guest scheduler yet. An original PE32+ fixture calls every service through its import table, using two guest TEBs. See `docs/interfaces.md`.
|
||||
|
||||
- Added an MSVC decorated-name decoder (`xenora_import_gen::demangle`), and import manifests now show undecorated names for C++ imports that need manual engineering. Unsupported constructs return no result rather than a guess. Tests decode names mangled independently by clang for `x86_64-pc-windows-msvc`.
|
||||
|
||||
- Added a guest service dispatch benchmark (`cargo bench -p xenora-loader --bench service_dispatch`). It runs correctness-gated guest loops that call services through the import table under the DBT; see `docs/testing/benchmarks.md`.
|
||||
|
||||
- Added a `runtime_services` fuzz target (`scripts/fuzz.sh runtime_services`) and a stable-toolchain replay test sharing the same driver. Both call random sequences of the standard guest services with zero, all-ones, writable, read-only, executable, unmapped, raw and earlier-result arguments, and check after every call that read-only and code memory are unchanged and nonvolatile registers are preserved. Writable guest memory is filled from a deterministic pattern so corpus bytes are reserved for dispatch. An earlier 300-second campaign's input and edge counts are withdrawn: that run exhausted each input while filling the 65,536-byte writable region and never reached the dispatch loop. After the harness fix, a local 300-second campaign on Apple Silicon (`scripts/fuzz.sh runtime_services 300`) ran 96,589 inputs (4,008 coverage edges, 9,940 features) without a crash; the first minutes also found a ~3.7 GiB `XMemAlloc` host OOM, which is now fixed by failing closed on overflowing sizes and routing mappings through the virtual allocation budget. Services that wait on real time or reach native Metal are excluded.
|
||||
|
||||
- Added guest system information, memory status, calendar time conversion, interrupt time and sleeping. The guest sees a configurable simulated machine (`GuestSystemProfile`, one processor by default), kept separate from the detected host hardware (`HostCapabilities`). Sleeping goes through the injectable clock, so tests advance time deterministically. An original PE32+ fixture verifies `SYSTEM_INFO`, `MEMORYSTATUSEX` and `SYSTEMTIME` layouts and leap-year handling against dates computed independently.
|
||||
|
||||
- Added services that call guest code and continue when it returns. The import dispatcher can run a sequence of guest callbacks on a checked stack frame, verifying the Win64 nonvolatile registers after each one. The CRT uses this for `qsort`, `qsort_s`, `bsearch`, `bsearch_s`, `_initterm`, `_initterm_e`, onexit tables, `atexit` and `_cexit`. Kernel32 uses it for `InitOnceExecuteOnce` and `FlsFree` cleanup callbacks. Original guest comparators and initializers in a PE32+ fixture verify ordering, stop-on-failure and register preservation.
|
||||
|
||||
- Fixed the import generator classifying the synchronization API-set entries for `CreateSemaphoreA`, `CreateSemaphoreW` and `ReleaseSemaphore` as stubs, which overrode the runtime handlers. A CLI test now checks that every generator entry marked as a standard service resolves to a registered, non-stub loader handler.
|
||||
|
||||
- Added guest module lookup and named symbol resolution for built-in Kernel32 and UCRT services.
|
||||
|
||||
- Added process exit and the first Gate A milestone, A1 (#329). `kernel32.dll!ExitProcess` stops the guest with the new `ExitReason::ProcessExit(status)`, carrying all 32 bits of the status, and never ends the host; a returning entry point does the same with EAX. The exit closes every guest handle, including Winsock sockets and task-queue handles, and the engine that ran the guest executes nothing further. A TLS callback that exits ends startup with that exit as its outcome, and the remaining callbacks and the entry point do not run. Startup reserves the page holding the return addresses the engine intercepts, so an image mapped over them is refused. `atexit` functions are not run. A1 is an original C program with no C library linked (`tests/compat_fixtures/gate_a1.c`): `crates/loader/tests/gate_a1.rs` builds it from source with clang and an LLD on every run, executes it through the loader, the standard services and the DBT at `-O0`, `-O1`, `-O2` and `-Os`, and checks its exit status, its report, its files and its memory against values recomputed in Rust. `docs/testing/gate-a.md` records what A1 shows and that Gate A stays open until the hosted milestone, A2, passes. Verified locally with two compilers; awaiting independent review.
|
||||
|
||||
- Added same-process guest file handle duplication with a shared file position.
|
||||
|
||||
- Added guest file and directory enumeration with typed search handles.
|
||||
|
||||
- Added closed-file moves and file and directory attribute queries on the synthetic guest drive.
|
||||
|
||||
- Added nested guest directories and checked file deletion on the synthetic drive.
|
||||
|
||||
- Added the second Gate A milestone, A2 (#419): an original hosted C program, `tests/compat_fixtures/gate_a2.c`, built from source by the new test `crates/loader/tests/gate_a2.rs` with the mingw-w64 C runtime (UCRT) and run through the loader, the standard services and the ARM64 DBT. The runtime's own startup code runs before `main`. The program takes `argc` and `argv`, sorts heap data with `qsort`, prints with `printf`, writes a report with `fprintf` and reads it back with `fgets`, registers a function with `atexit` and returns from `main`. At `-O0`, `-O1`, `-O2` and `-Os` it ends with exit status 0, and its captured output and its report match, byte for byte, text recomputed in Rust. Seven more tests cover other arguments, four wrong command lines, a step budget that is too small, and control variants that end in a failed check, in `exit(42)` and in `abort()`. The test needs mingw-w64 on the host and fails, not skips, without it, so the CI workflow now installs it. Nothing from mingw-w64 is stored in the repository. Local runs used mingw-w64 14.0.0 with GCC 16.2.0. This is one program and one C runtime, compared by hand with a native build of the same source and not with Windows or x86 hardware; `docs/testing/gate-a.md` lists what it does not show. Awaiting independent review.
|
||||
|
||||
- Added file seeking and end-of-file resizing on the synthetic guest drive.
|
||||
|
||||
- Added a bounded synthetic guest drive with synchronous file open, read, write, and size queries.
|
||||
|
||||
- Added files for a hosted C program (#402, part of Gate A2): `fopen`, `fclose`, `fgets` and `perror`, and file streams for the output services from #400, so `fprintf`, `fwrite` and `fputs` write to a file `fopen` returned. The files are the ones on the in-memory `C:` drive behind `CreateFileW`, so a file written through a C stream is the file `ReadFile` reads, and the reverse. `fopen` takes `r`, `w` or `a` with `+`, `b` and `t` as Microsoft's page describes them; text mode, the default, stores a line feed as carriage return and line feed, reads the pair back as a line feed and ends input at `CTRL+Z`. Failures return their documented results; the `errno` values beyond `EINVAL` for a null or empty argument are Xenora's choice. Nothing is buffered, there is no seeking, a C stream takes no part in Win32 sharing, and the other mode characters are refused. All four services are `partial`. Eight tests in `runtime_services.rs`, four in the new `crt_files.rs` that cross-check with `ReadFile` and `WriteFile`, and a unit test of the mode strings cover it. Not compared with Windows; awaiting independent review.
|
||||
|
||||
- Added unnamed guest semaphores with checked release and immediate mixed-object waits.
|
||||
|
||||
- Added non-alertable extended event waits through both Win64 wait APIs.
|
||||
|
||||
- Added the C runtime's `exit`, `_exit` and `abort` (#395, part of Gate A2), on top of the process exit from #329. A C program ends through `exit`, not `ExitProcess`, and a program built with the mingw-w64 runtime imports all three; the loader refused it before its entry point because they did not resolve. `exit` calls the functions registered with `atexit` and `_crt_atexit`, most recently registered first, and then ends the guest with `ExitReason::ProcessExit(status)`; `_exit` ends it with its status and `abort` with exit code 3, and neither calls a registered function. All three go through the same cleanup as `ExitProcess` and never end the host. A function registered while `exit` runs is called next, as ISO C requires; `exit` called again from a registered function, which ISO C leaves undefined, runs the remaining functions once and ends with the later status. All three are partial: no stream is flushed because there are none, `abort` prints no message and calls no `SIGABRT` handler, and thread-local destructors are not run. Nine tests in `crt_exit.rs` call them from guest code. `docs/testing/gate-a.md` now describes A2 as in progress and not passing. Not compared with Windows; awaiting independent review.
|
||||
|
||||
- Added immediate wait-any and wait-all for guest event handles.
|
||||
|
||||
- Added guest CRT signed and unsigned 64-bit conversions for narrow and wide strings.
|
||||
|
||||
- Added command-line arguments for a hosted C program (#392, part of Gate A2): the C runtime services `__p___argc`, `__p___argv`, `__p__environ`, `_configure_narrow_argv` and `_initialize_narrow_environment`, and a host method, `ServicesState::set_program_arguments`, that supplies the program's `argv`. A program built with the mingw-w64 runtime gets `argc`, `argv` and `envp` for `main` through these five, and the loader refused it before its entry point because they did not resolve. After configuration the guest finds the host's arguments in `__argc` and `__argv`, each NUL-terminated, with a null pointer after the last; with no host input it gets one empty argument, as ISO C specifies. The host method refuses a NUL byte, more than 32,767 bytes in all, and a call after the guest has built its table. The three variables are documented and the two initialization functions are not, so their behaviour is Xenora's: no code page, no wildcard expansion, and an empty environment table. All five are `partial`. Four tests in `runtime_services.rs` call the services from guest code and compare what the guest sees with what the test supplied. Not compared with Windows; awaiting independent review.
|
||||
|
||||
- Added bounded guest CRT long-integer parsing for byte and wide strings.
|
||||
|
||||
- Added standard output for a hosted C program (#400, part of Gate A2): a `printf` formatting engine, the standard streams, and capture of what the guest writes to `stdout` and `stderr`. The services are `__acrt_iob_func`, `__stdio_common_vfprintf` (what `printf` and `fprintf` call in a program built with the mingw-w64 runtime), `fwrite`, `fputs`, `fflush` and `setvbuf`; a host reads the output through `ServicesState::standard_output` and `standard_error`. The engine handles the flags, width, precision and size prefixes of `d`, `i`, `u`, `o`, `x`, `X`, `c`, `s`, `p` and `%%` as Microsoft's format specification page and ISO C describe, reading arguments from the guest's `va_list`. The standard streams are text-mode streams, so a line feed is captured as carriage return and line feed. Floating-point and wide conversions, a locale object, other streams and files are not modelled and stop the guest with the runtime-limit fault instead of printing something wrong; `%n` and unknown conversions return -1 with `EINVAL`. All six services are `partial`. The engine's output matches the host C library's `snprintf` on 2,600 generated cases whose result ISO C defines (`crates/loader/tests/printf/reference.py`), with hand-written cases for the Windows-specific rules, and seven tests in `runtime_services.rs` call the services from guest code. Not compared with Windows; awaiting independent review.
|
||||
|
||||
- Added guest CRT errno accessors and allocation failure reporting for the synthetic main thread.
|
||||
|
||||
- Added nine C runtime services that a C program's startup code calls or imports before `main`, and one alias (#382, part of Gate A2): `_set_app_type`, `_set_new_mode`, `_configthreadlocale`, `__setusermatherr`, `_set_invalid_parameter_handler`, `__p__fmode`, `__p__commode`, `signal` and `SetUnhandledExceptionFilter`, plus `memcpy` through `api-ms-win-crt-private-l1-1-0.dll`. A program built with the mingw-w64 runtime imports all of them, and the loader refused it before its entry point because they did not resolve. Each records what it is given and returns what its public documentation says: the previous mode, setting or handler, the documented failure value, or the address of the guest variables `_fmode` and `_commode`. All nine are declared `partial` in the typed registry because nothing acts on a recorded value: no handler or filter is ever called, no signal is raised, there is no locale, and nothing reads `_fmode` yet. `ServicesState` gains two read-only accessors, `crt_app_type` and `crt_user_math_error`. Five tests in `runtime_services.rs` call the services from guest code through a bound import table. Not compared with Windows; awaiting independent review.
|
||||
|
||||
- Added guest CRT allocation, zeroed array allocation, resizing, and release.
|
||||
|
||||
- Added private guest heap creation and destruction with per-heap allocation ownership.
|
||||
|
||||
- Added default guest heap reallocation with data preservation and an in-place-only option.
|
||||
|
||||
- Added the synthetic default process heap with allocation, size queries, and release.
|
||||
|
||||
- Added `VirtualProtect`, `VirtualQuery` and `__C_specific_handler` as `stub` services so that a C program built with the mingw-w64 runtime can bind its imports (#388, part of Gate A2). Such a program imports all three and does not call them on a normal run; without them the loader refused it before its entry point. A call to any of them stops the guest with the runtime-limit fault (`IllegalInstruction(0xFE)`) and writes nothing, so a program that needs one stops there and cannot run on with a made-up result. No page protection is changed, no region is described and no exception is dispatched. The service generator's API-set table gains `api-ms-win-crt-private-l1-1-0.dll` for `ucrtbase.dll`, which is inferred and not taken from a document that names it. Two tests in `runtime_services.rs` call the stubs from guest code and check how they resolve. Not compared with Windows; awaiting independent review.
|
||||
|
||||
- Added Win64 signatures for wide-string length and comparison and overlapping byte moves to the import catalog.
|
||||
|
||||
- Added guest CRT wide-string length and comparison using Windows 16-bit code units.
|
||||
|
||||
- Added checked guest CRT byte string comparison with `strcmp` and `strncmp`.
|
||||
|
||||
- Added bounded guest CRT byte fill, copy, move, and comparison services.
|
||||
|
||||
- Added guest CRT string length services for UCRT and its string API set.
|
||||
|
||||
- Added unnamed guest events with manual and automatic reset, signaling, immediate waits, and same-process handle duplication.
|
||||
|
||||
- Added same-process duplication of synthetic thread handles with independent closure.
|
||||
- Added a rights-checked `GetThreadId` query for handles to the synthetic guest thread.
|
||||
- Added 32-bit and 64-bit millisecond uptime queries for synthetic Windows guests.
|
||||
- Added high-resolution elapsed-time queries for synthetic Windows guests through `QueryPerformanceCounter` and `QueryPerformanceFrequency`.
|
||||
|
||||
- Added audio PCM streaming and sandboxed virtual filesystem (VFS) integration to the native application runtime (Gate 6, #284). The C interface gains audio management functions (`xenora_session_audio_init`, `xenora_session_audio_submit`, `xenora_session_audio_read`, `xenora_session_audio_status`, `xenora_session_audio_set_volume`) and virtual filesystem functions (`xenora_session_vfs_set_root`, `xenora_session_vfs_open`, `xenora_session_vfs_read`, `xenora_session_vfs_seek`, `xenora_session_vfs_close`, `xenora_session_run_audio_vfs_fixture`). The audio subsystem implements a bounded ring buffer supporting configurable sample rates, channel configurations, PCM formats (S16LE, F32LE), volume attenuation, mute, and buffer underrun tracking. The virtual filesystem operates within an explicitly configured, sandboxed directory root (`fixtures/assets`), strictly rejecting path traversal attempts (`..`, absolute paths, null bytes) and invalid or stale handles, while supporting sequential and seekable file reads (`XENORA_SEEK_SET`, `XENORA_SEEK_CUR`, `XENORA_SEEK_END`). An original PE fixture (`fixtures/pe/audio_vfs.exe`, generated by `fixtures/pe/audio_vfs.py` using only the supported ARM64 DBT instruction subset) opens `asset.bin` (generated by `fixtures/assets/generate.py`), loads a 2x2 RGBA texture and 256 PCM audio samples via VFS, initializes audio, submits the PCM audio queue, and renders the loaded texture on Metal. Verified with unit tests, four Metal acceptance tests in `crates/ffi/tests/audio_vfs.rs`, UI controls and a `--smoke-audio-vfs` CLI in `Xenora.app`.
|
||||
- Added persistent GPU resources, dynamic texture updates, and resource retirement to the native application (Gate 5, #279). The C interface gains `xenora_resource`, resource types (`XENORA_RESOURCE_TYPE_*`), `xenora_session_create_texture`, `xenora_session_update_texture`, `xenora_session_destroy_resource`, `xenora_session_resource_info`, `xenora_session_render_textured`, and `xenora_session_run_textured_fixture`. Persistent GPU resources (textures) are explicitly allocated and owned by the execution session, surviving across execution slices without re-allocation. Dynamic texture subregion updates modify GPU texture contents in-place on native Metal. Resource retirement is completion-aware: destroying a resource held by in-flight GPU execution marks it retired and safely defers destruction until in-flight work completes, while rejecting subsequent caller queries with typed error codes. An original PE fixture (`fixtures/pe/textured.exe`, generated by `fixtures/pe/textured.py` using only the supported ARM64 DBT instruction subset) creates a persistent 2x2 texture via `xenora.dll!texture_create`, renders frame 0, updates pixels via `xenora.dll!texture_update`, renders frame 1, and retires the resource via `xenora.dll!texture_destroy`. Xenora.app gains "Run textured fixture" controls and `--smoke-resources`. Six GPU acceptance tests with Metal validation verify persistent texture lifecycle across multiple frames, dynamic 1x1 and 2x1 subregion updates on native Metal, completion-aware deferred retirement, rejection of invalid/stale/double-destroyed handles, slot reuse across 200 cycles without leaking, and full guest fixture execution. Wired acceptance tests into `scripts/test-gpu.sh`.
|
||||
- Added interactive guest execution with dynamic input handling and rendering to the native application (Gate 4, #276). The C interface gains `xenora_session_start_interactive_loop`, `xenora_session_send_input`, `xenora_session_queue_input`, and `xenora_session_get_recorded_frame`, along with input masks (`XENORA_INPUT_*`) and `xenora_input_state`. The original interactive guest fixture (`fixtures/pe/interactive.exe`, generated by `fixtures/pe/interactive.py` using only the supported ARM64 DBT instruction subset) polls host input via `xenora.dll!input_poll` and steers its rendered column position (0..3) on native Metal. Xenora.app gains interactive frame-loop controls ("Interactive (300 frames)", "◀ Left", "▶ Right", "Release") and `--smoke-interactive`. Four GPU acceptance tests with Metal validation verify that input events drive guest state and pixel geometry, deterministic input replay reproduces identical frame sequences across multiple sessions, key release and focus loss cleanly hold position without stuck keys, and destroying an interactive session joins promptly. Wired the interactive tests into `scripts/test-gpu.sh`.
|
||||
- Added persistent guest rendering with pause, resume and stop to the native application (Gate 3, #266). The C interface gains `xenora_session_start_frame_loop`, `xenora_session_pause_frame_loop`, `xenora_session_resume_frame_loop`, `xenora_session_stop_frame_loop`, and `xenora_session_frame_loop_status`, plus new states (`XENORA_LOOP_*`). The guest fixture (`fixtures/pe/frame-loop.exe`, generated by `fixtures/pe/frame-loop.py` without external toolchains) runs on a session-owned thread and repeatedly calls `xenora.dll!frame_submit` until told to halt; each frame is rendered on native Metal, checked per pixel against geometric expectations, and returned via read-back RGBA8 buffers. Destroying a running or paused session safely stops its loop outside the global session lock. Xenora.app gains persistent frame-loop controls ("Start 300 frames", "Pause", "Resume", "Stop") and displays live frames with their frame index. Five GPU acceptance tests with Metal API and GPU validation verify frame ordering over 300 frames, live sampling across 2,000 frames without backwards progression, pause/resume/stop lifecycle, prompt join on session destruction, and stable memory footprint across repeated sessions. Added `--smoke-loop` to Xenora.app and wired the acceptance tests into `scripts/test-gpu.sh`.
|
||||
- Added read-only executable inspection to the native app (#267). Xenora.app can open a PE file with Open Executable…, by dropping it on the window, or from Finder (it registers as an alternate viewer for Windows executables). The new C function `xenora_inspect_executable` returns a text report built from the existing static probe and loader validation: file size and SHA-256, header facts, whether `ParsedPe::parse` accepts the file, sections, imports not provided by Xenora's standard runtime services, the bounded static disassembly's count of instructions the ARM64 DBT does not support with the first one's address, and relocation and TLS counts. Nothing in the file is executed, and executing opened files remains unavailable pending #257. Inputs over 256 MiB are refused before reading. A panic inside the probe is reported as a Xenora defect instead of crashing the app; the new truncation test found one in `probe_pe_bytes` (truncations of `trusted-runner.exe` to 1,556–1,665 bytes slice past the end of the file while reading an import name), reported as #270 and not fixed here. Checked with the x1 executables in `experiments/x1/fixtures`, which the app does not embed, with malformed inputs, and in the window through the Finder open path and the Open panel; drag and drop was not exercised.
|
||||
- Added eleven gfx1030 SOP1 unary forms through the semantic registry: `s_not_b32`, `s_brev_b32`, `s_bcnt0_i32_b32`, `s_bcnt1_i32_b32`, `s_ff0_i32_b32`, `s_ff1_i32_b32`, `s_flbit_i32_b32`, `s_flbit_i32`, `s_sext_i32_i8`, `s_sext_i32_i16` and `s_abs_i32` (AMD guide section 12.3). Searches that find nothing return -1, `s_abs_i32` of 0x80000000 stays 0x80000000, and only NOT, BCNT0, BCNT1 and ABS write SCC. The registry gained these primitives, a `sop1_sgpr` operand rule, and a declared `source_bits` for sign extension that is checked against the XML's 8- and 16-bit source operands. The reference and independent semantic-review interpreters, written separately from the guide, evaluate the same eleven forms and are checked against 4,126 guide-derived cases on both CPU interpreters and on native Metal with validation; 231 rejected programs are refused by both interpreters and by the compiler. A new LLVM-assembled fixture covers all eleven. Part of #215.
|
||||
- Showed the first guest-driven frame in the native app (Gate 2, #263). The C interface gains `xenora_session_run_trusted_fixture`, which runs only the embedded trusted PE fixture: its x86-64 code is translated and executed, its `xenora.dll!fixture_draw` call compiles the x9 RDNA2 shader fixtures to MSL and renders on the native Metal device, and the 4×3 RGBA8 read-back is returned only if the guest halts with the CLI runner's expected results and every pixel equals the pixel shader's export, (1, 0, 0, 1) as opaque red. Xenora.app's "Run trusted fixture" button shows that frame, and `--smoke-frame` prints it. A `gpu-tests` test, run by `scripts/test-gpu.sh`, executes the fixture three times through the interface with Metal validation enabled. The frame is a read-back image, not drawable presentation, and no caller-supplied executable can run. Verified on one Apple Silicon Mac; the window was checked by screenshot.
|
||||
- Added a minimal native macOS application shell and its Rust interface (Gate 1 of the native application work). `crates/ffi` builds a static library with a versioned C interface (`crates/ffi/include/xenora.h`, version 1): opaque, generation-checked 64-bit session handles (never pointers), at most 64 live sessions, stable status codes, and panics caught at the boundary. Version 1 can only create and destroy sessions and parse the bundled trusted PE fixture; it executes no guest code. `app/` is a SwiftUI app built with Swift Package Manager that shows the interface version and the fixture's section count and entry point. `scripts/build-app.sh` builds an ad-hoc-signed, arm64-only `build/Xenora.app` with no entitlements and runs its `--smoke` check. Six Rust tests cover invalid, stale and double-destroyed handles, version mismatch, null outputs, 4,000 concurrent create and destroy cycles, and header/constant agreement. The CLI and headless workflows are unchanged. Verified locally on one Apple Silicon Mac (macOS 27.2.1, Swift 6.4, Rust 1.100.0); not yet run in CI.
|
||||
- Added the gfx1030 SOPC compares `s_cmp_{eq,lg,gt,ge,lt,le}_{i32,u32}` through the semantic registry, which replaces the hand-written `s_cmp_eq_u32` path. Each sets only SCC to whether the relation holds with SSRC0 on the left (AMD guide section 12.4); the registry gained a `compare` operation with a declared `relation` and a `sopc_scalar` operand rule. `Instruction::ScalarCompareEqU32` is now `Instruction::ScalarCompare { op: ScalarCompareOp, .. }`; `s_cmp_eq_u32` behaves as before. The reference and independent semantic-review interpreters, written separately from the guide, evaluate all twelve, checked against 7,824 guide-derived cases on both CPU interpreters and on native Metal with validation; 348 rejected programs are refused by both interpreters and by the compiler. A new LLVM-assembled fixture covers all twelve. Two literal selectors stay rejected. Part of #215, stage D.
|
||||
- Added eight gfx1030 SOP2 forms through the semantic registry alone: `s_andn2_b32`, `s_orn2_b32`, `s_nand_b32`, `s_nor_b32`, `s_xnor_b32`, `s_lshl_b32`, `s_lshr_b32` and `s_ashr_i32`, each with SCC = result != 0. Each is one registry entry with no per-form Rust; the registry gained these primitives and a declared shift-count width (`shift_count_bits = 5`, so shifts use S1[4:0] as in the AMD guide, section 12.1), which the generator applies as a mask and checks against the XML's unsigned count operand. The reference interpreter and the independent semantic-review interpreter, written separately from the guide, now evaluate the same eight forms and are checked against 6,896 guide-derived cases; a new LLVM-assembled fixture (`fixtures/rdna2/scalar-logic.s`) runs on CPU and native Metal with validation. A NULL destination (s125) stays rejected. Part of #215, stage C.
|
||||
- Added an independent operand-domain verification harness for the 9 supported SOP2 scalar ALU forms and 12 VOPC integer compares (`tests/validation/tests/operand_domains.rs`, part of #215 stage E): 4,788 generated cases (boundary values, 64-bit carry and borrow chains, aliased registers, every integer inline constant, literals, s105 and v255, partial and zero EXEC, VCCZ) and 498 rejections (missing literal words, and encodings outside Xenora's supported subset) run on `xenora_ref` and, as an ignored test picked up by `scripts/test-gpu.sh`, on native Metal. Expected values come from the public AMD RDNA 2 guide's pseudocode, written out in the test without Xenora code; this is agreement with a spec-derived reference, not with Xbox hardware. Local verification only: 32 deliberate code breaks were each caught; the guide leaves the width of `S1 + SCC` in `s_subb_u32` open, and those 8 cases are kept in their own family.
|
||||
- Added a declarative semantic registry for gfx1030 instruction forms (`crates/isa/semantics/rdna2.toml`, schema 1) and its generator, `crates/isa/generate_semantics.py`, with `validate`, `generate` and `--check` modes. The generator checks every declaration against a closed vocabulary and the pinned AMD XML snapshot (opcode, family, SCC input and output, operand widths and signed formats), rejects contradictory, incomplete or duplicate definitions, and emits static Rust tables marked as generated. The nine SOP2 forms moved onto it with no change in behaviour: the decoder's SOP2 dispatch and `ScalarAluOp`'s mnemonic, SCC read and evaluation are now generated, and evaluation goes through shared primitives instead of per-opcode code. All existing SOP2 tests, including the native Metal known answers and the LLVM comparison, pass unchanged. Decoding speed is unchanged (10.2 ns before, 10.1 ns after, per SOP2 instruction, release build on an Apple M5 Pro). Also added `scripts/audit/semantic_coverage.py`, which generates `docs/shaders/semantic-coverage.md`: per-family counts of identified, declared, decoded, lowered, reference-verified and Metal-verified forms, taking evidence only from `docs/status.toml`. Part of #215, stages A and B.
|
||||
- Added a native Metal blend pass, `NativeCompute::render_blend`: up to 16 flat-coloured triangles drawn in order into an RGBA8 target, each with its own colour write mask (any subset of R, G, B, A) and either blending disabled or separate RGB and alpha blend factors (Zero, One, source and destination colour and alpha, and their one-minus forms) and operations (Add, Subtract, ReverseSubtract, and Min and Max, which take the unweighted values). Checked on the GPU with Metal validation in 39 passes over two original overlapping triangles: a clear-only pass; blending disabled; each source factor with the destination term zeroed and each destination factor with the source term zeroed; every operation; additive clamping; separate alpha factors; a separate alpha operation; eight write masks (each channel alone, RGB, none, RGBA, and RG with blending); and a pass whose first draw is itself blended and masked. Colours are compared per channel against images derived independently (in exact fractions) from the public Metal blend equations, which a new CPU reference in `xenora-ref` also reproduces. The tolerance was fixed before measuring: channels whose exact result is a whole 8-bit value must match exactly, and channels that need rounding may differ by 1. On an Apple M5 Pro every rounded channel matched round-to-nearest exactly. Synthetic fixtures only; no console blend state is involved.
|
||||
- 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.
|
||||
- Added a `pe_parse` cargo-fuzz target that feeds malformed bytes to the PE32+ parser (`ParsedPe::parse`, `rva_to_file_offset`) and, only when the summed section mapping size and `SizeOfImage` are both at most 64 MiB, to the checked guest-memory mapping step (`load_into_memory`); nothing is executed. A 600-second local campaign (nightly cargo-fuzz, fork mode, seeded from the repository's synthetic PE fixtures, about 120,000 executions, coverage 267 edges) found two loader panics, reported to the CPU owner and not fixed here: truncated optional headers panic on out-of-range slices in `parse`, and `rva_to_file_offset` overflows `u32` when a section's address plus size exceeds 4 GiB. Run it with `rustup run nightly cargo fuzz run pe_parse`; `scripts/fuzz.sh` does not list it yet.
|
||||
- Added `NativeCompute::run_words_with_group_width` and `max_group_width` to run a trusted kernel at an explicit threadgroup width, rejecting zero and widths above the device or pipeline limit. Native tests check 91 legal width and grid-size pairs (widths 1 to 1,024, including non-divisible grids) against independently computed outputs, and confirm the dispatched group sizes, including trimmed last groups. On an Apple M5 Pro, in three release runs of a 4,096-thread integer-mixing kernel (30 samples per width), widths 64, 128 and 256 were within 0.3 % of each other in two runs, at a median of 58.8 µs of GPU time. Width 512 was 5 to 6 % slower and width 1,024 about twice as slow in all three runs. The first run was about 4.7 times slower overall for reasons not determined, and in it 128 and 256 were 3 to 4 % faster than 64. The default width of 64 is unchanged. This was measured on one device and one workload.
|
||||
- Added a native Metal depth pass, `NativeCompute::render_depth`: up to 16 triangles drawn in order into an RGBA8 target with an optional `Depth32Float` attachment, a chosen clear depth, a per-draw depth compare function (all eight) and depth write enable. A pass without an attachment accepts only `DepthState::DISABLED`. Colour and the stored depth are both read back; the depth values are returned as the texture read gives them, without numeric conversion. A draw can sample an original BC1 texture whose blocks are uploaded to a native `BC1_RGBA` texture without CPU decoding, gated on `supportsBCTextureCompression`. Checked on the GPU with Metal validation in 30 passes of original overlapping triangles: clear, every compare function at three depths, write enabled and disabled, depth test disabled (`Always` without writes) with an attachment and no attachment at all, and a BC1-textured draw. Colour and depth are compared per pixel against expectations derived independently from the geometry, the Metal compare semantics and the public BC1 rules, which a new CPU reference in `xenora-ref` also reproduces. These are synthetic fixtures only; no console depth formats or guest render state are involved.
|
||||
- Added a CPU BC7 block decoder in `xenora-texture` for all eight modes, with explicit handling of the invalid all-zero mode byte. It is checked by hand-derived tests and 430 known-answer vectors from a separate clean-room reference written from the Khronos Data Format Specification (merged in PR #224 without a changelog entry).
|
||||
- Added independent negative tests for gfx1030 extension words: truncated literal, SDWA, DPP16, DPP8 and MIMG NSA trailers (62 prefixes of 18 LLVM-assembled instructions), disallowed extensions, and length recognition kept apart from semantic validity. Tests only, with no decoder change (merged in PR #231 without a changelog entry).
|
||||
- Added the gfx1030 Wave32 VOPC compares `v_cmp_{lt,eq,le,gt,ne,ge}_{i32,u32}_e32`. VCC_LO is EXEC_LO & the per-lane test, always fully written, so empty EXEC gives 0. A compare result can feed `s_cbranch_vccz`, `v_mov_b32_e32 vN, vcc_lo` and another compare's source; nothing else, so EXEC never becomes data-dependent. A data-dependent `s_cbranch_vccz` is a wave-uniform branch over integer vector ALU code, lowered to a select at the join. The Metal kernel builds each mask by recomputing the 32 lanes of its own RDNA wave, with no SIMD-group, threadgroup or barrier assumption. The reference now runs lockstep Wave32 waves. Verified on an LLVM-assembled fixture plus 251 original programs (boundary operands, partial and empty EXEC, both branch edges, a partial final wave) against exact integer definitions: translator, reference and second interpreter agree on CPU, and all 252 match on native Metal with validation. LLVM agrees on every encoding. VOP3, SDWA, DPP, `v_cmpx` and Wave64 stay rejected. See `docs/shaders/vector-compare.md`.
|
||||
- Added the gfx1030 SOP2 forms `s_add_i32` and `s_sub_i32`, with SCC as signed overflow as defined in the AMD RDNA 2 ISA guide (sections 5.3 and 12.1). They are checked on CPU and on native Metal with validation on 400 boundary programs, four immediate-operand overflows and the scalar ALU fixture, plus eight hand-worked overflow and no-overflow cases on CPU.
|
||||
- Added the gfx1030 SOP2 scalar forms `s_add_u32`, `s_sub_u32`, `s_addc_u32`, `s_subb_u32`, `s_and_b32`, `s_or_b32` and `s_xor_b32`. They are decoded, executed by the reference and independent interpreters, and resolved by the translator, with SCC as carry, borrow or nonzero result. `v_mov_b32_e32` can now read a normal SGPR. Verified on 1,400 original operand vectors plus an LLVM-assembled fixture, on CPU and on native Metal with validation. The other SOP2 forms stay unsupported. See `docs/shaders/scalar-alu.md`.
|
||||
- Added `scripts/audit/test_inventory.py`, which lists the Cargo test inventory of two commits in temporary detached worktrees and reports removed, added, newly ignored and newly un-ignored tests, failing on any loss not explained in an `--allow` file. Run against the old PR #166 head 5450612 and main 951189c, it reports the 12 BC texture tests that head was missing (exit 1); the same commit against itself reports no change. Default features only; see `docs/testing/test-inventory.md`.
|
||||
- Added complete gfx1030 instruction metadata generated from AMD's public RDNA 2 XML: 1,465 base forms across 21 encoding families with fields, operands, flags and allowed extension words. A committed, normalised snapshot lets `crates/isa/generate_rdna2_meta.py --check` verify the generated table offline; CI runs it.
|
||||
- Added `xenora_isa::meta::identify`, which finds any gfx1030 instruction's form and exact length, including literal, SDWA, DPP and NSA words, and rejects truncated, unassigned and disallowed-extension encodings. It agrees with every LLVM-assembled fixture and with LLVM 23.1.6 on a probe set covering each family and extension word. Identification does not make an instruction executable: `SEMANTIC_FORMS` lists the forms with semantic decoding (46 as of the VOPC compares).
|
||||
- Added `xenora shaders coverage [--json]` and `xenora shaders inspect <file>` for per-family coverage and stream listings that separate decoding failures from unsupported semantics. Each instruction is decoded at its stream offset and branch targets are checked against the whole stream's boundaries, so supported branches are no longer misreported as unsupported operands. `xenora_decoder::decode_at` decodes a single instruction for such callers.
|
||||
- Added an agent task queue for the cpu, gpu, runtime, shared and qa areas: an *Agent task* issue form with priority and interface fields, a workflow that decides `/claim`, `/release`, `/reassign`, `/progress`, `/blocked`, `/unblock` and `/approve-acceptance` comments one at a time (dependency, cycle and file-overlap checks, 24-hour leases renewed by progress), a pull request check (linked claimed task, file ownership, overlap with other pull requests, independent `/verified <head sha>`), `scripts/agent-queue.sh` and `scripts/agent-sync.sh` (upstream fetch every 12 minutes, task branches in separate worktrees) and a machine-readable queue summary. The rules are standard-library Python in `scripts/agent_queue/` with unit tests in `tests/agent_queue/`; issue text is never executed and acceptance commands need maintainer approval. Only comments that start with a command start a job, so ordinary pull request comments never re-run verification, and only an accepted `/verified <full head sha>` evaluates the check again; and each claim run decides every unanswered command in order, so commands whose pending runs GitHub cancelled are still answered. See `docs/coordination/agent-tasks.md`. Unit tests pass locally; the workflows have not run on GitHub yet, and the pull request check stays advisory (it never blocks a merge) until a live smoke test and the migration of existing issues are done.
|
||||
- Added explicit claim-before-work rules for contributors and coding agents to `AGENTS.md`, `CONTRIBUTING.md` and the pull request template: check for existing claims, claim with `/claim`, keep a 24-hour lease alive with `/progress`, `/release` when stopping, and link the claimed issue. Without the claim workflow, the earliest valid claim comment wins.
|
||||
- Added a CPU decoder for a bounded subset of BC6H (signed and unsigned HDR) in
|
||||
`xenora-texture`: the four single-subset modes (Khronos modes 3, 7, 11 and 15, Microsoft
|
||||
modes 11 to 14), listed in `BC6H_SUPPORTED_MODES`, plus the reserved modes, which decode to
|
||||
zero as specified. The ten two-subset modes are rejected with `Bc6hError::UnsupportedMode`
|
||||
and are not implemented. Tests check hand-derived values and 128 known-answer vectors from a
|
||||
separate clean-room reference decoder.
|
||||
- Added native Metal upload and readback of BC4 and BC5 textures (UNORM and SNORM):
|
||||
`xenora-texture` gains a pitched `BcChannelUpload`, and `NativeCompute::read_bc_channel_upload`
|
||||
sends the original blocks to `BC4_R*` or `BC5_RG*` textures when the device reports BC
|
||||
support, failing with `supportsBCTextureCompression` otherwise. GPU tests cover six- and
|
||||
eight-value interpolation, equal and extreme endpoints (signed -128 reads as -1.0), red-green
|
||||
channel order, padded row and slice pitches, two layers and two mips against the CPU decoders
|
||||
and hand-derived anchors. On an Apple M5 Pro interpolated codes were within 1.71 codes of the
|
||||
exact values and up to two codes from the truncating CPU reference.
|
||||
Edge levels of 5×3 and 1×1 and invalid payloads (zero extents, short, oversized or
|
||||
block-count-mismatched buffers) are covered.
|
||||
- Added native Metal upload and readback of BC2 and BC3 textures: `xenora-texture` gains a
|
||||
pitched `BcAlphaUpload` for 16-byte blocks, and `NativeCompute::read_bc_alpha_upload` sends
|
||||
the original blocks to `BC2_RGBA` or `BC3_RGBA` textures when the device reports BC support.
|
||||
GPU tests cover explicit and interpolated (six- and eight-value) alpha, both colour endpoint
|
||||
orders, padded row and slice pitches, two layers and two mips against the CPU decoders and
|
||||
hand-derived anchors. On an Apple M5 Pro the native decoder's interpolated values were within
|
||||
8/7 (about 1.14) codes of the exact values, so up to two codes from the truncating CPU reference.
|
||||
Edge levels of 5×3 (one block row) and 1×1 are covered, invalid payloads (zero extents,
|
||||
short, oversized or block-count-mismatched buffers, bad pitches) are rejected before upload,
|
||||
and `MetalError::is_capability_unavailable` separates a device without BC support from an
|
||||
implementation failure.
|
||||
- Added CPU block decoders for BC2, BC3, BC4 and BC5 (UNORM and SNORM) in `xenora-texture`, with tests whose expected texels were derived by hand from the Microsoft and Khronos block-compression specifications. Interpolated values truncate toward zero, as the existing BC1 decoder does; GPU upload and sampling of these formats are not implemented yet.
|
||||
- Added `dbt::tests::sib_store_executes_through_the_native_dbt`, an independent DBT execution
|
||||
test that runs the SIB store form `mov [rsp + 0x20], rbx` through the native ARM64 DBT and
|
||||
verifies the value lands in guest memory.
|
||||
- Added 8/16-bit MOV memory-operand support (opcodes 0x88/0x8A, register-to-memory and
|
||||
memory-to-register) to the native ARM64 DBT.
|
||||
- Added GS/FS legacy segment prefix support to the native DBT and the bounded x86-64
|
||||
interpreter, including `CpuState.gs_base`/`CpuState.fs_base` offsets added to the effective
|
||||
address computation.
|
||||
- Added Win64 TEB allocation and `gs_base` initialization to synthetic guest startup.
|
||||
|
||||
### Changed
|
||||
- Registering an import key twice is now an error instead of silently replacing the first service, ordinals are distinct from names, and API sets in the import generator match exactly instead of by prefix.
|
||||
- `GetSystemTimeAsFileTime` now stops the guest on a null pointer, as on any other invalid pointer, instead of setting the last error.
|
||||
|
||||
- Simplified the claim rules in `AGENTS.md`, `CONTRIBUTING.md` and the pull request template at the maintainer's request: claim an issue by replying on it in plain words, never claim over an existing claim, and treat a claim as stale only after about one week without a pull request. The task-queue lease (`lease_hours` in `.github/agent-queue.json`) is now 168 hours to match, and `docs/coordination/agent-tasks.md` marks the queue commands as optional.
|
||||
- The static PE probe now marks x86-64 SIB memory addressing as DBT-supported, matching the
|
||||
native DBT.
|
||||
|
||||
### Fixed
|
||||
- `MockClock::advance` no longer wraps the FILETIME. A large advance made the synthetic wall clock run backwards while the performance count beside it stopped at its maximum; both now stop at their maximum (#204).
|
||||
- Fixed `DuplicateHandle` and `GetThreadId` naming the main thread from other guest threads, `OwningThread` in critical sections always holding the main thread's ID, the callback-depth limit being shared by all guest threads, and pending one-time initializations being unbounded.
|
||||
- Fixed the address reported when a guest memory access faults part-way across a 4 KiB page boundary (#175). An access that starts in a mapped page and runs into an unmapped or forbidden one now reports the first byte it may not touch; it used to report the start of the access. An access whose first byte fails reports the same address as before, and a failed access still reads and writes nothing. Three Intel SDM page-fault cases in `cpu_known_answers.rs` moved from open defect to verified on both engines. `crates/loader/tests/memory_page_boundaries.rs` checks permissions, adjacent pages, address overflow and the fault address at every 4 KiB guest boundary across two host pages (16 KiB each on Apple Silicon). Guest memory is checked in software, so the host page size does not affect these results. Four #82 expectations and one CRT `memmove` expectation that pinned the start address were corrected. Not compared with x86 hardware; awaiting independent review.
|
||||
- Fixed the native dependency audit reading Cargo JSON and inspection-tool output in the process locale encoding; it now reads and reports UTF-8 paths and diagnostics under an ASCII locale (#363).
|
||||
- Fixed a latent ARM64 `LSLV` encoding bug that forced bit 1 of the shift-count register field (part of #131). The dynamic binary translator uses `X10` in its only call, which already has that bit set. `RBIT`, `CLZ` and `LSLV` now panic on out-of-range register numbers before emitting an instruction. Encoding tests use words checked against LLVM's assembler.
|
||||
- Fixed flat (untextured) guest `DrawInstanced` draws in the synthetic D3D12-style graphics context (#148). A draw with zero instances or fewer than three vertices now draws nothing. A non-zero start vertex or start instance, more than one instance or more than three vertices now fails with `GraphicsError::Unsupported` instead of drawing the view's first triangle. Vertex reads stay inside the vertex buffer, so a view past its end, or one whose guest address would overflow, fails with `IndexOutOfRange` instead of reading neighbouring guest memory or panicking. `crates/loader/tests/repeated_frames.rs` runs these through repeated reset, record, close and execute frames on the software reference backend, with hand-derived pixels; no native Metal result is claimed.
|
||||
- Made the static probe and the binder share one bounded import parser, after the truncated-name fix for #270. Truncated, unterminated, empty or non-ASCII names, reserved bits and endless tables are reported by the probe and refused by the binder.
|
||||
- Fixed TLS callback metadata that was accepted or misread without an error (#78). A non-zero `AddressOfCallbacks` outside the image's sections, or 4 GiB or more above the image base, is now refused; it used to mean "no callbacks" or read the list from an unrelated place. The callback list must reach its null entry inside its section, where the section's zero-filled tail counts, and a list of more than 64 callbacks is refused where it used to be cut short. `execute_tls_callbacks` refuses a stack top that is not 16-byte aligned or cannot hold the entry frame, which used to overflow a subtraction, and a file cut inside the TLS data-directory entry no longer panics the parser. `TlsError` gains four variants for these cases. Twelve unit tests in `crates/loader/src/tls.rs` use original headers and code, and also check the argument registers, the stack pointer at entry and after return, callback order and the instruction budget. Expectations come from Microsoft's public PE Format and x64 calling convention pages; nothing ran on Windows, and independent review is pending.
|
||||
- Fixed the thread's TLS pointer naming the TLS data itself (#76). Compiled code loads the pointer from the thread environment block, indexes it by the module's TLS index to get the address of the data block, and then adds a variable's offset; the loader had mapped the data where the pointer array belongs, so the first eight bytes of the template were used as the block address. `setup_tls` now maps a pointer array at the thread's TLS base and the data block one page above it, and stores the block address in the slot of the index it assigns. `crates/loader/tests/tls_layout.rs` follows that access sequence through guest memory for a template with zero fill, a rebased image and a zero-fill-only directory. The data block of the fixture harness can now be at most 60 KiB, down from 64 KiB, before it would meet the thread environment block. Alignment requests above 4 KiB and more than one module's TLS are not handled. The access sequence follows Microsoft's public PE Format page; nothing ran on Windows, and independent review is pending.
|
||||
- Fixed the MXCSR flags of an unmasked floating-point overflow whose result is exact before the exponent is bounded, such as the largest binary32 value times two (#128). Only the overflow flag is set; the precision flag used to be set as well although nothing was rounded. A masked overflow still sets both flags and delivers infinity or the largest finite value, and an unmasked overflow that is also inexact still sets both. Five Intel SDM cases in `cpu_known_answers.rs` moved from open defect to verified on both engines, with three more for the other rounding modes, and the scalar and conversion sweeps now compare the precision flag in this case as well. Not compared with x86 hardware; awaiting independent review.
|
||||
- Fixed the decoder refusing an instruction whose REX prefix is followed by a legacy prefix (#69). Such a REX is ignored, as the Intel SDM (Vol. 2A, 2.2.1) specifies, so `48 66 01 D8` now runs as `add ax, bx`; it used to stop the guest with an illegal-instruction exit. The ignored byte still counts toward the instruction's length, and a REX that directly precedes the opcode behaves as before. The interpreter, the DBT and the static probe share the decoder. One SDM-derived case in `cpu_known_answers.rs` moved from refused to verified and three were added, for an ignored REX.B, an ignored REX.W before a segment prefix, and a later REX that does apply. Two REX bytes in a row and the address-size prefix stay rejected. Not compared with x86 hardware; awaiting independent review.
|
||||
- Fixed import binding writing some slots before finding an unresolved import, and service calls taking effect before an unreadable return address was noticed. A service that changes a nonvolatile register, including XMM6 to XMM15, now stops the guest (part of #201).
|
||||
- Fixed older import-generator templates that reported success for unimplemented wrappers, used a nonexistent exit reason, and read floating-point arguments from integer registers.
|
||||
- Fixed guest flags in the native DBT (#64, #70). They lived only in host NZCV, so they were lost across helper calls and block boundaries and register ADD, SUB and XOR set none. JB, JAE, JBE and JA used ARM carry polarity, which is inverted for subtraction. Flags are now stored in the guest state.
|
||||
- Fixed the static probe reporting support for forms an engine rejects, including NOP, TEST, most conditional branches and the FF group in the interpreter.
|
||||
- Fixed the native DBT's `SXTW` encoding, which set bit 3 of the source register and was right only for registers that already had it set; the previous test used such a register by chance.
|
||||
- Fixed 32-bit guest stores and loads in the native DBT (MOV 89/8B and C7 /0), which accessed eight bytes: stores overwrote the next four guest bytes and accesses at the end of a mapping faulted. RIP-relative operands of byte moves and extensions, which were read as RBP-relative, and LEA with a segment prefix, which added the segment base, are fixed too.
|
||||
- Fixed an x86 prefix-length test that read an untracked fuzz artifact and so failed on every fresh checkout; its input is now inline.
|
||||
- Fixed agent-queue `apply_actions` crashing on comment-only decisions (claim refusals) by skipping no-op `gh issue edit` calls; accept `summary --now` after the subcommand; grant the audit job `pull-requests: read` so live audits can list open PRs (issue #180).
|
||||
- Fixed `scripts/audit/status.py` and the Python embedded in `scripts/audit/claims.sh` reading and writing tracked files in the process locale encoding instead of UTF-8: under an ASCII or cp1252 locale the status check crashed on `docs/claims.toml` or reported a spurious `xenora-progress.svg` difference. Both scripts now pass `encoding="utf-8"`, as the rest of `scripts/` does, the two write sites also pin `newline="\n"` so a Windows host cannot turn tracked LF files into CRLF when it regenerates them, and CI runs the two checks again under a non-UTF-8 locale so the requirement stays enforced.
|
||||
|
||||
- Generated CRT adapters now report unsupported calls when the required guest ABI or runtime behavior is missing.
|
||||
|
||||
- Win64 service argument decoding reports a guest memory error when a stack argument offset overflows.
|
||||
|
||||
- Fixed `xenora_isa::meta::identify` reading six VOP3 interpolation forms (`v_interp_p1_f32_e64`, `v_interp_p2_f32_e64`, `v_interp_mov_f32_e64`, `v_interp_p1ll_f16`, `v_interp_p1lv_f16`, `v_interp_p2_f16`) as 12 bytes when SRC0 is 255. In these forms SRC0 holds attribute bit-fields, not an operand selector (AMD RDNA 2 ISA guide section 10.4.2; XML operand type `OPR_ATTR`), so SRC0 = 255 no longer adds a literal word. The six corpus probes are now 8 bytes, as LLVM 23.1.6 also decodes them. The six pinned `mismatch` rows in the LLVM corpus check are gone: one now agrees fully, and five are `operand_flagged` (same instruction and length; LLVM flags an operand).
|
||||
- Updated `test_probe_static_analysis_does_not_execute_code`: the SIB store `mov [rsp + 0x20],
|
||||
rbx` at RVA 0x1004 is now genuinely supported by the native DBT (verified by the independent
|
||||
execution test above), so the probe reports no blocker for this program.
|
||||
- Added `test_probe_static_analysis_detects_genuinely_unsupported_instruction` with a new
|
||||
synthetic fixture containing an INT3 at RVA 0x1004, preserving blocker-detection coverage
|
||||
for genuinely unsupported DBT instructions.
|
||||
|
||||
## [X18] - Automated Import Compatibility Generation & Metadata Ingestion
|
||||
|
||||
Guest execution uses original, purpose-built test programs. Commercial Xbox game execution
|
||||
remains unsupported.
|
||||
|
||||
### Added
|
||||
|
||||
- Added `xenora-import-gen` deterministic code generation crate and `xenora imports generate <--pe <exe> | --csv <file>> [--out <dir>]` CLI command. Automatically extracts imported symbols from PE executables or CSV manifests, classifies them against a built-in offline database of documented public Win32/CRT and ISO C specifications without consuming AI tokens or network resources, maps compatible CRT functions to native macOS libc ABI adapters with guest memory bounds checking, generates logged Win32 service stubs, generates deterministic conformance test suites, and produces coverage reports in both Markdown and CSV format.
|
||||
- Added automated metadata ingestion (`ingest_standard_system_headers`) and `xenora imports metadata sync` command capable of parsing real POSIX/C system headers into typed `MetadataCatalog` definitions (188 entries).
|
||||
- Added `xenora imports verify` automated behavioral verification runner checking CRT math, string, and memory bounds invariants across 12 independent behavioral test cases.
|
||||
- Added explicit failure semantics for unsupported stubs returning `ExitReason::IllegalInstruction(0xFE)` rather than fabricated success.
|
||||
- Added public registration helper `ImportRegistry::register_with_status` and runtime integration test verifying generated bindings and stub failure semantics.
|
||||
- Added 8-bit and 16-bit guest memory access helpers (`read_u8`, `write_u8`, `read_u16`, `write_u16`) to `xenora-loader::GuestMemory`.
|
||||
|
||||
- Added guest-facing D3D12-style graphics runtime interfaces (`GraphicsContext`, `GraphicsDevice`, `GraphicsCommandQueue`, `GraphicsCommandAllocator`, `GraphicsCommandList`, `GraphicsResource`) with explicit backend selection (`GraphicsBackendId::MetalNative` vs `GraphicsBackendId::SoftwareReference`). Original PE32+ integration tests verify device creation, generation-checked handle ownership, command recording, barriers, and presentation.
|
||||
- Connected guest execution via ARM64 DBT and IAT dispatch to native Apple Silicon Metal rendering (`test_guest_dbt_graphics_pipeline_metal_render_dual_inputs`), proving that different guest vertex positions and clear colors produce distinct, verified GPU-rendered framebuffers with active Metal validation on Apple M5.
|
||||
- Added explicit test graphics service exports (`xenora_fixture.dll!CreateGraphicsDevice`, `xenora_fixture.dll!SubmitGuestDraw`) cleanly separated from unsupported production Xbox ABI claims.
|
||||
- Added control-flow-aware x86-64 static PE probe using worklist CFG traversal, eliminating false-positive startup blocker reports on unreachable INT3 padding.
|
||||
- Added `xenora imports sync` command with `--check` verification mode for automated, idempotent import compatibility backlog generation.
|
||||
- Added current-process handle and ID queries and a readable priority boost policy for the synthetic guest process. Original PE fixtures verify Win64 arguments, state changes and errors through imported calls.
|
||||
- Static import reports identify canonical bindings, API-set aliases, implemented and partial handlers, existing stubs, and missing services.
|
||||
|
||||
- Added a single startup path for original PE32+ fixtures that maps and rebases the image, binds imports before running thread-local storage callbacks, then enters the guest.
|
||||
- The static PE probe compares ordinary imports with the standard synthetic registry and exports unresolved DLL, symbol or ordinal, and import slot addresses to `missing_imports.csv`.
|
||||
|
||||
- Added synthetic PE32+ runtime support for 64-bit base relocations, thread-local storage setup and callbacks, Windows x64 calling convention arguments, and import binding to a limited service registry. The Xbox-style allocation service maps guest memory. Its free entry point remains a stub.
|
||||
- Extended native ARM64 dynamic binary translation with selected memory addressing, immediate stores, register increments and decrements, and indirect control flow through guest import slots.
|
||||
- Added runtime fixtures for rebasing, ordered callbacks, deterministic timing, guest memory allocation, and mock import dispatch. The GPU gate checks every pixel from a native offscreen draw through a synthetic import.
|
||||
|
||||
- Added a static PE compatibility probe that exports section, relocation, thread-local storage, import and bounded x86-64 entry-point analysis. Synthetic tests cover inspection and report export.
|
||||
- Added native Apple Silicon ARM64 Dynamic Binary Translation (DBT) engine (`DbtEngine`) with basic block decoding, native ARM64 code lowering, and W^X-compliant JIT code cache (`JitMemory`) utilizing macOS `MAP_JIT` and `pthread_jit_write_protect_np`.
|
||||
- Added an ARM64 machine instruction assembler (`Arm64Assembler`) supporting register/immediate arithmetic, logical operations, memory loads/stores, branch/call/ret control flow, and calling convention preservation.
|
||||
- Added synthetic guest graphics service dispatch connecting guest x86-64 execution through native ARM64 translated blocks directly to Xenora's Metal graphics pipeline (`NativeCompute::render_rgba8`), producing and independently checking the first guest-rendered frame.
|
||||
@@ -390,13 +55,6 @@ remains unsupported.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed the intermittent failure of the frame-loop memory-footprint test (#290). Each frame-loop session opened its own Metal command queue. The first command buffer on a queue makes the GPU driver allocate a working set for it (about 45 MiB on an Apple M5 with Metal validation), and the driver frees it asynchronously 10–50 ms after the queue is released, so the process footprint read right after a session ended depended on how far that release had got. Measured immediately after each of 50 destroys, it ranged from 45 to 96 MiB; the unchanged test failed 5 times in 30 runs, with up to 26 MiB of apparent growth. There was no leak: one second after each destroy the footprint was back at the same floor every time. Frame-loop sessions now share one process-wide Metal device and command queue, so the working set is allocated once and kept: the same readings stay within 93–98 MiB across 50 sessions, and the unchanged test passed 30 runs in a row (largest growth 0.31 MiB). The cost is that the process keeps that GPU memory (about 50 MiB with validation, 58 MiB total footprint without) after its first frame loop. A new 50-session test (normal completion, pause and resume, destroy while running) checks the readings stay within 16 MiB; it fails without the fix.
|
||||
- Stop ignoring `fixtures/pe/trusted-runner.exe`. The runner embeds it with `include_bytes!`, so ignoring the file made a fresh checkout fail to compile.
|
||||
- Corrected the ARM64 STP pre-index encoder, which had a hardcoded -32-byte immediate and therefore adjusted the host stack by the wrong amount once the translator frame grew to 48 bytes. The wrong frame silently corrupted the caller's stack and caused SIGSEGV in every native translation test. Emitter encodings are now checked against LLVM's assembler, and a test asserts that each translated block opens and closes the same 48-byte frame.
|
||||
- Translated guest memory faults now stop the block before it commits further architectural effects. A faulting push, call or store leaves guest RSP and registers unchanged, the reported instruction count covers only completed work, and guest RIP identifies the faulting instruction. Previously the block continued after the helper recorded a fault, so later instructions and writes still took effect.
|
||||
- Compute the static PE probe SHA-256 from the full input, including trailing bytes.
|
||||
- Report TLS callbacks that halt or exhaust their execution budget as failures. Reject unsupported 32-bit increment and decrement forms in the native translator.
|
||||
|
||||
- Reject unknown guest experiment arguments with a nonzero exit status.
|
||||
|
||||
- Validate branch targets, buffer bindings, and program termination throughout a shader fixture, including instructions skipped by a resolved branch.
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
# Code of Conduct
|
||||
|
||||
BetterXen welcomes contributors with different backgrounds and experience levels. Discussions should be about the technical work and conducted with respect.
|
||||
Xenora welcomes contributors with different backgrounds and experience levels. Discussions should be about the technical work and conducted with respect.
|
||||
|
||||
## Expected behavior
|
||||
|
||||
@@ -19,4 +19,4 @@ If possible, use an available private contact channel for a repository maintaine
|
||||
|
||||
Maintainers may remove content, limit participation or block accounts when necessary to protect the community. Responses should be proportionate to the behavior and protect the privacy of affected people. Do not retaliate against anyone reporting a concern in good faith.
|
||||
|
||||
This policy applies to repository issues, pull requests, discussions and other spaces officially managed by BetterXen.
|
||||
This policy applies to repository issues, pull requests, discussions and other spaces officially managed by Xenora.
|
||||
+4
-6
@@ -1,12 +1,11 @@
|
||||
# Contributing to BetterXen
|
||||
# Contributing to Xenora
|
||||
|
||||
BetterXen is an experimental Xbox Series X|S recompilation framework for Apple Silicon. Its graphics subsystem, XenoMetal, targets native Metal execution. Contributions should improve verified behavior rather than expand untested claims.
|
||||
Xenora is an experimental Xbox Series X|S recompilation framework for Apple Silicon. Its graphics subsystem, XenoMetal, targets native Metal execution. Contributions should improve verified behavior rather than expand untested claims.
|
||||
|
||||
## Getting started
|
||||
|
||||
- Read `README.md` and, when present, `AGENTS.md`, `docs/interfaces.md`, `docs/status.toml` and the relevant architecture decisions.
|
||||
- Discuss substantial changes in an issue before implementing them; small fixes do not require prior approval.
|
||||
- Claim an issue before working on it by replying on it in plain words, after checking its comments for an existing claim. Never claim over someone else. A claim with no pull request after about one week may be taken over with a reply saying so. Coding agents follow the same rules; see "Claiming work before you start" in `AGENTS.md`.
|
||||
- Use a native ARM64 macOS environment with Rust and the appropriate Xcode/Metal tools. LLVM AMDGPU tools are needed for ISA fixture generation; extra tooling depends on the subsystem.
|
||||
- Keep changes focused and preserve existing public interfaces unless a change is justified and documented.
|
||||
|
||||
@@ -28,11 +27,11 @@ For a performance change, provide reproducible before-and-after results using eq
|
||||
|
||||
## Research and clean-room policy
|
||||
|
||||
Use publicly accessible specifications and authorized materials only. Do not submit leaked SDKs, confidential documentation, firmware, keys, proprietary game binaries or unauthorized shader dumps. Under BetterXen's clean-room policy, anyone who has accessed leaked or confidential Xbox materials must not contribute. Do not post details of restricted material in issues or PRs.
|
||||
Use publicly accessible specifications and authorized materials only. Do not submit leaked SDKs, confidential documentation, firmware, keys, proprietary game binaries or unauthorized shader dumps. Under Xenora's clean-room policy, anyone who has accessed leaked or confidential Xbox materials must not contribute. Do not post details of restricted material in issues or PRs.
|
||||
|
||||
Distinguish desktop RDNA behavior from Xbox-specific behavior. Cite primary sources with exact applicable architectures and record uncertainties using the project's evidence classification when available. Tests on Apple GPUs do not establish verification on Xbox hardware.
|
||||
|
||||
BetterXen implements its own Rust guest runtime, decoder, typed IR, shader
|
||||
Xenora implements its own Rust guest runtime, decoder, typed IR, shader
|
||||
compiler and native Metal backend from public technical specifications
|
||||
and independently derived tests. Contributions must not copy, port or
|
||||
adapt code, decoder tables, internal metadata or implementation
|
||||
@@ -44,7 +43,6 @@ Before incorporating third-party code, verify per-file license compatibility wit
|
||||
## Pull requests
|
||||
|
||||
- Branch from the current main branch, keep commits focused, and link relevant issues.
|
||||
- Fill in every section of the pull request template, keep `Closes #<number>` (or write `No linked issue: <reason>`), and tick the claimed-first and DCO checkboxes. The *PR template* check fails until the description does, and runs again each time you edit it.
|
||||
- Include a clear explanation, tests and any documentation/status updates. Separate unverified work from supported behavior.
|
||||
- Disclose material AI assistance and personally review generated changes. AI output is not an authoritative source, test oracle or substitute for independent review.
|
||||
- Never include secrets, personal paths, credentials or private data in patches or logs.
|
||||
|
||||
Generated
+1
-97
@@ -8,50 +8,6 @@ version = "2.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
|
||||
|
||||
[[package]]
|
||||
name = "block-buffer"
|
||||
version = "0.10.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
|
||||
dependencies = [
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cfg-if"
|
||||
version = "1.0.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
|
||||
|
||||
[[package]]
|
||||
name = "cpufeatures"
|
||||
version = "0.2.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crypto-common"
|
||||
version = "0.1.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
|
||||
dependencies = [
|
||||
"generic-array",
|
||||
"typenum",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "digest"
|
||||
version = "0.10.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
|
||||
dependencies = [
|
||||
"block-buffer",
|
||||
"crypto-common",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dispatch2"
|
||||
version = "0.3.1"
|
||||
@@ -62,16 +18,6 @@ dependencies = [
|
||||
"objc2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "generic-array"
|
||||
version = "0.14.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
|
||||
dependencies = [
|
||||
"typenum",
|
||||
"version_check",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.191"
|
||||
@@ -127,35 +73,9 @@ dependencies = [
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sha2"
|
||||
version = "0.10.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures",
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "typenum"
|
||||
version = "1.20.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
|
||||
|
||||
[[package]]
|
||||
name = "version_check"
|
||||
version = "0.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
|
||||
|
||||
[[package]]
|
||||
name = "betterxen"
|
||||
name = "xenora"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"xenora-decoder",
|
||||
"xenora-import-gen",
|
||||
"xenora-isa",
|
||||
"xenora-loader",
|
||||
"xenora-metal",
|
||||
"xenora-ref",
|
||||
@@ -166,7 +86,6 @@ dependencies = [
|
||||
name = "xenora-benchmarks"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"xenora-isa",
|
||||
"xenora-metal",
|
||||
"xenora-ref",
|
||||
"xenora-shader",
|
||||
@@ -180,19 +99,6 @@ dependencies = [
|
||||
"xenora-ref",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "xenora-ffi"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"xenora-loader",
|
||||
"xenora-metal",
|
||||
"xenora-shader",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "xenora-import-gen"
|
||||
version = "0.1.0"
|
||||
|
||||
[[package]]
|
||||
name = "xenora-isa"
|
||||
version = "0.1.0"
|
||||
@@ -202,10 +108,8 @@ name = "xenora-loader"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"sha2",
|
||||
"xenora-metal",
|
||||
"xenora-shader",
|
||||
"xenora-texture",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
@@ -10,10 +10,3 @@ rust-version = "1.100"
|
||||
|
||||
[workspace.lints.rust]
|
||||
unsafe_op_in_unsafe_fn = "deny"
|
||||
|
||||
# Whole-program optimization for release and bench builds (#116). On an Apple M5 the
|
||||
# interpreter ran about 6 % and cold DBT about 9 % faster in `dbt_bench`, at the cost of
|
||||
# slower release builds. Debug and test builds are unaffected.
|
||||
[profile.release]
|
||||
lto = "fat"
|
||||
codegen-units = 1
|
||||
@@ -1,54 +1,64 @@
|
||||
# BetterXen
|
||||
|
||||
BetterXen is a community-maintained continuation. Original Git history, licenses and contributor attribution are retained. See the [project history and migration notes](docs/migration.md) for source attribution and imported issue and pull-request records.
|
||||
# Xenora
|
||||
|
||||
**Experimental Xbox Series X|S emulation research for Apple Silicon Macs.**
|
||||
|
||||
BetterXen 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.
|
||||
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.
|
||||
|
||||
**No Wine. No CrossOver. No Rosetta. No Vulkan runtime.**
|
||||
|
||||
BetterXen 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).
|
||||
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.
|
||||
|
||||
> [!CAUTION]
|
||||
> **BetterXen strictly opposes piracy.** BetterXen is an independent, clean-room, general-purpose emulation research project that neither distributes copyrighted game files nor supports unauthorized content, DRM circumvention, or leaked materials. Use only legally obtained software. BetterXen is not affiliated with Microsoft or any other publisher or platform holder.
|
||||
|
||||
[](https://github.com/MacosPorters/betterxen/actions/workflows/ci.yml)
|
||||
[](https://github.com/ranveersoni98/Xenora/actions/workflows/ci.yml)
|
||||
|
||||
---
|
||||
|
||||
## What works today?
|
||||
|
||||
BetterXen has progressed from executing individual x86-64 instructions to running original PE32+ guest programs that interact with translated GPU workloads on Apple Silicon.
|
||||
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 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.
|
||||
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.
|
||||
|
||||
### Development phases
|
||||
### Development milestones
|
||||
|
||||
The active plan follows demonstrable native macOS workloads. Every phase has
|
||||
completion checks, dependencies and contributor issues in the
|
||||
[full development plan](docs/development-phases.md).
|
||||
| Milestone | Implementation | Status |
|
||||
| --- | --- | --- |
|
||||
| X1 — Guest CPU | Bounded x86-64 instruction execution on ARM64 macOS | Verified |
|
||||
| X2 — Executable loading | Loading original fixed-base PE32+ test executables | Verified |
|
||||
| X3 — GPU compute | Guest-submitted Metal compute workloads and readback | Verified |
|
||||
| X4 — Metal rendering | Guest-driven offscreen rendering using authored Metal shaders | Verified |
|
||||
| X5 — Guest execution expansion | Additional bounded CPU execution and fixture coverage | Implemented |
|
||||
| X6 — Guest control flow | Nested calls, returns, checked memory and synthetic PE execution | Verified |
|
||||
| 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 |
|
||||
| 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 | Introduce an ARM64 dynamic recompiler (JIT) for supported x86-64 instructions, with interpreter fallback | Planned |
|
||||
| X15 — Executable compatibility | PE relocations, TLS, DLL loading, exception handling, imports and executable initialization | Planned |
|
||||
| X16 — Guest memory and threading | Virtual memory mapping, thread scheduling, synchronization primitives and atomic operations | Planned |
|
||||
| X17 — System services | Implement a tested subset of Xbox-compatible runtime APIs, memory services, filesystem access and application lifecycle | Planned |
|
||||
| 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 |
|
||||
| X21 — Application compatibility | Execute increasingly complex independently authored applications through the complete guest CPU and GPU pipeline | Planned |
|
||||
| X22 — First application boot | Establish a reproducible startup and error-reporting path for supported game-like applications | Planned |
|
||||
| X23 — Initial game compatibility | Investigate startup and execution of legally supported game software, identifying missing runtime and graphics behavior | Long-term goal |
|
||||
| X24 — Gameplay and performance | Expand rendering correctness, input, audio, memory management, shader caching and execution performance | Long-term goal |
|
||||
| X25 — Running games | Achieve reproducible, stable execution of compatible games on native Apple Silicon macOS using Metal | Long-term goal |
|
||||
|
||||
| Phase | Result to demonstrate |
|
||||
| --- | --- |
|
||||
| 1 — Compiled guest boot | Reproduce and independently accept the existing original C execution path on native ARM64. |
|
||||
| 2 — Modular guest runtime | Run an original executable with companion libraries, workers, checked waits and lifecycle cleanup. |
|
||||
| 3 — Guest-controlled Metal scene | Reach translated textured rendering through compiled guest calls, with checked resource lifetime and pixels. |
|
||||
| 4 — Interactive application | Combine guest execution, rendering, input, audio, saves and session controls in one original application. |
|
||||
| 5 — Compatibility corpus | Expand CPU/runtime/shader behavior using varied original workloads and independently derived regressions. |
|
||||
| 6 — Sustained native execution | Verify bounded long runs and measured performance on the Apple Silicon hosts actually tested. |
|
||||
| 7 — Xbox compatibility experiments | Resolve public console contracts and demonstrate each separately admitted execution stage before claiming support. |
|
||||
|
||||
These phases replace the previous roadmap. They are targets, not completed
|
||||
acceptance claims or a game-release timeline. Console-contract research and
|
||||
bounded subsystem work can proceed in parallel. Historical fixture identifiers
|
||||
such as X9 remain labels for their original test/evidence records.
|
||||
**Roadmap note:** X10–X25 are proposed engineering milestones, not completed implementations or a guaranteed sequence. Actual priorities will change as compatibility testing reveals new blockers. Successfully completing one milestone does not guarantee that a particular game will run.
|
||||
|
||||
All existing verification refers to independently authored synthetic programs and shaders. Commercial-game compatibility remains unverified.
|
||||
|
||||
See the [X9 acceptance matrix](docs/testing/x9-acceptance.md) for specific tests, results and unsupported behavior.
|
||||
|
||||
## Native graphics translation
|
||||
|
||||
BetterXen's graphics pipeline translates a supported subset of AMD RDNA 2 instructions into Metal Shading Language.
|
||||
Xenora's graphics pipeline translates a supported subset of AMD RDNA 2 instructions into Metal Shading Language.
|
||||
|
||||
The translation process is:
|
||||
|
||||
@@ -87,35 +97,14 @@ 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 newer passes below are separate Metal-validated campaigns, also with Metal API and shader 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.
|
||||
|
||||
Representative checks include:
|
||||
|
||||
@@ -126,9 +115,6 @@ 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.
|
||||
|
||||
@@ -155,26 +141,26 @@ The resource system remains experimental. Native GPU work already in flight duri
|
||||
|
||||
## Texture support
|
||||
|
||||
BetterXen includes original texture upload, readback and block-compression paths.
|
||||
Xenora includes an original BC1 texture-processing path.
|
||||
|
||||
Implemented and tested functionality includes:
|
||||
|
||||
- Validated mip levels and array layers.
|
||||
- Pitched texture uploads.
|
||||
- Block-compressed texture handling, including BC4/BC5 upload and readback and a CPU BC7 decoder for the eight modes.
|
||||
- Block-compressed texture handling.
|
||||
- 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 authored Metal kernels. It should not be confused with executing arbitrary RDNA2 texture-fetch instructions.
|
||||
The existing texture readback path uses an authored Metal kernel. 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.
|
||||
|
||||
## Architecture
|
||||
|
||||
BetterXen is organized around three connected subsystems: guest execution, shader translation and native GPU execution.
|
||||
Xenora is organized around three connected subsystems: guest execution, shader translation and native GPU execution.
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
@@ -221,9 +207,7 @@ flowchart TD
|
||||
end
|
||||
```
|
||||
|
||||
BetterXen'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.
|
||||
Xenora's host execution environment is native ARM64. The guest architecture being interpreted is x86-64.
|
||||
|
||||
The project does not currently provide a general-purpose x86-64 dynamic recompiler or a complete Xbox operating-system implementation.
|
||||
|
||||
@@ -233,7 +217,7 @@ See [Interface Contracts](docs/interfaces.md) for the documented execution and r
|
||||
|
||||
## Current limitations
|
||||
|
||||
BetterXen is an engineering research project, not a working commercial-game emulator.
|
||||
Xenora is an engineering research project, not a working commercial-game emulator.
|
||||
|
||||
The following remain unsupported or incomplete:
|
||||
|
||||
@@ -243,18 +227,18 @@ 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 and broader resource binding |
|
||||
| Textures | Authentic Xbox memory layouts and translated sampling |
|
||||
| Graphics | Translated texture sampling, broader resource binding, synchronization and general draw workloads |
|
||||
| Textures | Authentic Xbox memory layouts and broader compressed-format support |
|
||||
| Performance | Production-scale workloads, CPU/GPU profiling and optimized execution |
|
||||
| Game compatibility | No demonstrated execution of commercial Xbox titles |
|
||||
|
||||
BetterXen's current shader fixtures target a bounded subset of desktop gfx1030 behavior. This is not equivalent to complete Xbox Series GPU compatibility.
|
||||
Xenora's current shader fixtures target a bounded subset of desktop gfx1030 behavior. This is not equivalent to complete Xbox Series GPU compatibility.
|
||||
|
||||
Progress is measured by reproducible tests rather than estimated game compatibility percentages.
|
||||
|
||||
---
|
||||
|
||||
## Building BetterXen
|
||||
## Building Xenora
|
||||
|
||||
### Requirements
|
||||
|
||||
@@ -269,15 +253,15 @@ The recorded Apple M5 environment uses Rust 1.100.0 and Xcode 27.2.
|
||||
### Clone
|
||||
|
||||
```sh
|
||||
git clone https://github.com/MacosPorters/betterxen.git
|
||||
cd betterxen
|
||||
git clone https://github.com/ranveersoni98/Xenora.git
|
||||
cd Xenora
|
||||
```
|
||||
|
||||
### Build
|
||||
|
||||
```sh
|
||||
scripts/bootstrap.sh
|
||||
cargo build --locked -p betterxen
|
||||
cargo build --locked -p xenora
|
||||
```
|
||||
|
||||
### Run core tests
|
||||
@@ -288,10 +272,6 @@ 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.
|
||||
@@ -300,7 +280,7 @@ These require a Metal-capable Apple Silicon Mac.
|
||||
scripts/test-gpu.sh
|
||||
```
|
||||
|
||||
The native test suite enables Metal API and shader validation and tests the supported compute, rendering and texture paths. The full semantic-review batch defaults to a 300-second timeout; set `XENORA_SEMANTIC_TIMEOUT` to raise or lower it for a slower or faster host. On macOS, the script uses a Python 3 fallback when GNU `timeout` is unavailable.
|
||||
The native test suite enables Metal API and shader validation and tests the supported compute, rendering and texture paths.
|
||||
|
||||
### Verify guest execution
|
||||
|
||||
@@ -317,6 +297,8 @@ Run the original guest resource integration tests:
|
||||
tests/compat_fixtures/verify-resources.sh
|
||||
```
|
||||
|
||||
The X9 verification script builds synthetic PE fixtures, executes guest resource and rendering workloads, compares reported output and exercises negative cases.
|
||||
|
||||
Additional checks:
|
||||
|
||||
```sh
|
||||
@@ -340,22 +322,73 @@ Testing distinguishes between:
|
||||
|
||||
Compiling a shader is not equivalent to proving its GPU output is correct.
|
||||
|
||||
### Where the work is heading
|
||||
|
||||
See the [development phases](docs/development-phases.md) for the current work order, 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).
|
||||
The [X9 acceptance report](docs/testing/x9-acceptance.md) documents verified outcomes and unresolved work.
|
||||
|
||||
---
|
||||
|
||||
## Roadmap
|
||||
|
||||
Future development will focus on expanding the complete execution path instead of treating synthetic demonstration milestones as evidence of commercial-game compatibility.
|
||||
|
||||
### Near-term priorities
|
||||
|
||||
1. **Graphics compatibility:** Extend shader translation, texture sampling, resource bindings, multi-draw rendering and synchronization.
|
||||
2. **Guest execution:** Improve the PE loader, CPU instruction coverage, runtime services and execution correctness.
|
||||
3. **Performance:** Investigate efficient ARM64 guest execution, graphics pipeline caching, profiling and GPU resource lifetime management.
|
||||
|
||||
Longer-term research includes authentic Xbox application interfaces and significantly broader GPU behavior.
|
||||
|
||||
MetalFX upscaling and other presentation optimizations may become useful once substantial workloads render correctly. They are not substitutes for correct guest execution or shader translation.
|
||||
|
||||
There is no announced commercial-game support date.
|
||||
|
||||
---
|
||||
|
||||
## Contributors wanted
|
||||
|
||||
**Xenora is looking for developers interested in native Apple Silicon systems programming, graphics translation and emulation research.**
|
||||
|
||||
This is an ambitious project, and there's a great deal of work that would benefit from experienced contributors and independent reviewers.
|
||||
|
||||
Particularly useful areas include:
|
||||
|
||||
| Area | Potential contributions |
|
||||
| --- | --- |
|
||||
| Apple Metal | Rendering, resource management, synchronization, GPU debugging and profiling |
|
||||
| AMD RDNA2 | ISA decoding, wave semantics, shader execution and correctness tests |
|
||||
| Compiler engineering | Shader intermediate representations, lowering, optimization and code generation |
|
||||
| ARM64 / x86-64 | Guest CPU execution, instruction semantics, memory models and future JIT research |
|
||||
| Rust | Runtime architecture, concurrency, safety, tests and tooling |
|
||||
| macOS | Apple Silicon compatibility, native debugging and hardware validation |
|
||||
| Testing | Independent reference implementations, fuzzing, regression tests and reproducible GPU fixtures |
|
||||
|
||||
You don't need to be an expert in every subsystem.
|
||||
|
||||
Code review, small targeted fixes, independent test cases and technical criticism are all valuable contributions.
|
||||
|
||||
### Getting involved
|
||||
|
||||
1. Read [CONTRIBUTING.md](CONTRIBUTING.md) and the relevant architecture documentation.
|
||||
2. Review the [current acceptance results](docs/testing/x9-acceptance.md).
|
||||
3. Open a [GitHub issue](https://github.com/ranveersoni98/Xenora/issues) to discuss a feature, bug, or research question.
|
||||
4. Submit focused pull requests with reproducible tests and documented limitations.
|
||||
|
||||
Contributions must follow the project's original-implementation and clean-room research policies. Do not submit proprietary game files, leaked SDK materials, console keys or unauthorized shader dumps.
|
||||
|
||||
AI-assisted development has been used in Xenora. All contributions, including AI-assisted code, are expected to undergo human review and independent verification.
|
||||
|
||||
**The goal is to build a trustworthy native Apple Silicon compatibility framework, one verifiable subsystem at a time.**
|
||||
|
||||
---
|
||||
|
||||
## License
|
||||
|
||||
BetterXen is licensed under the [GNU General Public License v3 or later](LICENSE).
|
||||
Xenora is licensed under the [GNU General Public License v3 or later](LICENSE).
|
||||
|
||||
See [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) for third-party attribution and [docs/legal.md](docs/legal.md) for the project's research and legal boundaries.
|
||||
|
||||
BetterXen is an independent open-source project and is not affiliated with Microsoft, Xbox, Rockstar Games or Apple.
|
||||
Xenora is an independent open-source project and is not affiliated with Microsoft, Xbox, Rockstar Games or Apple.
|
||||
|
||||
---
|
||||
|
||||
**Built for Apple Silicon. Powered by Rust and Metal. Open to contributors.**
|
||||
+2
-2
@@ -2,13 +2,13 @@
|
||||
|
||||
## Scope
|
||||
|
||||
BetterXen is experimental and is not currently represented as a security-hardened runtime. Treat shaders, binary containers, caches and native library inputs as untrusted. Do not use it to process untrusted content in a sensitive environment.
|
||||
Xenora is experimental and is not currently represented as a security-hardened runtime. Treat shaders, binary containers, caches and native library inputs as untrusted. Do not use it to process untrusted content in a sensitive environment.
|
||||
|
||||
The project does not promise a fixed security support window at this stage. Report issues against a specific revision, preferably reproduced on current `main` where safe.
|
||||
|
||||
## Reporting vulnerabilities
|
||||
|
||||
Use [GitHub private vulnerability reporting](https://github.com/MacosPorters/betterxen/security/advisories/new), if enabled. If it is unavailable, request a private reporting channel without disclosing exploit details publicly. Do not open a public issue containing sensitive vulnerability details, credentials, or private data.
|
||||
Use [GitHub private vulnerability reporting](https://github.com/ranveersoni98/Xenora/security/advisories/new), if enabled. If it is unavailable, request a private reporting channel without disclosing exploit details publicly. Do not open a public issue containing sensitive vulnerability details, credentials, or private data.
|
||||
|
||||
Include the affected commit, environment, affected component, expected and actual behavior, impact and a minimal, authorized reproduction. Use synthetic inputs wherever possible. Do not attach protected content, leaked SDK material or proprietary shaders.
|
||||
|
||||
|
||||
+3
-3
@@ -1,9 +1,9 @@
|
||||
# Getting help
|
||||
|
||||
Start with the [README](README.md) and the relevant documentation in the repository, if available. BetterXen is an experimental research project, not a commercial game compatibility service.
|
||||
Start with the [README](README.md) and the relevant documentation in the repository, if available. Xenora is an experimental research project, not a commercial game compatibility service.
|
||||
|
||||
- Use [GitHub Issues](https://github.com/MacosPorters/betterxen/issues) for reproducible bugs, feature proposals, research findings and hardware verification reports.
|
||||
- Use [GitHub Discussions](https://github.com/MacosPorters/betterxen/discussions) for general questions if Discussions is enabled. Otherwise, search existing issues before filing a relevant question.
|
||||
- Use [GitHub Issues](https://github.com/ranveersoni98/Xenora/issues) for reproducible bugs, feature proposals, research findings and hardware verification reports.
|
||||
- Use [GitHub Discussions](https://github.com/ranveersoni98/Xenora/discussions) for general questions if Discussions is enabled. Otherwise, search existing issues before filing a relevant question.
|
||||
- Follow [SECURITY.md](SECURITY.md) for security-sensitive reports.
|
||||
|
||||
Include the exact revision, host architecture, macOS version, relevant tool versions, steps to reproduce and sanitized output. Do not share personal paths, private account information, protected game assets, credentials or confidential material. If the reported feature is not yet implemented, identify it as a request rather than a regression.
|
||||
@@ -1,13 +0,0 @@
|
||||
// swift-tools-version: 6.0
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Build with scripts/build-app.sh, which builds the Rust static library first.
|
||||
import PackageDescription
|
||||
|
||||
let package = Package(
|
||||
name: "BetterXen",
|
||||
platforms: [.macOS(.v14)],
|
||||
targets: [
|
||||
.systemLibrary(name: "CXenora", path: "Sources/CXenora"),
|
||||
.executableTarget(name: "BetterXen", dependencies: ["CXenora"], path: "Sources/Xenora"),
|
||||
]
|
||||
)
|
||||
@@ -1,5 +0,0 @@
|
||||
module CXenora [system] {
|
||||
header "../../../crates/ffi/include/xenora.h"
|
||||
link "xenora_ffi"
|
||||
export *
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import AVFoundation
|
||||
import Foundation
|
||||
|
||||
struct AudioMixMeasurement {
|
||||
let frames: Int
|
||||
let mean: Double
|
||||
let toneAmplitude: Double
|
||||
}
|
||||
|
||||
enum AudioMixFixtureError: Error {
|
||||
case bufferAllocation
|
||||
case renderFailure(AVAudioEngineManualRenderingStatus)
|
||||
case shortRender
|
||||
}
|
||||
|
||||
func measureAudioMixFixture() throws -> AudioMixMeasurement {
|
||||
let outputRate = 48_000.0
|
||||
let toneRate = 44_100.0
|
||||
let toneFrequency = 1_000.0
|
||||
let blockSize: AVAudioFrameCount = 480
|
||||
let totalFrames = 4_800
|
||||
guard let outputFormat = AVAudioFormat(standardFormatWithSampleRate: outputRate, channels: 1),
|
||||
let toneFormat = AVAudioFormat(standardFormatWithSampleRate: toneRate, channels: 1),
|
||||
let constant = AVAudioPCMBuffer(pcmFormat: outputFormat, frameCapacity: 4_800),
|
||||
let tone = AVAudioPCMBuffer(pcmFormat: toneFormat, frameCapacity: 4_410),
|
||||
let output = AVAudioPCMBuffer(pcmFormat: outputFormat, frameCapacity: blockSize),
|
||||
let constantSamples = constant.floatChannelData?[0],
|
||||
let toneSamples = tone.floatChannelData?[0],
|
||||
let outputSamples = output.floatChannelData?[0] else {
|
||||
throw AudioMixFixtureError.bufferAllocation
|
||||
}
|
||||
constant.frameLength = constant.frameCapacity
|
||||
tone.frameLength = tone.frameCapacity
|
||||
for index in 0..<Int(constant.frameLength) {
|
||||
constantSamples[index] = 0.125
|
||||
}
|
||||
for index in 0..<Int(tone.frameLength) {
|
||||
toneSamples[index] = Float(0.25 * sin(2 * .pi * toneFrequency * Double(index) / toneRate))
|
||||
}
|
||||
|
||||
let engine = AVAudioEngine()
|
||||
let constantPlayer = AVAudioPlayerNode()
|
||||
let tonePlayer = AVAudioPlayerNode()
|
||||
engine.attach(constantPlayer)
|
||||
engine.attach(tonePlayer)
|
||||
engine.connect(constantPlayer, to: engine.mainMixerNode, format: outputFormat)
|
||||
engine.connect(tonePlayer, to: engine.mainMixerNode, format: toneFormat)
|
||||
try engine.enableManualRenderingMode(.offline, format: outputFormat, maximumFrameCount: blockSize)
|
||||
defer {
|
||||
constantPlayer.stop()
|
||||
tonePlayer.stop()
|
||||
engine.stop()
|
||||
engine.disableManualRenderingMode()
|
||||
}
|
||||
try engine.start()
|
||||
constantPlayer.scheduleBuffer(constant)
|
||||
tonePlayer.scheduleBuffer(tone)
|
||||
constantPlayer.play()
|
||||
tonePlayer.play()
|
||||
|
||||
var mean = 0.0
|
||||
var sine = 0.0
|
||||
var cosine = 0.0
|
||||
var measured = 0
|
||||
for first in stride(from: 0, to: totalFrames, by: Int(blockSize)) {
|
||||
let status = try engine.renderOffline(blockSize, to: output)
|
||||
guard status == .success else { throw AudioMixFixtureError.renderFailure(status) }
|
||||
guard output.frameLength == blockSize else { throw AudioMixFixtureError.shortRender }
|
||||
// Exclude the leading and trailing conversion transients.
|
||||
if first == 0 || first == totalFrames - Int(blockSize) { continue }
|
||||
for offset in 0..<Int(blockSize) {
|
||||
let sample = Double(outputSamples[offset])
|
||||
let phase = 2 * Double.pi * toneFrequency * Double(first + offset) / outputRate
|
||||
mean += sample
|
||||
sine += sample * sin(phase)
|
||||
cosine += sample * cos(phase)
|
||||
measured += 1
|
||||
}
|
||||
}
|
||||
let count = Double(measured)
|
||||
return AudioMixMeasurement(frames: totalFrames, mean: mean / count, toneAmplitude: 2 * hypot(sine, cosine) / count)
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import CXenora
|
||||
import GameController
|
||||
|
||||
struct ControllerSnapshot: Equatable {
|
||||
let buttons: UInt32
|
||||
let x: Int16
|
||||
let y: Int16
|
||||
let leftTrigger: Float
|
||||
let rightTrigger: Float
|
||||
|
||||
init(buttons: UInt32, x: Float, y: Float, leftTrigger: Float, rightTrigger: Float) {
|
||||
self.buttons = buttons
|
||||
self.x = Self.axis(x)
|
||||
self.y = Self.axis(y)
|
||||
self.leftTrigger = Self.trigger(leftTrigger)
|
||||
self.rightTrigger = Self.trigger(rightTrigger)
|
||||
}
|
||||
|
||||
private static func axis(_ value: Float) -> Int16 {
|
||||
guard value.isFinite else { return 0 }
|
||||
let deadZone: Float = 0.15
|
||||
let magnitude = max(0, min(1, abs(value)) - deadZone) / (1 - deadZone)
|
||||
return Int16((magnitude * (value < 0 ? -32767 : 32767)).rounded())
|
||||
}
|
||||
|
||||
private static func trigger(_ value: Float) -> Float {
|
||||
value.isFinite ? min(1, max(0, value)) : 0
|
||||
}
|
||||
}
|
||||
|
||||
struct DetectedController: Equatable {
|
||||
let identity: ObjectIdentifier
|
||||
let name: String
|
||||
let supportsHaptics: Bool
|
||||
let snapshot: ControllerSnapshot
|
||||
}
|
||||
|
||||
@MainActor
|
||||
func pollGameController() -> DetectedController? {
|
||||
let controller = GCController.current.flatMap { $0.extendedGamepad == nil ? nil : $0 }
|
||||
?? GCController.controllers().first { $0.extendedGamepad != nil }
|
||||
guard let controller, let pad = controller.capture().extendedGamepad else { return nil }
|
||||
var buttons: UInt32 = 0
|
||||
if pad.dpad.right.isPressed { buttons |= UInt32(XENORA_INPUT_RIGHT) }
|
||||
if pad.dpad.left.isPressed { buttons |= UInt32(XENORA_INPUT_LEFT) }
|
||||
if pad.dpad.up.isPressed { buttons |= UInt32(XENORA_INPUT_UP) }
|
||||
if pad.dpad.down.isPressed { buttons |= UInt32(XENORA_INPUT_DOWN) }
|
||||
if pad.buttonA.isPressed { buttons |= UInt32(XENORA_INPUT_ACTION_A) }
|
||||
if pad.buttonB.isPressed { buttons |= UInt32(XENORA_INPUT_ACTION_B) }
|
||||
return DetectedController(
|
||||
identity: ObjectIdentifier(controller),
|
||||
name: controller.vendorName ?? controller.productCategory,
|
||||
supportsHaptics: controller.haptics != nil,
|
||||
snapshot: ControllerSnapshot(
|
||||
buttons: buttons, x: pad.leftThumbstick.xAxis.value, y: pad.leftThumbstick.yAxis.value,
|
||||
leftTrigger: pad.leftTrigger.value, rightTrigger: pad.rightTrigger.value
|
||||
)
|
||||
)
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -17,10 +17,3 @@ path = "src/main.rs"
|
||||
xenora-shader = { path = "../crates/shader" }
|
||||
xenora-ref = { path = "../crates/ref" }
|
||||
xenora-metal = { path = "../crates/metal" }
|
||||
|
||||
[dev-dependencies]
|
||||
xenora-isa = { path = "../crates/isa" }
|
||||
|
||||
[[bench]]
|
||||
name = "gfx1030_identify"
|
||||
harness = false
|
||||
@@ -1,16 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Original gfx1030 Wave32 instruction stream for metadata identification.
|
||||
s_mov_b32 s12, 0x89abcdef
|
||||
v_add_f32_e32 v4, v5, v9
|
||||
s_cmp_lt_u32 s12, s13
|
||||
ds_read_b32 v8, v2 offset:12
|
||||
v_mov_b32_dpp v9, v6 quad_perm:[2,3,0,1] row_mask:0xf bank_mask:0xf
|
||||
s_add_u32 s16, s17, s18
|
||||
buffer_store_dword v7, off, s[4:7], 0
|
||||
v_fma_f32 v5, v8, v10, 0x3f800003
|
||||
s_movk_i32 s19, 0x2345
|
||||
global_load_dword v3, v[10:11], off
|
||||
v_cmp_lt_u32_e32 vcc_lo, v3, v7
|
||||
s_load_dword s20, s[22:23], 0x20
|
||||
v_pk_add_f16 v3, v4, v6
|
||||
s_waitcnt vmcnt(0)
|
||||
@@ -1,143 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! CPU-only gfx1030 metadata benchmark.
|
||||
//!
|
||||
//! Run `cargo bench --locked -p xenora-benchmarks --bench gfx1030_identify`
|
||||
//! from the repository root. Repeat the command to collect independent
|
||||
//! first-pass samples. The first pass is the first identification in a fresh
|
||||
//! process with the input already in memory. It does not measure process
|
||||
//! startup or guarantee cold hardware caches. Repeated passes use the same
|
||||
//! stream after the untimed correctness check.
|
||||
//!
|
||||
//! To verify the fixture bytes and instruction lengths independently, run:
|
||||
//! ```sh
|
||||
//! llvm-mc -triple=amdgcn-amd-amdhsa -mcpu=gfx1030 -mattr=+wavefrontsize32 \
|
||||
//! -show-encoding benchmarks/benches/fixtures/gfx1030_mixed.s
|
||||
//! ```
|
||||
|
||||
use std::hint::black_box;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use xenora_isa::meta::{EncodingFamily, Identified, identify};
|
||||
|
||||
const COPIES: usize = 4096;
|
||||
const WARM_PASSES: usize = 9;
|
||||
|
||||
// Encodings and lengths come from llvm-mc, one row per instruction in
|
||||
// fixtures/gfx1030_mixed.s. Each word is stored in little-endian order.
|
||||
const FIXTURE: &[(&str, EncodingFamily, &[u32])] = {
|
||||
use EncodingFamily::*;
|
||||
&[
|
||||
("S_MOV_B32", Sop1, &[0xbe8c03ff, 0x89abcdef]),
|
||||
("V_ADD_F32", Vop2, &[0x06081305]),
|
||||
("S_CMP_LT_U32", Sopc, &[0xbf0a0d0c]),
|
||||
("DS_READ_B32", Ds, &[0xd8d8000c, 0x08000002]),
|
||||
("V_MOV_B32", Vop1, &[0x7e1202fa, 0xff004e06]),
|
||||
("S_ADD_U32", Sop2, &[0x80101211]),
|
||||
("BUFFER_STORE_DWORD", Mubuf, &[0xe0700000, 0x80010700]),
|
||||
("V_FMA_F32", Vop3, &[0xd54b0005, 0x03fe1508, 0x3f800003]),
|
||||
("S_MOVK_I32", Sopk, &[0xb0132345]),
|
||||
("GLOBAL_LOAD_DWORD", Global, &[0xdc308000, 0x037d000a]),
|
||||
("V_CMP_LT_U32", Vopc, &[0x7d820f03]),
|
||||
("S_LOAD_DWORD", Smem, &[0xf400050b, 0xfa000020]),
|
||||
("V_PK_ADD_F16", Vop3p, &[0xcc0f4003, 0x1a020d04]),
|
||||
("S_WAITCNT", Sopp, &[0xbf8c3f70]),
|
||||
]
|
||||
};
|
||||
|
||||
fn walk(stream: &[u8], mut observe: impl FnMut(usize, Identified)) -> usize {
|
||||
let mut offset = 0;
|
||||
let mut count = 0;
|
||||
while offset < stream.len() {
|
||||
let identified = identify(&stream[offset..])
|
||||
.unwrap_or_else(|error| panic!("identification failed at byte {offset}: {error}"));
|
||||
observe(offset, identified);
|
||||
offset += identified.len;
|
||||
count += 1;
|
||||
}
|
||||
count
|
||||
}
|
||||
|
||||
fn verify(stream: &[u8]) {
|
||||
let mut expected_offset = 0;
|
||||
let mut expected = FIXTURE.iter().cycle();
|
||||
let count = walk(stream, |offset, identified| {
|
||||
let &(name, family, words) = expected.next().expect("fixture is nonempty");
|
||||
let len = std::mem::size_of_val(words);
|
||||
assert_eq!(offset, expected_offset, "byte boundary for {name}");
|
||||
assert_eq!(identified.len, len, "length of {name} at byte {offset}");
|
||||
assert_eq!(identified.form.name, name, "mnemonic at byte {offset}");
|
||||
assert_eq!(identified.form.family, family, "family at byte {offset}");
|
||||
expected_offset += len;
|
||||
});
|
||||
assert_eq!(expected_offset, stream.len());
|
||||
assert_eq!(count, COPIES * FIXTURE.len());
|
||||
}
|
||||
|
||||
fn measure(stream: &[u8]) -> Duration {
|
||||
let start = Instant::now();
|
||||
let count = walk(black_box(stream), |_, identified| {
|
||||
black_box(identified);
|
||||
});
|
||||
let elapsed = start.elapsed();
|
||||
assert_eq!(count, COPIES * FIXTURE.len());
|
||||
elapsed
|
||||
}
|
||||
|
||||
fn report(label: &str, elapsed: Duration, byte_count: usize) {
|
||||
let seconds = elapsed.as_secs_f64();
|
||||
let count = (COPIES * FIXTURE.len()) as f64;
|
||||
println!(
|
||||
"{label}: {:.3} ms, {:.2} ns/instruction, {:.2} MiB/s",
|
||||
seconds * 1e3,
|
||||
seconds * 1e9 / count,
|
||||
byte_count as f64 / (1024.0 * 1024.0) / seconds
|
||||
);
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let block: Vec<u8> = FIXTURE
|
||||
.iter()
|
||||
.flat_map(|(_, _, words)| words.iter().flat_map(|word| word.to_le_bytes()))
|
||||
.collect();
|
||||
let stream = block.repeat(COPIES);
|
||||
|
||||
// 'cargo test --all-targets' checks the fixture without timing it.
|
||||
if !std::env::args().any(|arg| arg == "--bench") {
|
||||
verify(&stream);
|
||||
return;
|
||||
}
|
||||
|
||||
// Keep the first pass ahead of any metadata lookups. Validate the entire
|
||||
// stream before reporting any timings. That validation also warms the path.
|
||||
let first = measure(&stream);
|
||||
verify(&stream);
|
||||
let mut warm = [Duration::ZERO; WARM_PASSES];
|
||||
for sample in &mut warm {
|
||||
*sample = measure(&stream);
|
||||
}
|
||||
warm.sort_unstable();
|
||||
|
||||
println!(
|
||||
"gfx1030 metadata identification: {} instructions, {} bytes, {} repeated passes",
|
||||
COPIES * FIXTURE.len(),
|
||||
stream.len(),
|
||||
WARM_PASSES
|
||||
);
|
||||
report("First pass in a fresh process", first, stream.len());
|
||||
report("Repeated minimum", warm[0], stream.len());
|
||||
report("Repeated median", warm[WARM_PASSES / 2], stream.len());
|
||||
report("Repeated maximum", warm[WARM_PASSES - 1], stream.len());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn mixed_llvm_fixture_preserves_names_families_lengths_and_boundaries() {
|
||||
let block: Vec<u8> = super::FIXTURE
|
||||
.iter()
|
||||
.flat_map(|(_, _, words)| words.iter().flat_map(|word| word.to_le_bytes()))
|
||||
.collect();
|
||||
super::verify(&block.repeat(super::COPIES));
|
||||
}
|
||||
}
|
||||
+6
-243
@@ -14,12 +14,11 @@ use std::path::PathBuf;
|
||||
use std::process::Command;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use xenora_metal::{NativeCompute, RunProfile};
|
||||
use xenora_metal::NativeCompute;
|
||||
use xenora_shader::{Architecture, ENTRY_POINT, compile};
|
||||
|
||||
const WARMUP_REPS: usize = 2;
|
||||
const DEFAULT_REPS: usize = 7;
|
||||
const BATCH: usize = 8;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct Fixture {
|
||||
@@ -84,66 +83,10 @@ struct SizeResult {
|
||||
pipeline: Stats,
|
||||
gpu: Stats,
|
||||
host: Stats,
|
||||
/// Host submission stages inside `host`, plus readback after it.
|
||||
submit: SubmitStats,
|
||||
/// Fraction of samples whose GPU timestamp delta was zero.
|
||||
gpu_zero_fraction: f64,
|
||||
}
|
||||
|
||||
/// Host-side split of one dispatch's submission path.
|
||||
///
|
||||
/// `other` is `host` minus library, pipeline and the four stages below it,
|
||||
/// per sample: compile options, function lookup, bounds and validation checks.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
struct SubmitStats {
|
||||
alloc: Stats,
|
||||
encode: Stats,
|
||||
commit: Stats,
|
||||
wait: Stats,
|
||||
readback: Stats,
|
||||
other: Stats,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
struct SubmitSamples {
|
||||
alloc: Vec<f64>,
|
||||
encode: Vec<f64>,
|
||||
commit: Vec<f64>,
|
||||
wait: Vec<f64>,
|
||||
readback: Vec<f64>,
|
||||
other: Vec<f64>,
|
||||
}
|
||||
|
||||
impl SubmitSamples {
|
||||
fn push(&mut self, profile: &RunProfile) {
|
||||
self.alloc.push(profile.alloc_seconds);
|
||||
self.encode.push(profile.encode_seconds);
|
||||
self.commit.push(profile.commit_seconds);
|
||||
self.wait.push(profile.wait_seconds);
|
||||
self.readback.push(profile.readback_seconds);
|
||||
self.other.push(
|
||||
profile.host_seconds
|
||||
- profile.library_seconds
|
||||
- profile.pipeline_seconds
|
||||
- profile.alloc_seconds
|
||||
- profile.encode_seconds
|
||||
- profile.commit_seconds
|
||||
- profile.wait_seconds,
|
||||
);
|
||||
}
|
||||
|
||||
fn stats(self) -> SubmitStats {
|
||||
SubmitStats {
|
||||
alloc: Stats::from_samples(self.alloc),
|
||||
encode: Stats::from_samples(self.encode),
|
||||
commit: Stats::from_samples(self.commit),
|
||||
wait: Stats::from_samples(self.wait),
|
||||
readback: Stats::from_samples(self.readback),
|
||||
other: Stats::from_samples(self.other),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct FixtureResult {
|
||||
name: String,
|
||||
@@ -152,31 +95,12 @@ struct FixtureResult {
|
||||
status: String,
|
||||
reason: String,
|
||||
sizes: Vec<SizeResult>,
|
||||
batch: Option<BatchResult>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct BatchResult {
|
||||
words: usize,
|
||||
sync: Stats,
|
||||
pipelined: Stats,
|
||||
}
|
||||
|
||||
mod startup;
|
||||
mod startup_report;
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
// Taken before anything else so a fresh startup child can report the time
|
||||
// from its parent's spawn to `main`.
|
||||
let entered = SystemTime::now();
|
||||
let mut args = std::env::args().skip(1).peekable();
|
||||
match args.peek().map(String::as_str) {
|
||||
Some("startup") => return startup::run(args.skip(1)),
|
||||
Some("startup-child") => return startup::child(entered, args.skip(1)),
|
||||
_ => {}
|
||||
}
|
||||
let mut output = PathBuf::from("benchmarks/results");
|
||||
let mut reps = DEFAULT_REPS;
|
||||
let mut args = std::env::args().skip(1);
|
||||
while let Some(arg) = args.next() {
|
||||
match arg.as_str() {
|
||||
"--output" => {
|
||||
@@ -190,11 +114,7 @@ fn main() -> Result<(), Box<dyn Error>> {
|
||||
.map_err(|_| "--reps must be a positive integer")?;
|
||||
}
|
||||
"--help" | "-h" => {
|
||||
println!(
|
||||
"usage: xenora-bench [--output DIR] [--reps N]\n \
|
||||
xenora-bench startup [--fixture NAME] [--words N] [--processes N] \
|
||||
[--reps N] [--output DIR]"
|
||||
);
|
||||
println!("usage: xenora-bench [--output DIR] [--reps N]");
|
||||
return Ok(());
|
||||
}
|
||||
other => return Err(format!("unknown argument {other}").into()),
|
||||
@@ -260,7 +180,6 @@ fn run_fixture(metal: &NativeCompute, fixture: &Fixture, reps: usize) -> Fixture
|
||||
status: "not-implemented".to_string(),
|
||||
reason: String::new(),
|
||||
sizes: Vec::new(),
|
||||
batch: None,
|
||||
};
|
||||
|
||||
let code = match fs::read(&fixture.path) {
|
||||
@@ -323,7 +242,6 @@ fn run_fixture(metal: &NativeCompute, fixture: &Fixture, reps: usize) -> Fixture
|
||||
let mut pipeline_samples = Vec::with_capacity(reps);
|
||||
let mut gpu_samples = Vec::with_capacity(reps);
|
||||
let mut host_samples = Vec::with_capacity(reps);
|
||||
let mut submit_samples = SubmitSamples::default();
|
||||
let mut gpu_zero = 0usize;
|
||||
|
||||
let mut mismatch = None;
|
||||
@@ -357,7 +275,6 @@ fn run_fixture(metal: &NativeCompute, fixture: &Fixture, reps: usize) -> Fixture
|
||||
pipeline_samples.push(profile.pipeline_seconds);
|
||||
gpu_samples.push(profile.gpu_seconds);
|
||||
host_samples.push(profile.host_seconds);
|
||||
submit_samples.push(&profile);
|
||||
if profile.gpu_seconds <= 0.0 {
|
||||
gpu_zero += 1;
|
||||
}
|
||||
@@ -377,7 +294,6 @@ fn run_fixture(metal: &NativeCompute, fixture: &Fixture, reps: usize) -> Fixture
|
||||
pipeline: Stats::from_samples(pipeline_samples),
|
||||
gpu: Stats::from_samples(gpu_samples),
|
||||
host: Stats::from_samples(host_samples),
|
||||
submit: submit_samples.stats(),
|
||||
gpu_zero_fraction: if measured == 0 {
|
||||
0.0
|
||||
} else {
|
||||
@@ -386,83 +302,11 @@ fn run_fixture(metal: &NativeCompute, fixture: &Fixture, reps: usize) -> Fixture
|
||||
});
|
||||
}
|
||||
|
||||
let batch_words = fixture
|
||||
.sizes
|
||||
.iter()
|
||||
.copied()
|
||||
.min_by_key(|words| words.abs_diff(1024))
|
||||
.unwrap_or(1024);
|
||||
match measure_batch(metal, &code, fixture, batch_words, reps) {
|
||||
Ok(batch) => result.batch = Some(batch),
|
||||
Err(reason) => {
|
||||
result.status = "excluded".to_string();
|
||||
result.reason = reason;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
result.sizes = sizes;
|
||||
result.status = "benchmarked".to_string();
|
||||
result
|
||||
}
|
||||
|
||||
fn measure_batch(
|
||||
metal: &NativeCompute,
|
||||
code: &[u8],
|
||||
fixture: &Fixture,
|
||||
words: usize,
|
||||
reps: usize,
|
||||
) -> Result<BatchResult, String> {
|
||||
let input = expand(&fixture.input, words);
|
||||
let expected = expand(&fixture.expected, words);
|
||||
let mut sync = Vec::with_capacity(reps);
|
||||
let mut pipelined = Vec::with_capacity(reps);
|
||||
for rep in 0..(WARMUP_REPS + reps) {
|
||||
for (samples, variant) in [(&mut sync, "sync"), (&mut pipelined, "pipelined")] {
|
||||
let mut tokens = Vec::with_capacity(BATCH);
|
||||
let mut outputs = Vec::with_capacity(BATCH);
|
||||
let start = std::time::Instant::now();
|
||||
for _ in 0..BATCH {
|
||||
let compiled = compile(Architecture::Gfx1030, code).map_err(|error| {
|
||||
format!("{variant} batch compile failed at {words} words: {error}")
|
||||
})?;
|
||||
if variant == "sync" {
|
||||
let profile = metal
|
||||
.run_words_profiled(&compiled.msl, ENTRY_POINT, &input)
|
||||
.map_err(|error| {
|
||||
format!("{variant} batch run failed at {words} words: {error}")
|
||||
})?;
|
||||
outputs.push(profile.output);
|
||||
} else {
|
||||
let token = metal
|
||||
.submit_words(&compiled.msl, ENTRY_POINT, &input)
|
||||
.map_err(|error| {
|
||||
format!("{variant} batch submit failed at {words} words: {error}")
|
||||
})?;
|
||||
tokens.push(token);
|
||||
}
|
||||
}
|
||||
for token in tokens {
|
||||
let profile = metal.wait(token).map_err(|error| {
|
||||
format!("{variant} batch wait failed at {words} words: {error}")
|
||||
})?;
|
||||
outputs.push(profile.output);
|
||||
}
|
||||
let per_dispatch = start.elapsed().as_secs_f64() / BATCH as f64;
|
||||
if outputs.iter().any(|output| *output != expected) {
|
||||
return Err(format!("{variant} batch GPU mismatch at {words} words"));
|
||||
}
|
||||
if rep >= WARMUP_REPS {
|
||||
samples.push(per_dispatch);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(BatchResult {
|
||||
words,
|
||||
sync: Stats::from_samples(sync),
|
||||
pipelined: Stats::from_samples(pipelined),
|
||||
})
|
||||
}
|
||||
|
||||
fn expand(base: &[u32], words: usize) -> Vec<u32> {
|
||||
(0..words).map(|i| base[i % base.len()]).collect()
|
||||
}
|
||||
@@ -768,19 +612,13 @@ fn results_json(results: &[FixtureResult]) -> String {
|
||||
for (size_index, size) in result.sizes.iter().enumerate() {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" {{ \"words\": {}, \"compile\": {}, \"library\": {}, \"pipeline\": {}, \"gpu\": {}, \"host\": {}, \"alloc\": {}, \"encode\": {}, \"commit\": {}, \"wait\": {}, \"readback\": {}, \"host_other\": {}, \"gpu_zero_fraction\": {:.4} }}{}",
|
||||
" {{ \"words\": {}, \"compile\": {}, \"library\": {}, \"pipeline\": {}, \"gpu\": {}, \"host\": {}, \"gpu_zero_fraction\": {:.4} }}{}",
|
||||
size.words,
|
||||
stats_json(&size.compile),
|
||||
stats_json(&size.library),
|
||||
stats_json(&size.pipeline),
|
||||
stats_json(&size.gpu),
|
||||
stats_json(&size.host),
|
||||
stats_json(&size.submit.alloc),
|
||||
stats_json(&size.submit.encode),
|
||||
stats_json(&size.submit.commit),
|
||||
stats_json(&size.submit.wait),
|
||||
stats_json(&size.submit.readback),
|
||||
stats_json(&size.submit.other),
|
||||
size.gpu_zero_fraction,
|
||||
if size_index + 1 == result.sizes.len() {
|
||||
""
|
||||
@@ -789,19 +627,9 @@ fn results_json(results: &[FixtureResult]) -> String {
|
||||
}
|
||||
);
|
||||
}
|
||||
out.push_str(" ]");
|
||||
if let Some(batch) = &result.batch {
|
||||
let _ = write!(
|
||||
out,
|
||||
",\n \"batch\": {{ \"dispatches\": {BATCH}, \"words\": {}, \"sync\": {}, \"pipelined\": {} }}",
|
||||
batch.words,
|
||||
stats_json(&batch.sync),
|
||||
stats_json(&batch.pipelined)
|
||||
);
|
||||
}
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"\n }}{}",
|
||||
" ]\n }}{}",
|
||||
if index + 1 == results.len() { "" } else { "," }
|
||||
);
|
||||
}
|
||||
@@ -816,7 +644,7 @@ fn report_markdown(metadata: &Metadata, results: &[FixtureResult]) -> String {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"Generated by `xenora-bench`. Every timed fixture passed its correctness test in this run. \
|
||||
See `docs/testing/benchmarks.md` for the single-dispatch protocol."
|
||||
Timings are single command-buffer samples; see `docs/testing/benchmarks.md` for the protocol."
|
||||
);
|
||||
let _ = writeln!(out);
|
||||
let _ = writeln!(out, "## Environment");
|
||||
@@ -911,70 +739,5 @@ fn report_markdown(metadata: &Metadata, results: &[FixtureResult]) -> String {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let _ = writeln!(out);
|
||||
let _ = writeln!(out, "## Submission split");
|
||||
let _ = writeln!(out);
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"Medians in microseconds of the host stages inside `host`: `alloc` creates the input and \
|
||||
output shared buffers, `encode` creates the command buffer and encodes the dispatch, \
|
||||
`commit` and `wait` time `commit` and `waitUntilCompleted`, and `other` is the per-sample \
|
||||
remainder of `host` after library, pipeline and these four stages. `readback` copies \
|
||||
the output after `host` ends."
|
||||
);
|
||||
let _ = writeln!(out);
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"| Fixture | Words | host | alloc | encode | commit | wait | other | readback |"
|
||||
);
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"| --- | --- | --- | --- | --- | --- | --- | --- | --- |"
|
||||
);
|
||||
for result in results.iter().filter(|r| r.status == "benchmarked") {
|
||||
for size in &result.sizes {
|
||||
let stages = &size.submit;
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"| {} | {} | {:.2} | {:.2} | {:.2} | {:.2} | {:.2} | {:.2} | {:.2} |",
|
||||
result.name,
|
||||
size.words,
|
||||
size.host.median * 1e6,
|
||||
stages.alloc.median * 1e6,
|
||||
stages.encode.median * 1e6,
|
||||
stages.commit.median * 1e6,
|
||||
stages.wait.median * 1e6,
|
||||
stages.other.median * 1e6,
|
||||
stages.readback.median * 1e6
|
||||
);
|
||||
}
|
||||
}
|
||||
let _ = writeln!(out);
|
||||
let _ = writeln!(out, "## Batched submission");
|
||||
let _ = writeln!(out);
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"Median host microseconds per dispatch in batches of {BATCH}, including recompilation."
|
||||
);
|
||||
let _ = writeln!(out);
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"| Fixture | Words | Sync (µs) | Pipelined (µs) | Sync / pipelined |"
|
||||
);
|
||||
let _ = writeln!(out, "| --- | --- | --- | --- | --- |");
|
||||
for result in results {
|
||||
if let Some(batch) = &result.batch {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"| {} | {} | {:.2} | {:.2} | {:.2}× |",
|
||||
result.name,
|
||||
batch.words,
|
||||
batch.sync.median * 1e6,
|
||||
batch.pipelined.median * 1e6,
|
||||
batch.sync.median / batch.pipelined.median
|
||||
);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -1,405 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Metal startup distributions: fresh processes versus repeated submissions (#178).
|
||||
//!
|
||||
//! `xenora-bench startup` checks one manifest fixture against the independent
|
||||
//! reference, then measures it two ways:
|
||||
//!
|
||||
//! - **Fresh process.** It launches its own executable `--processes` times. Each
|
||||
//! child creates the Metal device and queue, translates the fixture, runs it
|
||||
//! once with `run_words_profiled`, checks the output and prints one sample line.
|
||||
//! - **Repeated.** In this process it creates one device, then translates and runs
|
||||
//! the same fixture `--reps` times. The first run is reported on its own.
|
||||
//!
|
||||
//! Every sample must produce the expected words. One wrong output, failed child or
|
||||
//! unparsable sample line stops the run before anything is written. The
|
||||
//! numbers describe this host only; two distributions do not explain each other.
|
||||
|
||||
use std::error::Error;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
use std::process::{Command, Stdio};
|
||||
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use xenora_metal::NativeCompute;
|
||||
use xenora_shader::{Architecture, ENTRY_POINT, compile};
|
||||
|
||||
use crate::startup_report::Report;
|
||||
use crate::{Fixture, Metadata, expand, parse_manifest, percentile, slug};
|
||||
|
||||
const DEFAULT_PROCESSES: usize = 30;
|
||||
const DEFAULT_REPS: usize = 100;
|
||||
/// A fresh process that has not exited by then is killed and fails the run.
|
||||
const CHILD_TIMEOUT: Duration = Duration::from_secs(60);
|
||||
|
||||
/// Phases of one run, in seconds. `spawn_to_main` exists only for fresh processes.
|
||||
pub(crate) const PHASES: [&str; 8] = [
|
||||
"spawn_to_main",
|
||||
"device",
|
||||
"translate",
|
||||
"library",
|
||||
"pipeline",
|
||||
"submit",
|
||||
"gpu",
|
||||
"readback",
|
||||
];
|
||||
|
||||
/// One run's phase timings, indexed like [`PHASES`].
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Default)]
|
||||
pub(crate) struct Sample(pub(crate) [f64; PHASES.len()]);
|
||||
|
||||
impl Sample {
|
||||
fn line(&self) -> String {
|
||||
let fields: Vec<String> = PHASES
|
||||
.iter()
|
||||
.zip(self.0)
|
||||
.map(|(name, value)| format!("{name}={value:e}"))
|
||||
.collect();
|
||||
format!("startup-sample {}", fields.join(" "))
|
||||
}
|
||||
|
||||
/// Parses exactly the line [`Sample::line`] prints: every phase once, in order.
|
||||
pub(crate) fn parse(line: &str) -> Result<Self, String> {
|
||||
let rest = line
|
||||
.strip_prefix("startup-sample ")
|
||||
.ok_or("missing startup-sample prefix")?;
|
||||
let fields: Vec<&str> = rest.split(' ').collect();
|
||||
if fields.len() != PHASES.len() {
|
||||
return Err(format!(
|
||||
"expected {} fields, got {}",
|
||||
PHASES.len(),
|
||||
fields.len()
|
||||
));
|
||||
}
|
||||
let mut sample = Self::default();
|
||||
for (i, (field, name)) in fields.iter().zip(PHASES).enumerate() {
|
||||
let value = field
|
||||
.strip_prefix(name)
|
||||
.and_then(|v| v.strip_prefix('='))
|
||||
.ok_or_else(|| format!("field {i} is not {name}=<seconds>"))?;
|
||||
let value: f64 = value.parse().map_err(|_| format!("bad {name} value"))?;
|
||||
if !value.is_finite() || value < 0.0 {
|
||||
return Err(format!("{name} must be finite and non-negative"));
|
||||
}
|
||||
sample.0[i] = value;
|
||||
}
|
||||
Ok(sample)
|
||||
}
|
||||
}
|
||||
|
||||
/// Median, tail and extremes of one phase.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub(crate) struct Summary {
|
||||
pub(crate) n: usize,
|
||||
pub(crate) min: f64,
|
||||
pub(crate) median: f64,
|
||||
pub(crate) p90: f64,
|
||||
pub(crate) p99: f64,
|
||||
pub(crate) max: f64,
|
||||
}
|
||||
|
||||
pub(crate) fn summarize(values: &[f64]) -> Option<Summary> {
|
||||
if values.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut sorted = values.to_vec();
|
||||
sorted.sort_by(f64::total_cmp);
|
||||
Some(Summary {
|
||||
n: sorted.len(),
|
||||
min: sorted[0],
|
||||
median: percentile(&sorted, 0.5),
|
||||
p90: percentile(&sorted, 0.9),
|
||||
p99: percentile(&sorted, 0.99),
|
||||
max: sorted[sorted.len() - 1],
|
||||
})
|
||||
}
|
||||
|
||||
struct Options {
|
||||
fixture: Option<String>,
|
||||
words: Option<usize>,
|
||||
processes: usize,
|
||||
reps: usize,
|
||||
output: PathBuf,
|
||||
}
|
||||
|
||||
fn count(value: Option<String>, flag: &str) -> Result<usize, String> {
|
||||
let n: usize = value
|
||||
.ok_or_else(|| format!("{flag} needs a count"))?
|
||||
.parse()
|
||||
.map_err(|_| format!("{flag} must be a positive integer"))?;
|
||||
if n == 0 {
|
||||
return Err(format!("{flag} must be at least 1"));
|
||||
}
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
fn parse_options(mut args: impl Iterator<Item = String>) -> Result<Options, String> {
|
||||
let mut options = Options {
|
||||
fixture: None,
|
||||
words: None,
|
||||
processes: DEFAULT_PROCESSES,
|
||||
reps: DEFAULT_REPS,
|
||||
output: PathBuf::from("artifacts/startup"),
|
||||
};
|
||||
while let Some(arg) = args.next() {
|
||||
match arg.as_str() {
|
||||
"--fixture" => options.fixture = Some(args.next().ok_or("--fixture needs a name")?),
|
||||
"--words" => options.words = Some(count(args.next(), "--words")?),
|
||||
"--processes" => options.processes = count(args.next(), "--processes")?,
|
||||
"--reps" => options.reps = count(args.next(), "--reps")?,
|
||||
"--output" => {
|
||||
options.output = PathBuf::from(args.next().ok_or("--output needs a path")?);
|
||||
}
|
||||
other => return Err(format!("unknown startup argument {other}")),
|
||||
}
|
||||
}
|
||||
Ok(options)
|
||||
}
|
||||
|
||||
/// The fixture to time and its word count, after the reference agrees with it.
|
||||
fn select(options: &Options) -> Result<(Fixture, usize), Box<dyn Error>> {
|
||||
let fixtures = parse_manifest(&fs::read_to_string("benchmarks/manifest.toml")?)?;
|
||||
let fixture = match &options.fixture {
|
||||
Some(name) => fixtures.into_iter().find(|f| &f.name == name),
|
||||
None => fixtures.into_iter().next(),
|
||||
}
|
||||
.ok_or("fixture not found in benchmarks/manifest.toml")?;
|
||||
let code = fs::read(&fixture.path)?;
|
||||
let reference = xenora_ref::execute(&code, &fixture.input).map_err(|e| e.to_string())?;
|
||||
if reference != fixture.expected {
|
||||
return Err("reference disagrees with hand-derived expected values".into());
|
||||
}
|
||||
let words = options
|
||||
.words
|
||||
.unwrap_or_else(|| *fixture.sizes.first().unwrap_or(&fixture.input.len()));
|
||||
Ok((fixture, words))
|
||||
}
|
||||
|
||||
/// Translates and runs the fixture once on `metal`, checking the output.
|
||||
fn run_once(
|
||||
metal: &NativeCompute,
|
||||
fixture: &Fixture,
|
||||
words: usize,
|
||||
sample: &mut Sample,
|
||||
) -> Result<(), Box<dyn Error>> {
|
||||
let input = expand(&fixture.input, words);
|
||||
let expected = expand(&fixture.expected, words);
|
||||
let start = Instant::now();
|
||||
let code = fs::read(&fixture.path)?;
|
||||
let compiled = compile(Architecture::Gfx1030, &code).map_err(|e| e.to_string())?;
|
||||
sample.0[2] = start.elapsed().as_secs_f64();
|
||||
let profile = metal
|
||||
.run_words_profiled(&compiled.msl, ENTRY_POINT, &input)
|
||||
.map_err(|e| e.to_string())?;
|
||||
if profile.output != expected {
|
||||
return Err(format!("{} output disagrees with known answers", fixture.name).into());
|
||||
}
|
||||
sample.0[3] = profile.library_seconds;
|
||||
sample.0[4] = profile.pipeline_seconds;
|
||||
sample.0[5] = profile.host_seconds - profile.library_seconds - profile.pipeline_seconds;
|
||||
sample.0[6] = profile.gpu_seconds;
|
||||
sample.0[7] = profile.readback_seconds;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn unix_nanos(time: SystemTime) -> u128 {
|
||||
time.duration_since(UNIX_EPOCH).map_or(0, |d| d.as_nanos())
|
||||
}
|
||||
|
||||
/// Entry point of one fresh child process, called first thing in `main`.
|
||||
///
|
||||
/// `entered` is the wall-clock time at `main`; the parent passes the wall-clock
|
||||
/// time just before it spawned this process.
|
||||
pub(crate) fn child(
|
||||
entered: SystemTime,
|
||||
mut args: impl Iterator<Item = String>,
|
||||
) -> Result<(), Box<dyn Error>> {
|
||||
let spawned: u128 = args.next().ok_or("missing spawn time")?.parse()?;
|
||||
let options = parse_options(args)?;
|
||||
let (fixture, words) = select(&options)?;
|
||||
let mut sample = Sample::default();
|
||||
sample.0[0] = unix_nanos(entered).saturating_sub(spawned) as f64 / 1e9;
|
||||
let start = Instant::now();
|
||||
let metal = NativeCompute::new().map_err(|e| e.to_string())?;
|
||||
sample.0[1] = start.elapsed().as_secs_f64();
|
||||
run_once(&metal, &fixture, words, &mut sample)?;
|
||||
println!("{}", sample.line());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn forwarded(fixture: &Fixture, words: usize) -> Vec<String> {
|
||||
vec![
|
||||
"--fixture".into(),
|
||||
fixture.name.clone(),
|
||||
"--words".into(),
|
||||
words.to_string(),
|
||||
]
|
||||
}
|
||||
|
||||
/// Runs one fresh child and returns its spawn-to-exit wall time and stdout.
|
||||
///
|
||||
/// The child inherits this process's environment on purpose, so its `MTL_*`
|
||||
/// validation settings are the ones the run's metadata records.
|
||||
fn spawn_child(
|
||||
exe: &std::path::Path,
|
||||
fixture: &Fixture,
|
||||
words: usize,
|
||||
) -> Result<(f64, String), Box<dyn Error>> {
|
||||
let started = Instant::now();
|
||||
let spawned = unix_nanos(SystemTime::now());
|
||||
let mut child = Command::new(exe)
|
||||
.arg("startup-child")
|
||||
.arg(spawned.to_string())
|
||||
.args(forwarded(fixture, words))
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()?;
|
||||
// Drain both pipes while waiting, so a child that writes more than a pipe
|
||||
// buffer (validation logs, for example) cannot block and look like a hang.
|
||||
let drain = |pipe: Option<Box<dyn std::io::Read + Send>>| {
|
||||
std::thread::spawn(move || {
|
||||
let mut text = String::new();
|
||||
if let Some(mut pipe) = pipe {
|
||||
let _ = pipe.read_to_string(&mut text);
|
||||
}
|
||||
text
|
||||
})
|
||||
};
|
||||
let out = drain(child.stdout.take().map(|p| Box::new(p) as _));
|
||||
let err = drain(child.stderr.take().map(|p| Box::new(p) as _));
|
||||
let status = loop {
|
||||
if let Some(status) = child.try_wait()? {
|
||||
break status;
|
||||
}
|
||||
if started.elapsed() > CHILD_TIMEOUT {
|
||||
child.kill()?;
|
||||
child.wait()?;
|
||||
return Err(format!("no exit within {} s", CHILD_TIMEOUT.as_secs()).into());
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
};
|
||||
let seconds = started.elapsed().as_secs_f64();
|
||||
let stdout = out.join().map_err(|_| "stdout reader panicked")?;
|
||||
let stderr = err.join().map_err(|_| "stderr reader panicked")?;
|
||||
if !status.success() {
|
||||
return Err(format!("{status}: {}", stderr.trim()).into());
|
||||
}
|
||||
Ok((seconds, stdout))
|
||||
}
|
||||
|
||||
/// Runs both regimes and writes `startup.json` and `report.md`.
|
||||
pub(crate) fn run(args: impl Iterator<Item = String>) -> Result<(), Box<dyn Error>> {
|
||||
let options = parse_options(args)?;
|
||||
let (fixture, words) = select(&options)?;
|
||||
let exe = std::env::current_exe()?;
|
||||
|
||||
let mut fresh = Vec::with_capacity(options.processes);
|
||||
let mut wall = Vec::with_capacity(options.processes);
|
||||
for i in 0..options.processes {
|
||||
let (seconds, stdout) = spawn_child(&exe, &fixture, words)
|
||||
.map_err(|e| format!("fresh process {i} failed: {e}"))?;
|
||||
wall.push(seconds);
|
||||
let line = stdout
|
||||
.lines()
|
||||
.find(|l| l.starts_with("startup-sample "))
|
||||
.ok_or_else(|| format!("fresh process {i} printed no sample"))?;
|
||||
fresh.push(Sample::parse(line).map_err(|e| format!("fresh process {i}: {e}"))?);
|
||||
}
|
||||
|
||||
let mut first = Sample::default();
|
||||
let start = Instant::now();
|
||||
let metal = NativeCompute::new().map_err(|e| e.to_string())?;
|
||||
first.0[1] = start.elapsed().as_secs_f64();
|
||||
run_once(&metal, &fixture, words, &mut first)?;
|
||||
let mut repeated = Vec::with_capacity(options.reps);
|
||||
for _ in 0..options.reps {
|
||||
let mut sample = Sample::default();
|
||||
run_once(&metal, &fixture, words, &mut sample)?;
|
||||
repeated.push(sample);
|
||||
}
|
||||
|
||||
let metadata = Metadata::collect(&metal.device_name(), options.reps);
|
||||
let dir = options
|
||||
.output
|
||||
.join(slug(&metadata.device))
|
||||
.join(&metadata.run_id);
|
||||
fs::create_dir_all(&dir)?;
|
||||
fs::write(dir.join("metadata.json"), metadata.to_json())?;
|
||||
let report = Report {
|
||||
fixture: &fixture.name,
|
||||
words,
|
||||
fresh: &fresh,
|
||||
wall: &wall,
|
||||
first: &first,
|
||||
repeated: &repeated,
|
||||
};
|
||||
fs::write(dir.join("startup.json"), report.json())?;
|
||||
let markdown = report.markdown(&metadata);
|
||||
fs::write(dir.join("report.md"), &markdown)?;
|
||||
println!("{markdown}");
|
||||
println!("Startup results written to {}", dir.display());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn sample_lines_round_trip() {
|
||||
let sample = Sample([0.5, 1e-3, 2.5e-4, 0.0, 7.0, 1e-9, 3.25, 42.0]);
|
||||
assert_eq!(Sample::parse(&sample.line()), Ok(sample));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sample_lines_reject_damaged_input() {
|
||||
let line = Sample([1.0; PHASES.len()]).line();
|
||||
assert!(Sample::parse(&line.replacen("startup-sample", "sample", 1)).is_err());
|
||||
assert!(Sample::parse(&line.replacen("device=", "devise=", 1)).is_err());
|
||||
assert!(Sample::parse(&line.replacen("gpu=1e0", "gpu=-1e0", 1)).is_err());
|
||||
assert!(Sample::parse(&line.replacen("gpu=1e0", "gpu=NaN", 1)).is_err());
|
||||
assert!(Sample::parse(&line.replacen("gpu=1e0", "gpu=x", 1)).is_err());
|
||||
assert!(Sample::parse(line.rsplit_once(' ').unwrap().0).is_err());
|
||||
assert!(Sample::parse(&format!("{line} extra=1")).is_err());
|
||||
// Phases out of order are refused even when every name is present.
|
||||
let swapped = line
|
||||
.replacen("device=", "TMP=", 1)
|
||||
.replacen("translate=", "device=", 1)
|
||||
.replacen("TMP=", "translate=", 1);
|
||||
assert!(Sample::parse(&swapped).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn summary_uses_interpolated_percentiles() {
|
||||
// 1..=100: position 0.9 * 99 = 89.1 lies between 90 and 91, and
|
||||
// 0.99 * 99 = 98.01 between 99 and 100.
|
||||
let values: Vec<f64> = (1..=100).rev().map(f64::from).collect();
|
||||
let s = summarize(&values).unwrap();
|
||||
assert_eq!((s.n, s.min, s.max), (100, 1.0, 100.0));
|
||||
assert!((s.median - 50.5).abs() < 1e-9);
|
||||
assert!((s.p90 - 90.1).abs() < 1e-9);
|
||||
assert!((s.p99 - 99.01).abs() < 1e-9);
|
||||
assert_eq!(summarize(&[]), None);
|
||||
let one = summarize(&[3.0]).unwrap();
|
||||
assert_eq!(
|
||||
(one.median, one.p90, one.p99, one.max),
|
||||
(3.0, 3.0, 3.0, 3.0)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_reject_bad_counts_and_flags() {
|
||||
let parse = |args: &[&str]| parse_options(args.iter().map(|s| s.to_string()));
|
||||
let defaults = parse(&[]).unwrap();
|
||||
assert_eq!(
|
||||
(defaults.processes, defaults.reps),
|
||||
(DEFAULT_PROCESSES, DEFAULT_REPS)
|
||||
);
|
||||
let set = parse(&["--processes", "3", "--reps", "5", "--words", "64"]).unwrap();
|
||||
assert_eq!((set.processes, set.reps, set.words), (3, 5, Some(64)));
|
||||
assert!(parse(&["--processes", "0"]).is_err());
|
||||
assert!(parse(&["--reps", "-1"]).is_err());
|
||||
assert!(parse(&["--words"]).is_err());
|
||||
assert!(parse(&["--fast"]).is_err());
|
||||
}
|
||||
}
|
||||
@@ -1,146 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! JSON and markdown output of `xenora-bench startup` (#178).
|
||||
|
||||
use std::fmt::Write as _;
|
||||
|
||||
use crate::startup::{PHASES, Sample, Summary, summarize};
|
||||
use crate::{Metadata, json_str};
|
||||
|
||||
pub(crate) struct Report<'a> {
|
||||
pub(crate) fixture: &'a str,
|
||||
pub(crate) words: usize,
|
||||
pub(crate) fresh: &'a [Sample],
|
||||
pub(crate) wall: &'a [f64],
|
||||
pub(crate) first: &'a Sample,
|
||||
pub(crate) repeated: &'a [Sample],
|
||||
}
|
||||
|
||||
fn column(samples: &[Sample], phase: usize) -> Vec<f64> {
|
||||
samples.iter().map(|s| s.0[phase]).collect()
|
||||
}
|
||||
|
||||
fn summary_json(summary: Option<Summary>) -> String {
|
||||
summary.map_or_else(
|
||||
|| "null".to_string(),
|
||||
|s| {
|
||||
format!(
|
||||
"{{\"n\": {}, \"min\": {:e}, \"median\": {:e}, \"p90\": {:e}, \"p99\": {:e}, \"max\": {:e}}}",
|
||||
s.n, s.min, s.median, s.p90, s.p99, s.max
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
impl Report<'_> {
|
||||
pub(crate) fn json(&self) -> String {
|
||||
let mut out = format!(
|
||||
"{{\n \"fixture\": {},\n \"words\": {},\n \"process_wall\": {},\n",
|
||||
json_str(self.fixture),
|
||||
self.words,
|
||||
summary_json(summarize(self.wall))
|
||||
);
|
||||
for (regime, samples) in [("fresh", self.fresh), ("repeated", self.repeated)] {
|
||||
let _ = writeln!(out, " \"{regime}\": {{");
|
||||
for (i, phase) in PHASES.iter().enumerate() {
|
||||
let comma = if i + 1 < PHASES.len() { "," } else { "" };
|
||||
let summary = if regime == "repeated" && i < 2 {
|
||||
None
|
||||
} else {
|
||||
summarize(&column(samples, i))
|
||||
};
|
||||
let _ = writeln!(out, " \"{phase}\": {}{comma}", summary_json(summary));
|
||||
}
|
||||
out.push_str(" },\n");
|
||||
}
|
||||
let first: Vec<String> = PHASES
|
||||
.iter()
|
||||
.zip(self.first.0)
|
||||
.skip(1)
|
||||
.map(|(p, v)| format!("\"{p}\": {v:e}"))
|
||||
.collect();
|
||||
let _ = writeln!(out, " \"first_in_process\": {{{}}},", first.join(", "));
|
||||
// Raw fresh-process samples in launch order, so a cold first process
|
||||
// (for example an empty Metal shader cache) stays visible.
|
||||
let rows: Vec<String> = self
|
||||
.fresh
|
||||
.iter()
|
||||
.zip(self.wall)
|
||||
.map(|(sample, wall)| {
|
||||
let phases: Vec<String> = sample.0.iter().map(|v| format!("{v:e}")).collect();
|
||||
format!("[{}, {wall:e}]", phases.join(", "))
|
||||
})
|
||||
.collect();
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" \"fresh_samples_columns\": [{}, \"process_wall\"],\n \"fresh_samples\": [\n {}\n ]\n}}",
|
||||
PHASES
|
||||
.iter()
|
||||
.map(|p| json_str(p))
|
||||
.collect::<Vec<_>>()
|
||||
.join(", "),
|
||||
rows.join(",\n ")
|
||||
);
|
||||
out
|
||||
}
|
||||
|
||||
pub(crate) fn markdown(&self, metadata: &Metadata) -> String {
|
||||
let ms = |v: f64| format!("{:.3}", v * 1e3);
|
||||
let mut out = format!(
|
||||
"# Metal startup: `{}`, {} words\n\nDevice {}, {} build, commit `{}`, API validation `{}`, shader validation `{}`, power `{}`, thermal `{}`.\n\nAll values in milliseconds. Fresh: {} processes. Repeated: {} runs after the first in one process. Every sample produced the expected output.\n\n| Phase | Fresh median | Fresh p90 | Fresh p99 | Fresh max | First in process | Repeated median | Repeated p90 | Repeated p99 | Repeated max |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n",
|
||||
self.fixture,
|
||||
self.words,
|
||||
metadata.device,
|
||||
metadata.profile,
|
||||
metadata.commit,
|
||||
metadata.api_validation,
|
||||
metadata.shader_validation,
|
||||
metadata.power,
|
||||
metadata.thermal,
|
||||
self.fresh.len(),
|
||||
self.repeated.len(),
|
||||
);
|
||||
for (i, phase) in PHASES.iter().enumerate() {
|
||||
let fresh = summarize(&column(self.fresh, i));
|
||||
let repeated = (i >= 2)
|
||||
.then(|| summarize(&column(self.repeated, i)))
|
||||
.flatten();
|
||||
let cells = |s: Option<Summary>| {
|
||||
s.map_or_else(
|
||||
|| "– | – | – | –".to_string(),
|
||||
|s| {
|
||||
format!(
|
||||
"{} | {} | {} | {}",
|
||||
ms(s.median),
|
||||
ms(s.p90),
|
||||
ms(s.p99),
|
||||
ms(s.max)
|
||||
)
|
||||
},
|
||||
)
|
||||
};
|
||||
let first = if i == 0 {
|
||||
"–".to_string()
|
||||
} else {
|
||||
ms(self.first.0[i])
|
||||
};
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"| `{phase}` | {} | {first} | {} |",
|
||||
cells(fresh),
|
||||
cells(repeated)
|
||||
);
|
||||
}
|
||||
if let Some(s) = summarize(self.wall) {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"| process wall (spawn to exit) | {} | {} | {} | {} | – | – | – | – | – |",
|
||||
ms(s.median),
|
||||
ms(s.p90),
|
||||
ms(s.p99),
|
||||
ms(s.max)
|
||||
);
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Exercise the benchmark's LLVM-derived fixture during ordinary workspace tests.
|
||||
#[allow(dead_code)]
|
||||
#[path = "../benches/gfx1030_identify.rs"]
|
||||
mod benchmark;
|
||||
@@ -1,5 +1,5 @@
|
||||
[package]
|
||||
name = "betterxen"
|
||||
name = "xenora"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
@@ -9,10 +9,7 @@ rust-version.workspace = true
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
xenora-decoder = { path = "../decoder" }
|
||||
xenora-isa = { path = "../isa" }
|
||||
xenora-metal = { path = "../metal" }
|
||||
xenora-ref = { path = "../ref" }
|
||||
xenora-shader = { path = "../shader" }
|
||||
xenora-loader = { path = "../loader" }
|
||||
xenora-import-gen = { path = "../import-gen" }
|
||||
+6
-517
@@ -1,19 +1,14 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
mod demo;
|
||||
mod runner;
|
||||
mod shaders;
|
||||
|
||||
use std::process::ExitCode;
|
||||
|
||||
/// Where `probe` writes and `imports sync` reads without `--report`.
|
||||
const DEFAULT_REPORT_DIR: &str = "diagnostics/probe";
|
||||
|
||||
fn main() -> ExitCode {
|
||||
match std::env::args().nth(1).as_deref() {
|
||||
Some("info") => {
|
||||
println!(
|
||||
"BetterXen {} ({})",
|
||||
"Xenora {} ({})",
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
std::env::consts::ARCH
|
||||
);
|
||||
@@ -21,7 +16,7 @@ fn main() -> ExitCode {
|
||||
}
|
||||
Some("inspect") => {
|
||||
let Some(file_path) = std::env::args().nth(2) else {
|
||||
eprintln!("usage: betterxen inspect <path-to-pe-binary>");
|
||||
eprintln!("usage: xenora inspect <path-to-pe-binary>");
|
||||
return ExitCode::from(2);
|
||||
};
|
||||
match xenora_loader::triage_file(&file_path) {
|
||||
@@ -42,14 +37,11 @@ fn main() -> ExitCode {
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
},
|
||||
Some("run") => runner::command(std::env::args_os().skip(2)),
|
||||
Some("imports") => imports_command(std::env::args().skip(2).collect()),
|
||||
Some("shaders") => shaders::command(&std::env::args().skip(2).collect::<Vec<_>>()),
|
||||
Some("probe") => {
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
let mut pe_path: Option<String> = None;
|
||||
let mut mode = "static".to_string();
|
||||
let mut report_dir = DEFAULT_REPORT_DIR.to_string();
|
||||
let mut report_dir = "diagnostics/gta6-candidate-e95020b2".to_string();
|
||||
|
||||
let mut i = 2;
|
||||
while i < args.len() {
|
||||
@@ -90,7 +82,7 @@ fn main() -> ExitCode {
|
||||
|
||||
let Some(pe) = pe_path else {
|
||||
eprintln!(
|
||||
"usage: betterxen probe --pe <path> [--mode <static>] [--report <output-dir>]"
|
||||
"usage: xenora probe --pe <path> [--mode <static>] [--report <output-dir>]"
|
||||
);
|
||||
return ExitCode::from(2);
|
||||
};
|
||||
@@ -111,20 +103,12 @@ fn main() -> ExitCode {
|
||||
let config = xenora_loader::ProbeConfig::default();
|
||||
match xenora_loader::run_probe_and_export(&bytes, &report_dir, &config) {
|
||||
Ok(report) => {
|
||||
println!("BetterXen static PE probe complete.");
|
||||
println!("Xenora static PE probe complete.");
|
||||
println!("Artifacts exported to: {report_dir}");
|
||||
println!("Sections: {}", report.parsed.sections.len());
|
||||
println!("Relocations: {}", report.relocations.total_entries);
|
||||
println!("TLS Callbacks: {}", report.tls.callback_targets.len());
|
||||
println!("Imported Thunks: {}", report.imports.len());
|
||||
println!(
|
||||
"Unresolved Standard Import Thunks: {}",
|
||||
report
|
||||
.imports
|
||||
.iter()
|
||||
.filter(|import| !import.is_supported)
|
||||
.count()
|
||||
);
|
||||
if let Some(insn) = report.first_unsupported_dbt_insn {
|
||||
println!("First DBT Blocker: RVA 0x{:08x} ({})", insn.rva, insn.notes);
|
||||
}
|
||||
@@ -137,503 +121,8 @@ fn main() -> ExitCode {
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
eprintln!("usage: betterxen <info|demo|inspect|probe|run|imports|shaders>");
|
||||
eprintln!("usage: xenora <info|demo|inspect|probe>");
|
||||
ExitCode::from(2)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `betterxen imports sync [--report <dir>] [--check]`
|
||||
/// `betterxen imports generate --pe <path> [--out <dir>]`
|
||||
/// `betterxen imports metadata sync [--out <dir>]`
|
||||
/// `betterxen imports verify`
|
||||
fn imports_command(args: Vec<String>) -> ExitCode {
|
||||
if args.is_empty() {
|
||||
eprintln!("usage: betterxen imports <sync|generate|metadata|verify> [options]");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
|
||||
match args[0].as_str() {
|
||||
"generate" => run_imports_generate_cli(&args[1..]),
|
||||
"sync" => run_imports_sync_cli(&args[1..]),
|
||||
"metadata" => run_imports_metadata_cli(&args[1..]),
|
||||
"verify" => run_imports_verify_cli(&args[1..]),
|
||||
other => {
|
||||
eprintln!("unknown imports subcommand: {other}");
|
||||
eprintln!("usage: betterxen imports <sync|generate|metadata|verify> [options]");
|
||||
ExitCode::from(2)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn run_imports_metadata_cli(args: &[String]) -> ExitCode {
|
||||
let mut out_dir = "artifacts/metadata".to_string();
|
||||
let mut i = 0;
|
||||
while i < args.len() {
|
||||
match args[i].as_str() {
|
||||
"sync" => {
|
||||
i += 1;
|
||||
}
|
||||
"--out" => {
|
||||
if i + 1 < args.len() {
|
||||
out_dir = args[i + 1].clone();
|
||||
i += 2;
|
||||
} else {
|
||||
eprintln!("missing argument for --out");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
}
|
||||
other => {
|
||||
eprintln!("unknown metadata argument: {other}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
println!("Synchronizing offline API metadata catalog from public specifications...");
|
||||
let catalog = xenora_import_gen::MetadataCatalog::builtin();
|
||||
println!(
|
||||
"Loaded version {} with {} entries.",
|
||||
catalog.version,
|
||||
catalog.entries.len()
|
||||
);
|
||||
|
||||
let _ = std::fs::create_dir_all(&out_dir);
|
||||
let out_file = format!("{out_dir}/api_catalog.json");
|
||||
let mut json = String::from("{\n \"version\": 1,\n \"entries\": [\n");
|
||||
let mut first = true;
|
||||
for ((module, sym), sig) in &catalog.entries {
|
||||
if !first {
|
||||
json.push_str(",\n");
|
||||
}
|
||||
first = false;
|
||||
json.push_str(&format!(
|
||||
" {{\"module\": \"{}\", \"symbol\": \"{}\", \"header\": \"{}\", \"doc\": \"{}\"}}",
|
||||
module, sym, sig.header_source, sig.doc
|
||||
));
|
||||
}
|
||||
json.push_str("\n ]\n}\n");
|
||||
|
||||
if let Err(e) = std::fs::write(&out_file, json) {
|
||||
eprintln!("failed to write metadata catalog: {e}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
println!("API metadata catalog synchronized to: {out_file}");
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
|
||||
fn run_imports_verify_cli(args: &[String]) -> ExitCode {
|
||||
if !args.is_empty() {
|
||||
eprintln!("warning: verify takes no additional arguments");
|
||||
}
|
||||
println!("Running automated behavioral verification for generated import bindings...");
|
||||
match xenora_import_gen::run_verification() {
|
||||
Ok(res) => {
|
||||
for detail in &res.details {
|
||||
println!(" {detail}");
|
||||
}
|
||||
println!(
|
||||
"Verification summary: {}/{} tests passed.",
|
||||
res.passed, res.total
|
||||
);
|
||||
if res.failed > 0 {
|
||||
ExitCode::FAILURE
|
||||
} else {
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!("verification failed: {err}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn run_imports_generate_cli(args: &[String]) -> ExitCode {
|
||||
let mut pe_path: Option<String> = None;
|
||||
let mut csv_path: Option<String> = None;
|
||||
let mut out_dir = "crates/loader/src/generated".to_string();
|
||||
|
||||
let mut i = 0;
|
||||
while i < args.len() {
|
||||
match args[i].as_str() {
|
||||
"--pe" => {
|
||||
if i + 1 < args.len() {
|
||||
pe_path = Some(args[i + 1].clone());
|
||||
i += 2;
|
||||
} else {
|
||||
eprintln!("missing argument for --pe");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
}
|
||||
"--csv" => {
|
||||
if i + 1 < args.len() {
|
||||
csv_path = Some(args[i + 1].clone());
|
||||
i += 2;
|
||||
} else {
|
||||
eprintln!("missing argument for --csv");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
}
|
||||
"--out" => {
|
||||
if i + 1 < args.len() {
|
||||
out_dir = args[i + 1].clone();
|
||||
i += 2;
|
||||
} else {
|
||||
eprintln!("missing argument for --out");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
}
|
||||
other => {
|
||||
eprintln!("unknown generate argument: {other}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut records = if let Some(ref pe) = pe_path {
|
||||
println!("Extracting imports from PE executable: {pe}");
|
||||
let bytes = match std::fs::read(pe) {
|
||||
Ok(b) => b,
|
||||
Err(err) => {
|
||||
eprintln!("error reading PE binary '{pe}': {err}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
let probe_cfg = xenora_loader::ProbeConfig::default();
|
||||
let report = match xenora_loader::probe::probe_pe_bytes(&bytes, &probe_cfg) {
|
||||
Ok(rep) => rep,
|
||||
Err(err) => {
|
||||
eprintln!("error probing PE binary: {err}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
report
|
||||
.imports
|
||||
.into_iter()
|
||||
.map(|imp| xenora_import_gen::ImportRecord {
|
||||
module: imp.dll,
|
||||
symbol: imp.symbol,
|
||||
ordinal: match imp.import_name {
|
||||
xenora_loader::import_table::ImportName::Ordinal(ordinal) => Some(ordinal),
|
||||
xenora_loader::import_table::ImportName::Name(_) => None,
|
||||
},
|
||||
iat_rva: imp.iat_rva as u64,
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
} else if let Some(ref csv) = csv_path {
|
||||
match xenora_import_gen::parse_csv(csv) {
|
||||
Ok(recs) => recs,
|
||||
Err(err) => {
|
||||
eprintln!("error reading CSV '{csv}': {err}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
eprintln!(
|
||||
"usage: betterxen imports generate <--pe <executable> | --csv <missing_imports.csv>> [--out <dir>]"
|
||||
);
|
||||
return ExitCode::from(2);
|
||||
};
|
||||
|
||||
records.sort();
|
||||
records.dedup();
|
||||
println!("Total imports extracted: {}", records.len());
|
||||
let db = xenora_import_gen::SymbolDb::builtin();
|
||||
let manifest = xenora_import_gen::Manifest::build(&records, &db);
|
||||
let summary = manifest.summary();
|
||||
|
||||
println!("Catalog classification by import slot:");
|
||||
for (tier, count) in &summary {
|
||||
let pct = (*count as f64 / records.len() as f64 * 100.0) as u32;
|
||||
println!(" - {tier}: {count} ({pct}%)");
|
||||
}
|
||||
|
||||
println!("Emitted disposition by distinct import:");
|
||||
for (disposition, count) in manifest.emission_summary() {
|
||||
println!(" - {disposition}: {count}");
|
||||
}
|
||||
|
||||
let files = xenora_import_gen::generate(&manifest, &db);
|
||||
if let Err(err) = files.write_all(&out_dir) {
|
||||
eprintln!("failed to write generated files: {err}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
let manifest_csv = format!("{out_dir}/generated_manifest.csv");
|
||||
if let Err(err) = manifest.write_csv(&manifest_csv) {
|
||||
eprintln!("failed to write manifest CSV: {err}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
|
||||
println!("Successfully generated bindings in '{out_dir}':");
|
||||
println!(" - {out_dir}/generated_crt.rs");
|
||||
println!(" - {out_dir}/generated_stubs.rs");
|
||||
println!(" - {out_dir}/generated_tests.rs");
|
||||
println!(" - {out_dir}/generated_manifest.md");
|
||||
println!(" - {out_dir}/generated_manifest.csv");
|
||||
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
|
||||
fn run_imports_sync_cli(args: &[String]) -> ExitCode {
|
||||
let mut report_dir = DEFAULT_REPORT_DIR.to_string();
|
||||
let mut check_mode = false;
|
||||
|
||||
let mut i = 0;
|
||||
while i < args.len() {
|
||||
match args[i].as_str() {
|
||||
"--report" => {
|
||||
if i + 1 < args.len() {
|
||||
report_dir = args[i + 1].clone();
|
||||
i += 2;
|
||||
} else {
|
||||
eprintln!("missing argument for --report");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
}
|
||||
"--check" => {
|
||||
check_mode = true;
|
||||
i += 1;
|
||||
}
|
||||
other => {
|
||||
eprintln!("unknown sync argument: {other}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
match run_imports_sync(&report_dir, check_mode) {
|
||||
Ok(changed) => {
|
||||
if check_mode {
|
||||
if changed {
|
||||
eprintln!("imports sync --check: import_backlog.md is out of date");
|
||||
ExitCode::FAILURE
|
||||
} else {
|
||||
println!("imports sync --check: import_backlog.md is up to date");
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
} else {
|
||||
println!("imports sync complete. Report written to: {report_dir}");
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("imports sync failed: {e}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn run_imports_sync(
|
||||
report_dir: &str,
|
||||
check_mode: bool,
|
||||
) -> Result<bool, Box<dyn std::error::Error>> {
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::sync::Arc;
|
||||
use xenora_loader::ImportRegistry;
|
||||
use xenora_loader::import_table::ImportName;
|
||||
use xenora_loader::imports::ServiceStatus;
|
||||
use xenora_loader::services::{MockClock, ServicesState, register_standard_services};
|
||||
|
||||
let imports_csv_path = std::path::Path::new(report_dir).join("imports.csv");
|
||||
if !imports_csv_path.exists() {
|
||||
return Err(format!(
|
||||
"imports.csv not found in '{report_dir}'. Run `betterxen probe` first."
|
||||
)
|
||||
.into());
|
||||
}
|
||||
|
||||
// Build the standard registry to get current implementation state.
|
||||
let mut registry = ImportRegistry::new();
|
||||
register_standard_services(
|
||||
&mut registry,
|
||||
Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))),
|
||||
);
|
||||
|
||||
// Parse imports.csv (skip header line).
|
||||
let csv_text = std::fs::read_to_string(&imports_csv_path)?;
|
||||
let mut by_module: BTreeMap<String, Vec<(String, bool, Option<ServiceStatus>)>> =
|
||||
BTreeMap::new();
|
||||
let mut total = 0usize;
|
||||
let mut counts: BTreeMap<&'static str, usize> = BTreeMap::new();
|
||||
|
||||
let mut lines = csv_text.lines();
|
||||
let header = lines.next().unwrap_or_default();
|
||||
let has_import_kind = header.ends_with(",import_kind");
|
||||
// Binding does not resolve delay-loaded imports, so the backlog omits them.
|
||||
let table_column = header
|
||||
.split(',')
|
||||
.position(|column| column == "import_table");
|
||||
for line in lines {
|
||||
if table_column.and_then(|index| line.split(',').nth(index)) == Some("delayed") {
|
||||
continue;
|
||||
}
|
||||
// Format: "module","symbol",0xRVA,category,registered,status,is_alias,"canonical",priority,cluster
|
||||
// We re-query the live registry rather than trusting cached status.
|
||||
let fields: Vec<&str> = line.splitn(10, ',').collect();
|
||||
if fields.len() < 2 {
|
||||
continue;
|
||||
}
|
||||
let module = fields[0].trim_matches('"').to_string();
|
||||
let symbol = fields[1].trim_matches('"').to_string();
|
||||
if module.is_empty() || symbol.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let name = if has_import_kind && line.ends_with(",ordinal") {
|
||||
let Some(ordinal) = symbol.strip_prefix("Ordinal#").and_then(|n| n.parse().ok()) else {
|
||||
continue;
|
||||
};
|
||||
ImportName::Ordinal(ordinal)
|
||||
} else {
|
||||
ImportName::Name(symbol.clone())
|
||||
};
|
||||
let binding = registry.resolve(&module, &name);
|
||||
let is_registered = binding.is_some();
|
||||
let status = binding.map(|b| b.status);
|
||||
|
||||
let label: &'static str = match status {
|
||||
Some(ServiceStatus::Implemented) => "implemented",
|
||||
Some(ServiceStatus::Partial) => "partial",
|
||||
Some(ServiceStatus::Stub) => "stub",
|
||||
None => {
|
||||
// Check explicit known-unsupported list
|
||||
match (module.to_ascii_lowercase().as_str(), symbol.as_str()) {
|
||||
(
|
||||
"api-ms-win-core-processthreads-l1-1-0.dll",
|
||||
"CreateThread" | "ResumeThread" | "SuspendThread" | "TerminateProcess",
|
||||
)
|
||||
| (
|
||||
"api-ms-win-core-synch-l1-1-0.dll",
|
||||
"WaitForSingleObject" | "WaitForSingleObjectEx",
|
||||
)
|
||||
| ("api-ms-win-core-synch-l1-2-1.dll", "WaitForMultipleObjects")
|
||||
| ("api-ms-win-core-rtlsupport-l1-1-0.dll", "RtlVirtualUnwind") => {
|
||||
"unsupported"
|
||||
}
|
||||
_ => "missing",
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
*counts.entry(label).or_default() += 1;
|
||||
total += 1;
|
||||
by_module
|
||||
.entry(module.to_ascii_lowercase())
|
||||
.or_default()
|
||||
.push((symbol, is_registered, status));
|
||||
}
|
||||
|
||||
// Build the refreshed import_backlog.md.
|
||||
let mut md = String::new();
|
||||
let _ = writeln!(md, "# BetterXen import compatibility backlog");
|
||||
let _ = writeln!(md);
|
||||
let _ = writeln!(
|
||||
md,
|
||||
"Generated by `betterxen imports sync`. Do not edit manually."
|
||||
);
|
||||
let _ = writeln!(
|
||||
md,
|
||||
"Re-run after adding service handlers to refresh this file."
|
||||
);
|
||||
let _ = writeln!(md);
|
||||
let _ = writeln!(md, "## Summary");
|
||||
let _ = writeln!(md);
|
||||
let _ = writeln!(md, "| Status | Count |");
|
||||
let _ = writeln!(md, "| --- | ---: |");
|
||||
let _ = writeln!(md, "| **Total** | {total} |");
|
||||
for (label, count) in &counts {
|
||||
let _ = writeln!(md, "| {label} | {count} |");
|
||||
}
|
||||
let _ = writeln!(md);
|
||||
|
||||
let _ = writeln!(md, "## Missing handlers (highest value first)");
|
||||
let _ = writeln!(md);
|
||||
|
||||
// Priority ordering: processthreads, synch, rtlsupport, memory, crt, file, graphics, other
|
||||
fn priority_key(module: &str) -> u8 {
|
||||
if module.contains("processthreads") || module.contains("core-handle") {
|
||||
1
|
||||
} else if module.contains("fibers") || module.contains("tls") {
|
||||
2
|
||||
} else if module.contains("core-synch") {
|
||||
3
|
||||
} else if module.contains("core-profile") || module.contains("core-sysinfo") {
|
||||
4
|
||||
} else if module.contains("core-memory")
|
||||
|| module.contains("core-heap")
|
||||
|| module == "xmem.dll"
|
||||
{
|
||||
5
|
||||
} else if module.starts_with("api-ms-win-crt-")
|
||||
|| module.contains("vcruntime")
|
||||
|| module.contains("libraryloader")
|
||||
{
|
||||
6
|
||||
} else if module.contains("rtlsupport") || module.contains("errorhandling") {
|
||||
7
|
||||
} else if module.contains("core-file") || module == "xcrdapi.dll" {
|
||||
8
|
||||
} else {
|
||||
9
|
||||
}
|
||||
}
|
||||
|
||||
// Collect missing/unsupported into a prioritized list.
|
||||
let mut missing_entries: Vec<(u8, String, String)> = Vec::new();
|
||||
for (module, symbols) in &by_module {
|
||||
for (symbol, is_registered, _status) in symbols {
|
||||
if !is_registered {
|
||||
missing_entries.push((priority_key(module), module.clone(), symbol.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
missing_entries.sort();
|
||||
|
||||
let mut prev_priority = 255u8;
|
||||
for (priority, module, symbol) in &missing_entries {
|
||||
if *priority != prev_priority {
|
||||
let _ = writeln!(md, "### Priority {priority}");
|
||||
let _ = writeln!(md);
|
||||
prev_priority = *priority;
|
||||
}
|
||||
let _ = writeln!(md, "- `{module}!{symbol}`");
|
||||
}
|
||||
|
||||
let _ = writeln!(md);
|
||||
let _ = writeln!(md, "## Registered handlers");
|
||||
let _ = writeln!(md);
|
||||
let _ = writeln!(md, "| Module | Symbol | Status |");
|
||||
let _ = writeln!(md, "| --- | --- | --- |");
|
||||
// Enumerate canonical registrations sorted by module, symbol
|
||||
let mut registered: BTreeSet<(String, String, &'static str)> = BTreeSet::new();
|
||||
for (module, symbol, status) in registry.iter_registered() {
|
||||
registered.insert((
|
||||
module.to_ascii_lowercase(),
|
||||
symbol.to_string(),
|
||||
status.as_str(),
|
||||
));
|
||||
}
|
||||
for (module, symbol, status) in ®istered {
|
||||
let _ = writeln!(md, "| `{module}` | `{symbol}` | {status} |");
|
||||
}
|
||||
|
||||
let out_path = std::path::Path::new(report_dir).join("import_backlog.md");
|
||||
let existing = std::fs::read_to_string(&out_path).unwrap_or_default();
|
||||
let changed = existing != md;
|
||||
|
||||
if !check_mode {
|
||||
std::fs::write(&out_path, &md)?;
|
||||
println!(
|
||||
" Total imports: {total} | implemented: {} | partial: {} | stub: {} | missing: {}",
|
||||
counts.get("implemented").copied().unwrap_or(0),
|
||||
counts.get("partial").copied().unwrap_or(0),
|
||||
counts.get("stub").copied().unwrap_or(0),
|
||||
counts.get("missing").copied().unwrap_or(0),
|
||||
);
|
||||
}
|
||||
|
||||
Ok(changed)
|
||||
}
|
||||
|
||||
use std::fmt::Write as _;
|
||||
@@ -1,370 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
use std::error::Error;
|
||||
use std::ffi::OsString;
|
||||
use std::fs::{self, File};
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, ExitCode, Stdio};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use xenora_loader::startup::{StartupEvent, StartupLayout, run_synthetic_startup_with_observer};
|
||||
use xenora_loader::{
|
||||
ExitReason, ImportRegistry, Register, ServicesState, SystemClock, register_standard_services,
|
||||
};
|
||||
use xenora_metal::NativeCompute;
|
||||
use xenora_shader::{Architecture, PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics};
|
||||
|
||||
const FIXTURE: &[u8] = include_bytes!("../../../fixtures/pe/trusted-runner.exe");
|
||||
const SERVICES_FIXTURE: &[u8] = include_bytes!("../../../fixtures/pe/runtime-services.exe");
|
||||
const WALL_LIMIT: Duration = Duration::from_secs(15);
|
||||
const DEFAULT_STEPS: usize = 100;
|
||||
const MAX_STEPS: usize = 10_000;
|
||||
const IMAGE_BASE: u64 = 0x150000000;
|
||||
const TICKET_ADDRESS: u64 = IMAGE_BASE + 0x3000;
|
||||
const TICKET: u64 = 17;
|
||||
const DRAW_RESULT: u64 = 0x42;
|
||||
const EXTENT: [usize; 2] = [4, 3];
|
||||
const EXPECTED_PIXEL: [u8; 4] = [255, 0, 0, 255];
|
||||
const USAGE: &str = "usage: betterxen run --pe <trusted-fixture> --experimental [--trace] [--metal-hud] [--max-steps <1..=10000>]";
|
||||
|
||||
struct Options {
|
||||
path: PathBuf,
|
||||
max_steps: usize,
|
||||
worker: bool,
|
||||
trace: bool,
|
||||
hud: bool,
|
||||
}
|
||||
|
||||
impl Options {
|
||||
fn parse(args: impl IntoIterator<Item = OsString>) -> Result<Self, String> {
|
||||
let mut args = args.into_iter();
|
||||
let mut path = None;
|
||||
let mut max_steps = None;
|
||||
let (mut experimental, mut trace, mut hud, mut worker) = (false, false, false, false);
|
||||
while let Some(arg) = args.next() {
|
||||
match arg.to_str() {
|
||||
Some("--pe") if path.is_none() => {
|
||||
path = Some(PathBuf::from(args.next().ok_or("missing --pe path")?));
|
||||
}
|
||||
Some("--max-steps") if max_steps.is_none() => {
|
||||
max_steps = Some(
|
||||
args.next()
|
||||
.and_then(|arg| arg.to_str()?.parse::<usize>().ok())
|
||||
.filter(|steps| (1..=MAX_STEPS).contains(steps))
|
||||
.ok_or("--max-steps must be in 1..=10000")?,
|
||||
);
|
||||
}
|
||||
Some("--experimental") if !experimental => experimental = true,
|
||||
Some("--trace") if !trace => trace = true,
|
||||
Some("--metal-hud") if !hud => hud = true,
|
||||
Some("--worker") if !worker => worker = true,
|
||||
_ => return Err(format!("unknown or repeated run argument {arg:?}")),
|
||||
}
|
||||
}
|
||||
if !experimental {
|
||||
return Err("run requires --experimental".into());
|
||||
}
|
||||
Ok(Self {
|
||||
path: path.ok_or("missing --pe path")?,
|
||||
max_steps: max_steps.unwrap_or(DEFAULT_STEPS),
|
||||
worker,
|
||||
trace,
|
||||
hud,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn command(args: impl IntoIterator<Item = OsString>) -> ExitCode {
|
||||
let options = match Options::parse(args) {
|
||||
Ok(options) => options,
|
||||
Err(error) => {
|
||||
eprintln!("{error}\n{USAGE}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
};
|
||||
let result = if options.worker {
|
||||
run_worker(&options).map(|()| ExitCode::SUCCESS)
|
||||
} else {
|
||||
launch_worker(&options)
|
||||
};
|
||||
match result {
|
||||
Ok(code) => code,
|
||||
Err(error) => {
|
||||
eprintln!("run failed: {error}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn launch_worker(options: &Options) -> Result<ExitCode, Box<dyn Error>> {
|
||||
let started = Instant::now();
|
||||
let mut child = Command::new(std::env::current_exe()?)
|
||||
.args([
|
||||
"run",
|
||||
"--experimental",
|
||||
"--trace",
|
||||
"--metal-hud",
|
||||
"--worker",
|
||||
])
|
||||
.arg("--max-steps")
|
||||
.arg(options.max_steps.to_string())
|
||||
.arg("--pe")
|
||||
.arg(&options.path)
|
||||
.stdin(Stdio::null())
|
||||
.spawn()?;
|
||||
loop {
|
||||
match child.try_wait() {
|
||||
Ok(Some(status)) => {
|
||||
return match status.code() {
|
||||
Some(code) => Ok(ExitCode::from(u8::try_from(code)?)),
|
||||
None => Err(format!("worker terminated: {status}").into()),
|
||||
};
|
||||
}
|
||||
Ok(None) if started.elapsed() < WALL_LIMIT => {
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
status => {
|
||||
let _ = child.kill();
|
||||
child.wait()?;
|
||||
status?;
|
||||
return Err("experimental worker exceeded its 15 second wall deadline".into());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn verify_fixture(path: &Path) -> Result<&'static [u8], Box<dyn Error>> {
|
||||
let valid_metadata =
|
||||
|metadata: fs::Metadata| metadata.is_file() && metadata.len() == FIXTURE.len() as u64;
|
||||
let rejection =
|
||||
"execution denied: input must match an embedded trusted PE fixture byte for byte";
|
||||
// Check size before opening and again on the descriptor. Bound the read
|
||||
// even if another process changes the file after the metadata checks.
|
||||
if !valid_metadata(fs::metadata(path)?) {
|
||||
return Err(rejection.into());
|
||||
}
|
||||
let file = File::open(path)?;
|
||||
if !valid_metadata(file.metadata()?) {
|
||||
return Err(rejection.into());
|
||||
}
|
||||
let mut bytes = Vec::with_capacity(FIXTURE.len() + 1);
|
||||
file.take(FIXTURE.len() as u64 + 1)
|
||||
.read_to_end(&mut bytes)?;
|
||||
[FIXTURE, SERVICES_FIXTURE]
|
||||
.into_iter()
|
||||
.find(|fixture| *fixture == bytes)
|
||||
.ok_or_else(|| rejection.into())
|
||||
}
|
||||
|
||||
fn run_worker(options: &Options) -> Result<(), Box<dyn Error>> {
|
||||
std::thread::Builder::new()
|
||||
.name("xenora-deadline".into())
|
||||
.spawn(|| {
|
||||
std::thread::sleep(WALL_LIMIT);
|
||||
// The supervisor also enforces this deadline. The worker retains
|
||||
// its own deadline if it is invoked directly.
|
||||
std::process::exit(124);
|
||||
})?;
|
||||
let fixture = verify_fixture(&options.path)?;
|
||||
let (name, ticket, bound_imports) = if fixture == SERVICES_FIXTURE {
|
||||
("runtime-services", 23, 3)
|
||||
} else {
|
||||
("trusted-runner", TICKET, 1)
|
||||
};
|
||||
if options.trace {
|
||||
println!(
|
||||
"trace fixture={name} policy=exact-bytes entry_step_limit={} wall_limit_ms=15000",
|
||||
options.max_steps
|
||||
);
|
||||
}
|
||||
|
||||
let capture = Arc::new(Mutex::new(None));
|
||||
let draw_capture = Arc::clone(&capture);
|
||||
let mut imports = ImportRegistry::new();
|
||||
register_standard_services(
|
||||
&mut imports,
|
||||
Arc::new(ServicesState::new(Arc::new(SystemClock))),
|
||||
);
|
||||
let trace = options.trace;
|
||||
imports.register("xenora.dll", "fixture_draw", move |args, _, memory| {
|
||||
let ticket_address = args.get(0, memory).map_err(ExitReason::MemoryFault)?;
|
||||
let mut result = draw_capture
|
||||
.lock()
|
||||
.map_err(|_| ExitReason::IllegalInstruction(0xff))?;
|
||||
if result.is_some() {
|
||||
return Err(ExitReason::IllegalInstruction(0xff));
|
||||
}
|
||||
if ticket_address != TICKET_ADDRESS
|
||||
|| memory
|
||||
.read_u64(ticket_address)
|
||||
.map_err(ExitReason::MemoryFault)?
|
||||
!= ticket
|
||||
{
|
||||
*result = Some(Err(
|
||||
"guest draw ticket differed from the expected value".into()
|
||||
));
|
||||
return Err(ExitReason::IllegalInstruction(0xff));
|
||||
}
|
||||
if trace {
|
||||
println!("trace import=xenora.dll!fixture_draw tls_ticket={ticket}");
|
||||
}
|
||||
let frame = draw().map_err(|error| error.to_string());
|
||||
let drawn = frame.is_ok();
|
||||
*result = Some(frame);
|
||||
if drawn {
|
||||
Ok(DRAW_RESULT)
|
||||
} else {
|
||||
Err(ExitReason::IllegalInstruction(0xff))
|
||||
}
|
||||
});
|
||||
|
||||
let started = Instant::now();
|
||||
// Use only the embedded snapshot. The file is solely an exact-byte gate.
|
||||
let startup = run_synthetic_startup_with_observer(
|
||||
fixture,
|
||||
StartupLayout {
|
||||
image_base: IMAGE_BASE,
|
||||
stack_top: 0x200010000,
|
||||
tls_base: 0x300000000,
|
||||
},
|
||||
imports,
|
||||
options.max_steps,
|
||||
|event| {
|
||||
if options.trace {
|
||||
trace_startup(event);
|
||||
}
|
||||
},
|
||||
)?;
|
||||
let host_ms = started.elapsed().as_secs_f64() * 1000.0;
|
||||
let result = capture
|
||||
.lock()
|
||||
.map_err(|_| "fixture draw result lock failed")?
|
||||
.take();
|
||||
let exit = startup.execution.exit_reason;
|
||||
let rax = startup.execution.final_state.get(Register::Rax);
|
||||
if options.trace {
|
||||
println!(
|
||||
"trace stage=exit entry_steps={} exit={exit:?} rax={rax:#x}",
|
||||
startup.execution.instructions_executed,
|
||||
);
|
||||
}
|
||||
if let Some(Err(error)) = &result {
|
||||
return Err(format!("fixture draw failed: {error}").into());
|
||||
}
|
||||
if exit != ExitReason::Halt {
|
||||
return Err(exit.into());
|
||||
}
|
||||
if startup.relocations.applied_dir64 != 4
|
||||
|| startup.bound_imports != bound_imports
|
||||
|| startup.tls_callbacks != 1
|
||||
|| rax != DRAW_RESULT
|
||||
{
|
||||
return Err("trusted fixture startup or result differs from the expected values".into());
|
||||
}
|
||||
let frame = result.ok_or("guest halted without a draw")??;
|
||||
if options.trace {
|
||||
println!(
|
||||
"trace stage=framebuffer extent={}x{} verified_pixels={}",
|
||||
EXTENT[0],
|
||||
EXTENT[1],
|
||||
EXTENT[0] * EXTENT[1],
|
||||
);
|
||||
}
|
||||
if options.hud {
|
||||
let gpu_time = frame.gpu_seconds.map_or_else(
|
||||
|| "unavailable".to_owned(),
|
||||
|seconds| format!("{:.3}", seconds * 1000.0),
|
||||
);
|
||||
println!(
|
||||
"Metal HUD | device={} | offscreen={}x{} | draw_calls=1 | verified_pixels={} | host_render_readback_ms={:.3} | host_startup_ms={host_ms:.3} | gpu_command_ms={gpu_time}",
|
||||
frame.device,
|
||||
EXTENT[0],
|
||||
EXTENT[1],
|
||||
EXTENT[0] * EXTENT[1],
|
||||
frame.host_render_readback_ms,
|
||||
);
|
||||
let metrics = startup.dbt_metrics;
|
||||
println!(
|
||||
"DBT | entry_steps={} | native_steps_tls_and_entry={} | blocks_compiled={} | native_bytes={} | native_dispatches={} | service_calls={} | interpreter_fallbacks={}",
|
||||
startup.execution.instructions_executed,
|
||||
metrics.instructions_executed,
|
||||
metrics.blocks_compiled,
|
||||
metrics.native_bytes_emitted,
|
||||
metrics.dbt_dispatches,
|
||||
metrics.service_calls,
|
||||
metrics.interpreter_fallbacks,
|
||||
);
|
||||
}
|
||||
println!("Trusted fixture completed one verified offscreen Metal draw.");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn trace_startup(event: StartupEvent) {
|
||||
match event {
|
||||
StartupEvent::Parsed {
|
||||
sections,
|
||||
entry_rva,
|
||||
} => {
|
||||
println!("trace stage=parsed sections={sections} entry_rva={entry_rva:#x}");
|
||||
}
|
||||
StartupEvent::Mapped { entry_va } => {
|
||||
println!("trace stage=mapped base={IMAGE_BASE:#x} entry_va={entry_va:#x}");
|
||||
}
|
||||
StartupEvent::Relocated { applied_dir64 } => {
|
||||
println!("trace stage=relocated dir64_applied={applied_dir64}");
|
||||
}
|
||||
StartupEvent::ImportsBound { count } => {
|
||||
println!("trace stage=imports_bound bound_imports={count}");
|
||||
}
|
||||
StartupEvent::TlsCompleted {
|
||||
callbacks,
|
||||
native_steps,
|
||||
} => {
|
||||
println!(
|
||||
"trace stage=tls_completed tls_callbacks={callbacks} native_steps={native_steps}"
|
||||
);
|
||||
}
|
||||
StartupEvent::Entering { step_limit } => {
|
||||
println!("trace stage=entry step_limit={step_limit}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Frame {
|
||||
device: String,
|
||||
host_render_readback_ms: f64,
|
||||
gpu_seconds: Option<f64>,
|
||||
}
|
||||
|
||||
fn draw() -> Result<Frame, Box<dyn Error>> {
|
||||
let shader = compile_graphics(
|
||||
Architecture::Gfx1030,
|
||||
include_bytes!("../../../fixtures/rdna2/x9-constant-vs.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/x9-constant-ps.bin"),
|
||||
)?;
|
||||
let gpu = NativeCompute::new()?;
|
||||
let started = Instant::now();
|
||||
let (pixels, gpu_seconds) = gpu.render_rgba8_profiled(
|
||||
&shader.msl,
|
||||
[VERTEX_ENTRY_POINT, PIXEL_ENTRY_POINT],
|
||||
&[
|
||||
[-1.0, -1.0, 0.5, 1.0],
|
||||
[3.0, -1.0, 0.5, 1.0],
|
||||
[-1.0, 3.0, 0.5, 1.0],
|
||||
],
|
||||
&[[0.0; 4]; 3],
|
||||
EXTENT,
|
||||
[19, 43, 93, 251],
|
||||
)?;
|
||||
let host_render_readback_ms = started.elapsed().as_secs_f64() * 1000.0;
|
||||
if pixels != EXPECTED_PIXEL.repeat(EXTENT[0] * EXTENT[1]) {
|
||||
return Err("offscreen readback did not match opaque red at every pixel".into());
|
||||
}
|
||||
Ok(Frame {
|
||||
device: gpu.device_name().to_owned(),
|
||||
host_render_readback_ms,
|
||||
gpu_seconds,
|
||||
})
|
||||
}
|
||||
@@ -1,288 +0,0 @@
|
||||
//! `betterxen shaders`: instruction inventory and stream inspection.
|
||||
|
||||
use std::process::ExitCode;
|
||||
|
||||
use xenora_decoder::{Architecture, SEMANTIC_FORMS, decode_at};
|
||||
use xenora_isa::meta::{self, EncodingFamily, FORMS, identify};
|
||||
|
||||
const USAGE: &str = "usage: betterxen shaders <coverage [--json] | inspect <gfx1030.bin>>";
|
||||
|
||||
pub fn command(args: &[String]) -> ExitCode {
|
||||
match args.first().map(String::as_str) {
|
||||
Some("coverage") => coverage(args.get(1).map(String::as_str) == Some("--json")),
|
||||
Some("inspect") => match args.get(1) {
|
||||
Some(path) => inspect(path),
|
||||
None => usage(),
|
||||
},
|
||||
_ => usage(),
|
||||
}
|
||||
}
|
||||
|
||||
fn usage() -> ExitCode {
|
||||
eprintln!("{USAGE}");
|
||||
ExitCode::from(2)
|
||||
}
|
||||
|
||||
fn semantic(family: EncodingFamily) -> usize {
|
||||
SEMANTIC_FORMS
|
||||
.iter()
|
||||
.filter(|(_, form_family)| *form_family == family)
|
||||
.count()
|
||||
}
|
||||
|
||||
/// Per-family counts. "Discovered" forms come from AMD's XML and are identified
|
||||
/// with their length; "semantic" forms decode into executable instructions.
|
||||
/// Reference, Metal and native GPU evidence per form stays in docs/status.toml.
|
||||
fn coverage(json: bool) -> ExitCode {
|
||||
print!("{}", coverage_report(json));
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
|
||||
fn coverage_report(json: bool) -> String {
|
||||
use std::fmt::Write as _;
|
||||
let rows: Vec<_> = meta::inventory()
|
||||
.into_iter()
|
||||
.map(|(family, discovered)| (family, discovered, semantic(family)))
|
||||
.collect();
|
||||
let total: usize = rows.iter().map(|row| row.1).sum();
|
||||
let supported: usize = rows.iter().map(|row| row.2).sum();
|
||||
let mut out = String::new();
|
||||
if json {
|
||||
let families: Vec<String> = rows
|
||||
.iter()
|
||||
.map(|(family, discovered, semantic)| {
|
||||
format!(
|
||||
"{{\"family\":\"{}\",\"discovered\":{discovered},\"semantic\":{semantic}}}",
|
||||
family.name()
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
writeln!(
|
||||
out,
|
||||
"{{\"architecture\":\"gfx1030\",\"source_sha256\":\"{}\",\"discovered\":{total},\"semantic\":{supported},\"families\":[{}]}}",
|
||||
meta::SOURCE_SHA256,
|
||||
families.join(",")
|
||||
)
|
||||
.unwrap();
|
||||
} else {
|
||||
writeln!(
|
||||
out,
|
||||
"{:<10} {:>10} {:>9}",
|
||||
"family", "discovered", "semantic"
|
||||
)
|
||||
.unwrap();
|
||||
for (family, discovered, semantic) in &rows {
|
||||
writeln!(out, "{:<10} {discovered:>10} {semantic:>9}", family.name()).unwrap();
|
||||
}
|
||||
writeln!(out, "{:<10} {total:>10} {supported:>9}", "total").unwrap();
|
||||
writeln!(
|
||||
out,
|
||||
"Semantic forms decode for the operand subsets in docs/status.toml only."
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn inspect(path: &str) -> ExitCode {
|
||||
let bytes = match std::fs::read(path) {
|
||||
Ok(bytes) => bytes,
|
||||
Err(error) => {
|
||||
eprintln!("{path}: {error}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
let listing = listing(&bytes);
|
||||
for row in &listing.rows {
|
||||
println!("{row}");
|
||||
}
|
||||
if let Some(failure) = listing.failure {
|
||||
println!("{failure}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
println!(
|
||||
"{} instructions inspected against {} gfx1030 forms; {} without semantic decoding",
|
||||
listing.rows.len(),
|
||||
FORMS.len(),
|
||||
listing.unsupported
|
||||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
|
||||
/// The printed rows of `betterxen shaders inspect`, the number of rows that do
|
||||
/// not decode into executable instructions and the identification failure
|
||||
/// that ended the stream early, if any.
|
||||
struct Listing {
|
||||
rows: Vec<String>,
|
||||
unsupported: usize,
|
||||
failure: Option<String>,
|
||||
}
|
||||
|
||||
fn listing(bytes: &[u8]) -> Listing {
|
||||
let mut listing = Listing {
|
||||
rows: Vec::new(),
|
||||
unsupported: 0,
|
||||
failure: None,
|
||||
};
|
||||
// Identify every instruction first: a branch target is valid only if it
|
||||
// lands on one of these boundaries, which no single instruction can show.
|
||||
let mut forms = Vec::new();
|
||||
let mut offset = 0;
|
||||
while offset < bytes.len() {
|
||||
match identify(&bytes[offset..]) {
|
||||
Ok(found) => {
|
||||
forms.push((offset, found));
|
||||
offset += found.len;
|
||||
}
|
||||
Err(error) => {
|
||||
listing.failure = Some(format!("{offset:#06x} decode failure: {error}"));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
let boundary = |target: usize| forms.binary_search_by_key(&target, |form| form.0).is_ok();
|
||||
// Past the last identified instruction the boundaries are unknown.
|
||||
let identified = forms
|
||||
.last()
|
||||
.map_or(0, |&(offset, found)| offset + found.len);
|
||||
for &(offset, found) in &forms {
|
||||
let instruction = &bytes[offset..offset + found.len];
|
||||
let words: Vec<String> = instruction
|
||||
.chunks(4)
|
||||
.map(|chunk| format!("{:08x}", u32::from_le_bytes(chunk.try_into().unwrap())))
|
||||
.collect();
|
||||
let status = match decode_at(Architecture::Gfx1030, &bytes[..offset + found.len], offset) {
|
||||
Ok(decoded) => match decoded.branch_target() {
|
||||
Some(target) if listing.failure.is_some() && target >= identified => {
|
||||
format!("branch target {target:#04x} unverified: stream not identified there")
|
||||
}
|
||||
Some(target) if !boundary(target) => {
|
||||
format!("invalid branch target {target:#04x}")
|
||||
}
|
||||
_ => "semantic".to_owned(),
|
||||
},
|
||||
Err(error) if SEMANTIC_FORMS.contains(&(found.form.name, found.form.family)) => {
|
||||
format!("unsupported operands: {error}")
|
||||
}
|
||||
Err(_) => "unsupported instruction semantics".to_owned(),
|
||||
};
|
||||
if status != "semantic" {
|
||||
listing.unsupported += 1;
|
||||
}
|
||||
listing.rows.push(format!(
|
||||
"{offset:#06x} {:<8} {:<28} {:<26} {status}",
|
||||
found.form.family.name(),
|
||||
found.form.name.to_ascii_lowercase(),
|
||||
words.join(" ")
|
||||
));
|
||||
}
|
||||
listing
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{coverage_report, listing};
|
||||
use xenora_decoder::SEMANTIC_FORMS;
|
||||
use xenora_isa::meta::{EncodingFamily, FORMS};
|
||||
|
||||
#[test]
|
||||
fn coverage_totals_match_the_generated_table() {
|
||||
let json = coverage_report(true);
|
||||
assert!(json.starts_with("{\"architecture\":\"gfx1030\""), "{json}");
|
||||
assert!(json.ends_with("}]}\n"), "{json}");
|
||||
assert_eq!(json.matches('{').count(), json.matches('}').count());
|
||||
let totals = format!(
|
||||
"\"discovered\":{},\"semantic\":{},\"families\":[",
|
||||
FORMS.len(),
|
||||
SEMANTIC_FORMS.len()
|
||||
);
|
||||
assert!(json.contains(&totals), "{json}");
|
||||
let families: Vec<usize> = json
|
||||
.split("{\"family\":")
|
||||
.skip(1)
|
||||
.map(|row| {
|
||||
let count = row.split("\"discovered\":").nth(1).unwrap();
|
||||
count[..count.find(',').unwrap()].parse().unwrap()
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(families.len(), EncodingFamily::ALL.len());
|
||||
assert_eq!(families.iter().sum::<usize>(), FORMS.len());
|
||||
let text = coverage_report(false);
|
||||
let total = format!(
|
||||
"{:<10} {:>10} {:>9}\n",
|
||||
"total",
|
||||
FORMS.len(),
|
||||
SEMANTIC_FORMS.len()
|
||||
);
|
||||
assert!(text.contains(&total), "{text}");
|
||||
}
|
||||
|
||||
fn program(words: &[u32]) -> Vec<u8> {
|
||||
words.iter().flat_map(|word| word.to_le_bytes()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn branches_in_a_valid_program_are_semantic() {
|
||||
let fixture = include_bytes!("../../../fixtures/rdna2/bitwise-branch.bin");
|
||||
let listing = listing(fixture);
|
||||
assert_eq!(listing.failure, None);
|
||||
assert_eq!(listing.rows.len(), 15);
|
||||
let branches: Vec<_> = listing
|
||||
.rows
|
||||
.iter()
|
||||
.filter(|row| row.contains("branch"))
|
||||
.collect();
|
||||
assert_eq!(branches.len(), 3);
|
||||
for row in &branches {
|
||||
assert!(row.ends_with(" semantic"), "{row}");
|
||||
}
|
||||
assert_eq!(listing.unsupported, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn targets_past_an_identification_failure_are_unverified() {
|
||||
// s_branch 1 targets 0x08; 0xbfff0000 is not a gfx1030 form, so
|
||||
// nothing past 0x04 is identified; s_endpgm.
|
||||
let listing = listing(&program(&[0xbf82_0001, 0xbfff_0000, 0xbf81_0000]));
|
||||
assert!(listing.failure.as_deref().unwrap().starts_with("0x0004"));
|
||||
assert_eq!(listing.rows.len(), 1);
|
||||
assert!(
|
||||
listing.rows[0].ends_with("branch target 0x08 unverified: stream not identified there"),
|
||||
"{}",
|
||||
listing.rows[0]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_fixture_is_fully_semantic() {
|
||||
let listing = listing(include_bytes!("../../../fixtures/rdna2/add.bin"));
|
||||
assert_eq!(listing.failure, None);
|
||||
assert_eq!(listing.rows.len(), 7);
|
||||
assert_eq!(listing.unsupported, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn branch_targets_are_checked_against_the_whole_stream() {
|
||||
// s_branch 1 skips one word; s_cbranch_scc0 1 lands inside the
|
||||
// two-word v_mov_b32 literal form; s_endpgm.
|
||||
let listing = listing(&program(&[
|
||||
0xbf82_0001,
|
||||
0xbf84_0001,
|
||||
0x7e04_02ff,
|
||||
0x00ff_00ff,
|
||||
0xbf81_0000,
|
||||
]));
|
||||
assert_eq!(listing.failure, None);
|
||||
assert!(
|
||||
listing.rows[0].ends_with(" semantic"),
|
||||
"{}",
|
||||
listing.rows[0]
|
||||
);
|
||||
assert!(
|
||||
listing.rows[1].ends_with("invalid branch target 0x0c"),
|
||||
"{}",
|
||||
listing.rows[1]
|
||||
);
|
||||
assert_eq!(listing.unsupported, 1);
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Default report folder of `betterxen probe` and `betterxen imports sync`.
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
#[test]
|
||||
fn probe_and_sync_use_the_same_default_folder() {
|
||||
let fixture = concat!(
|
||||
env!("CARGO_MANIFEST_DIR"),
|
||||
"/../../fixtures/pe/delay-imports.exe"
|
||||
);
|
||||
let folder = std::env::temp_dir().join(format!("xenora-default-{}", std::process::id()));
|
||||
std::fs::create_dir(&folder).unwrap();
|
||||
for arguments in [&["probe", "--pe", fixture][..], &["imports", "sync"]] {
|
||||
let status = Command::new(env!("CARGO_BIN_EXE_betterxen"))
|
||||
.args(arguments)
|
||||
.current_dir(&folder)
|
||||
.status()
|
||||
.unwrap();
|
||||
assert!(status.success(), "{arguments:?}");
|
||||
}
|
||||
let written = ["imports.csv", "import_backlog.md"]
|
||||
.map(|name| folder.join("diagnostics/probe").join(name).is_file());
|
||||
std::fs::remove_dir_all(folder).unwrap();
|
||||
assert_eq!(written, [true, true]);
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! `betterxen imports sync` over a probe report that lists delay-loaded imports.
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
#[test]
|
||||
fn backlog_leaves_out_delay_loaded_imports() {
|
||||
// `fixtures/pe/delay-imports.py` writes two ordinary imports from
|
||||
// `fixture-ordinary.dll` and three delay-loaded ones from two other DLLs.
|
||||
let fixture = concat!(
|
||||
env!("CARGO_MANIFEST_DIR"),
|
||||
"/../../fixtures/pe/delay-imports.exe"
|
||||
);
|
||||
let report = std::env::temp_dir().join(format!("xenora-sync-delayed-{}", std::process::id()));
|
||||
let betterxen = |arguments: &[&str]| {
|
||||
let status = Command::new(env!("CARGO_BIN_EXE_betterxen"))
|
||||
.args(arguments)
|
||||
.arg("--report")
|
||||
.arg(&report)
|
||||
.status()
|
||||
.unwrap();
|
||||
assert!(status.success(), "{arguments:?}");
|
||||
};
|
||||
betterxen(&["probe", "--pe", fixture]);
|
||||
betterxen(&["imports", "sync"]);
|
||||
let listed = std::fs::read_to_string(report.join("imports.csv")).unwrap();
|
||||
let backlog = std::fs::read_to_string(report.join("import_backlog.md")).unwrap();
|
||||
std::fs::remove_dir_all(report).unwrap();
|
||||
|
||||
assert_eq!(listed.matches(",delayed,").count(), 3);
|
||||
assert!(backlog.contains("| **Total** | 2 |"), "{backlog}");
|
||||
assert!(backlog.contains("fixture-ordinary.dll"), "{backlog}");
|
||||
assert!(!backlog.contains("fixture-delay"), "{backlog}");
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! The import generator skips emitting an adapter for a symbol it classifies
|
||||
//! as a standard service, so every such classification must name a handler
|
||||
//! the standard loader registry actually provides.
|
||||
|
||||
use std::sync::Arc;
|
||||
use xenora_import_gen::{Classification, SymbolDb};
|
||||
use xenora_loader::import_table::ImportName;
|
||||
use xenora_loader::imports::{ImportRegistry, ServiceStatus};
|
||||
use xenora_loader::services::{MockClock, ServicesState, register_standard_services};
|
||||
|
||||
#[test]
|
||||
fn every_standard_service_classification_resolves_to_a_registered_handler() {
|
||||
let mut registry = ImportRegistry::new();
|
||||
let state = ServicesState::new(Arc::new(MockClock::new(0)));
|
||||
register_standard_services(&mut registry, Arc::new(state));
|
||||
|
||||
let db = SymbolDb::builtin();
|
||||
let mut checked = 0;
|
||||
let mut missing = Vec::new();
|
||||
for (module, symbol, class) in db.entries() {
|
||||
if !matches!(class, Classification::StandardService) {
|
||||
continue;
|
||||
}
|
||||
checked += 1;
|
||||
match registry.resolve(module, &ImportName::Name(symbol.to_string())) {
|
||||
Some(service) if service.status != ServiceStatus::Stub => {}
|
||||
_ => missing.push(format!("{module}!{symbol}")),
|
||||
}
|
||||
}
|
||||
assert!(missing.is_empty(), "unregistered: {missing:?}");
|
||||
assert!(checked > 100, "{checked}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registered_synchronization_services_are_not_classified_as_stubs() {
|
||||
let db = SymbolDb::builtin();
|
||||
for module in ["api-ms-win-core-synch-l1-1-0.dll", "kernel32.dll"] {
|
||||
for symbol in [
|
||||
"CreateSemaphoreW",
|
||||
"ReleaseSemaphore",
|
||||
"CreateMutexW",
|
||||
"EnterCriticalSection",
|
||||
"TryEnterCriticalSection",
|
||||
"AcquireSRWLockExclusive",
|
||||
] {
|
||||
assert!(
|
||||
matches!(
|
||||
db.get(module, symbol),
|
||||
Some(Classification::StandardService)
|
||||
),
|
||||
"{module}!{symbol}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
+130
-336
@@ -3,56 +3,15 @@
|
||||
use std::fmt;
|
||||
|
||||
pub use xenora_isa::{
|
||||
Architecture, CompareRelation, ExportTarget, Instruction, InterpolationPhase, ScalarAluOp,
|
||||
ScalarCompareOp, ScalarImmediateCompareOp, ScalarImmediateOp, ScalarSource, ScalarUnaryOp,
|
||||
SoppControlOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp, VectorCompareVop3Op,
|
||||
VectorSource, VectorSwapOp, VectorUnaryOp,
|
||||
Architecture, ExportTarget, Instruction, InterpolationPhase, ScalarSource, VectorSource,
|
||||
};
|
||||
use xenora_isa::{
|
||||
BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_WAITCNT_VSCNT, V_ADD_F32,
|
||||
V_INTERP_P1_F32, V_INTERP_P2_F32, V_MOV_B32, V_MUL_F32, VCC_LO,
|
||||
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_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,
|
||||
};
|
||||
|
||||
use xenora_isa::meta::EncodingFamily;
|
||||
use xenora_isa::semantics::{FORM_IDS, OperandRule};
|
||||
pub use xenora_isa::semantics::{VectorBinary, VectorLowering, VectorUnary, VectorVcc};
|
||||
|
||||
/// Metadata forms that [`decode`] turns into an [`Instruction`] for at least one
|
||||
/// 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); 10] = [
|
||||
("BUFFER_LOAD_DWORD", EncodingFamily::Mubuf),
|
||||
("BUFFER_STORE_DWORD", EncodingFamily::Mubuf),
|
||||
("EXP", EncodingFamily::Exp),
|
||||
("IMAGE_SAMPLE_LZ", EncodingFamily::Mimg),
|
||||
("S_WAITCNT_VSCNT", EncodingFamily::Sopk),
|
||||
("V_ADD_F32", EncodingFamily::Vop2),
|
||||
("V_INTERP_P1_F32", EncodingFamily::Vintrp),
|
||||
("V_INTERP_P2_F32", EncodingFamily::Vintrp),
|
||||
("V_MOV_B32", EncodingFamily::Vop1),
|
||||
("V_MUL_F32", EncodingFamily::Vop2),
|
||||
];
|
||||
|
||||
/// A successfully decoded instruction and its location in the input stream.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct DecodedInstruction {
|
||||
@@ -64,20 +23,6 @@ pub struct DecodedInstruction {
|
||||
pub instruction: Instruction,
|
||||
}
|
||||
|
||||
impl DecodedInstruction {
|
||||
/// Destination byte offset of a branch, from the start of the stream.
|
||||
#[must_use]
|
||||
pub fn branch_target(&self) -> Option<usize> {
|
||||
match self.instruction {
|
||||
Instruction::Branch { target }
|
||||
| Instruction::BranchSccZero { target }
|
||||
| Instruction::BranchExecZero { target }
|
||||
| Instruction::BranchVccZero { target } => Some(target),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for DecodedInstruction {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(formatter, "{:04x}: {}", self.offset, self.instruction)
|
||||
@@ -162,15 +107,26 @@ pub fn decode(
|
||||
architecture: Architecture,
|
||||
bytes: &[u8],
|
||||
) -> Result<Vec<DecodedInstruction>, DecodeError> {
|
||||
let decode_instruction = match architecture {
|
||||
Architecture::Gfx1030 => decode_gfx1030,
|
||||
};
|
||||
let mut result = Vec::new();
|
||||
let mut offset = 0;
|
||||
while offset < bytes.len() {
|
||||
let decoded = decode_at(architecture, bytes, offset)?;
|
||||
offset += usize::from(decoded.byte_len);
|
||||
result.push(decoded);
|
||||
let (instruction, byte_len) = decode_instruction(&bytes[offset..], offset)
|
||||
.map_err(|kind| DecodeError { offset, kind })?;
|
||||
result.push(DecodedInstruction {
|
||||
offset,
|
||||
byte_len,
|
||||
instruction,
|
||||
});
|
||||
offset += usize::from(byte_len);
|
||||
}
|
||||
for decoded in &result {
|
||||
if let Some(target) = decoded.branch_target()
|
||||
if let Instruction::Branch { target }
|
||||
| Instruction::BranchSccZero { target }
|
||||
| Instruction::BranchExecZero { target }
|
||||
| Instruction::BranchVccZero { target } = decoded.instruction
|
||||
&& result
|
||||
.binary_search_by_key(&target, |item| item.offset)
|
||||
.is_err()
|
||||
@@ -184,32 +140,6 @@ pub fn decode(
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Decodes the one instruction that starts at `offset` in `bytes`. Branch
|
||||
/// targets are stream offsets, but whether they land on an instruction
|
||||
/// boundary is left to the caller, which knows the rest of the stream.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns `offset` with a truncated instruction, unsupported opcode or
|
||||
/// unsupported form. An `offset` at or past the end is truncated.
|
||||
pub fn decode_at(
|
||||
architecture: Architecture,
|
||||
bytes: &[u8],
|
||||
offset: usize,
|
||||
) -> Result<DecodedInstruction, DecodeError> {
|
||||
let decode_instruction = match architecture {
|
||||
Architecture::Gfx1030 => decode_gfx1030,
|
||||
};
|
||||
let rest = bytes.get(offset..).unwrap_or_default();
|
||||
let (instruction, byte_len) =
|
||||
decode_instruction(rest, offset).map_err(|kind| DecodeError { offset, kind })?;
|
||||
Ok(DecodedInstruction {
|
||||
offset,
|
||||
byte_len,
|
||||
instruction,
|
||||
})
|
||||
}
|
||||
|
||||
fn word(bytes: &[u8], end: u8) -> Result<u32, DecodeErrorKind> {
|
||||
let end_index = usize::from(end);
|
||||
let Some(word) = bytes
|
||||
@@ -310,148 +240,103 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
|
||||
if V_MOV_B32.matches(first) {
|
||||
return move_b32(first, bytes);
|
||||
}
|
||||
// AMD RDNA 2 ISA guide 13.3.2: VDST occupies bits 17–24 and SRC0 bits 0–8.
|
||||
if let Some(op) = VectorUnaryOp::from_word(first) {
|
||||
let dst = (first >> 17) as u8;
|
||||
let (src, len) = vector_src0(first, bytes, op.assembly_name())?;
|
||||
return Ok((Instruction::VectorUnary { op, dst, src }, len));
|
||||
if V_ADD_NC_U32.matches(first) {
|
||||
let len = V_ADD_NC_U32.byte_len();
|
||||
let second = word(bytes, len)?;
|
||||
return Ok((add_u32(first, second)?, len));
|
||||
}
|
||||
if let Some(op) = VectorSwapOp::from_word(first) {
|
||||
if first & 0x100 == 0 {
|
||||
return Err(unsupported(
|
||||
op.assembly_name(),
|
||||
"expected a VGPR SRC0 for writeback",
|
||||
));
|
||||
}
|
||||
let dst = (first >> 17) as u8;
|
||||
let src = first as u8;
|
||||
return Ok((Instruction::VectorSwap { op, dst, src }, 4));
|
||||
}
|
||||
if let Some(op) = VectorCompareOp::from_word(first) {
|
||||
return vector_compare(op, first, bytes);
|
||||
}
|
||||
if let Some(op) = VectorCompareVop3Op::from_word(first) {
|
||||
let second = word(bytes, 8)?;
|
||||
let sdst = first as u8;
|
||||
if sdst > VCC_LO {
|
||||
return Err(unsupported(
|
||||
op.assembly_name(),
|
||||
"expected a destination of s0-s105 or vcc_lo",
|
||||
));
|
||||
}
|
||||
let (src0, src1) = vop3_vgpr2_sources(op.assembly_name(), first, second)?;
|
||||
return Ok((
|
||||
Instruction::VectorCompareVop3 {
|
||||
op,
|
||||
sdst,
|
||||
src0,
|
||||
src1,
|
||||
},
|
||||
8,
|
||||
));
|
||||
}
|
||||
if let Some(op) = VectorAluVop3Op::from_word(first) {
|
||||
let second = word(bytes, 8)?;
|
||||
return Ok((vop3_vgpr2(op, first, second)?, 8));
|
||||
}
|
||||
if let Some(op) = ScalarUnaryOp::from_word(first) {
|
||||
// SOP1: SSRC0 in bits 0-7, SDST in bits 16-22.
|
||||
let mnemonic = op.mnemonic();
|
||||
if S_MOV_B32.matches(first) {
|
||||
let dst = ((first >> 16) & 0x7f) as u8;
|
||||
match op.semantics().operands {
|
||||
OperandRule::Sop1Move if !matches!(dst, 0..=107 | 126..=127) => {
|
||||
return Err(unsupported(
|
||||
mnemonic,
|
||||
"expected a normal SGPR or EXEC/VCC destination",
|
||||
));
|
||||
}
|
||||
OperandRule::Sop1Sgpr if dst > 105 => {
|
||||
return Err(unsupported(mnemonic, "expected a normal SGPR destination"));
|
||||
}
|
||||
_ => {}
|
||||
if !matches!(dst, 0..=107 | 126..=127) {
|
||||
return Err(unsupported(
|
||||
"s_mov_b32",
|
||||
"expected a normal SGPR or EXEC/VCC destination",
|
||||
));
|
||||
}
|
||||
let (src, len) = scalar_source(first as u8, bytes, mnemonic)?;
|
||||
return Ok((Instruction::ScalarUnary { op, dst, src }, len));
|
||||
let (src, len) = scalar_source(first as u8, bytes, "s_mov_b32")?;
|
||||
return Ok((Instruction::ScalarMoveB32 { dst, src }, len));
|
||||
}
|
||||
if let Some(op) = ScalarCompareOp::from_word(first) {
|
||||
let mnemonic = op.mnemonic();
|
||||
if S_CMP_EQ_U32.matches(first) {
|
||||
let src0_bits = first as u8;
|
||||
let src1_bits = (first >> 8) as u8;
|
||||
if src0_bits == 255 && src1_bits == 255 {
|
||||
return Err(unsupported(
|
||||
mnemonic,
|
||||
"s_cmp_eq_u32",
|
||||
"only one source may select a literal",
|
||||
));
|
||||
}
|
||||
let (src0, len0) = scalar_source(src0_bits, bytes, mnemonic)?;
|
||||
let (src1, len1) = scalar_source(src1_bits, bytes, mnemonic)?;
|
||||
let (src0, len0) = scalar_source(src0_bits, bytes, "s_cmp_eq_u32")?;
|
||||
let (src1, len1) = scalar_source(src1_bits, bytes, "s_cmp_eq_u32")?;
|
||||
return Ok((
|
||||
Instruction::ScalarCompare { op, src0, src1 },
|
||||
Instruction::ScalarCompareEqU32 { src0, src1 },
|
||||
len0.max(len1),
|
||||
));
|
||||
}
|
||||
if let Some(op) = ScalarImmediateOp::from_word(first) {
|
||||
// SOPK: SIMM16 in bits 0-15, SDST in bits 16-22; the word has no literal.
|
||||
let dst = ((first >> 16) & 0x7f) as u8;
|
||||
if dst > 105 {
|
||||
return Err(unsupported(
|
||||
op.mnemonic(),
|
||||
"expected a normal SGPR destination",
|
||||
));
|
||||
}
|
||||
let simm16 = first as u16;
|
||||
return Ok((Instruction::ScalarImmediate { op, dst, simm16 }, 4));
|
||||
if S_BRANCH.matches(first) {
|
||||
let target = branch_target(first, offset, "s_branch")?;
|
||||
return Ok((Instruction::Branch { target }, S_BRANCH.byte_len()));
|
||||
}
|
||||
if let Some(op) = ScalarImmediateCompareOp::from_word(first) {
|
||||
let src = ((first >> 16) & 0x7f) as u8;
|
||||
if src > 105 {
|
||||
return Err(unsupported(op.mnemonic(), "expected a normal SGPR operand"));
|
||||
}
|
||||
let simm16 = first as u16;
|
||||
return Ok((Instruction::ScalarImmediateCompare { op, src, simm16 }, 4));
|
||||
}
|
||||
if let Some(op) = SoppControlOp::from_word(first) {
|
||||
let immediate = first as u16;
|
||||
if op
|
||||
.required_immediate()
|
||||
.is_some_and(|exact| immediate != exact)
|
||||
{
|
||||
let detail = if op == SoppControlOp::EndProgram {
|
||||
"expected zero immediate"
|
||||
} else {
|
||||
"expected vmcnt(0) alone"
|
||||
};
|
||||
return Err(unsupported(op.mnemonic(), detail));
|
||||
}
|
||||
let instruction = op.decode(|| branch_target(immediate, offset, op.mnemonic()))?;
|
||||
return Ok((instruction, 4));
|
||||
}
|
||||
if let Some(op) = ScalarAluOp::from_word(first) {
|
||||
return scalar_alu(op, first, bytes);
|
||||
}
|
||||
if let Some(op) = VectorAluOp::from_word(first) {
|
||||
// VOP2: SRC0 in bits 0-8, VSRC1 in bits 9-16, VDST in bits 17-24.
|
||||
let dst = ((first >> 17) & 0xff) as u8;
|
||||
let src1 = ((first >> 9) & 0xff) as u8;
|
||||
let (src0, len) = match op.operand_rule() {
|
||||
// Operand rule `vop2_vgpr2`: SRC0 must select a VGPR (256-511).
|
||||
OperandRule::Vop2Vgpr2 => {
|
||||
let (_, src0, _) = vop2_registers(first, op.assembly_name())?;
|
||||
(VectorSource::Register(src0), 4)
|
||||
}
|
||||
OperandRule::Vop2Vgpr | OperandRule::Vop2Vcc => {
|
||||
vector_src0(first, bytes, op.assembly_name())?
|
||||
}
|
||||
_ => unreachable!("non-VOP2 operand rule for VOP2 instruction"),
|
||||
};
|
||||
if S_CBRANCH_SCC0.matches(first) {
|
||||
let target = branch_target(first, offset, "s_cbranch_scc0")?;
|
||||
return Ok((
|
||||
Instruction::VectorAlu {
|
||||
op,
|
||||
dst,
|
||||
src0,
|
||||
src1,
|
||||
},
|
||||
len,
|
||||
Instruction::BranchSccZero { target },
|
||||
S_CBRANCH_SCC0.byte_len(),
|
||||
));
|
||||
}
|
||||
if S_CBRANCH_EXECZ.matches(first) {
|
||||
let target = branch_target(first, offset, "s_cbranch_execz")?;
|
||||
return Ok((
|
||||
Instruction::BranchExecZero { target },
|
||||
S_CBRANCH_EXECZ.byte_len(),
|
||||
));
|
||||
}
|
||||
if S_CBRANCH_VCCZ.matches(first) {
|
||||
let target = branch_target(first, offset, "s_cbranch_vccz")?;
|
||||
return Ok((
|
||||
Instruction::BranchVccZero { target },
|
||||
S_CBRANCH_VCCZ.byte_len(),
|
||||
));
|
||||
}
|
||||
if V_LSHLREV_B32.matches(first) {
|
||||
let (dst, src0, src1) = vop2_registers(first, "v_lshlrev_b32_e32")?;
|
||||
return Ok((
|
||||
Instruction::VectorLshlrevB32 { dst, src0, src1 },
|
||||
V_LSHLREV_B32.byte_len(),
|
||||
));
|
||||
}
|
||||
if V_ASHRREV_I32.matches(first) {
|
||||
let (dst, src0, src1) = vop2_registers(first, "v_ashrrev_i32_e32")?;
|
||||
return Ok((
|
||||
Instruction::VectorAshrrevI32 { dst, src0, src1 },
|
||||
V_ASHRREV_I32.byte_len(),
|
||||
));
|
||||
}
|
||||
if V_LSHRREV_B32.matches(first) {
|
||||
let (dst, src0, src1) = vop2_registers(first, "v_lshrrev_b32_e32")?;
|
||||
return Ok((
|
||||
Instruction::VectorLshrrevB32 { dst, src0, src1 },
|
||||
V_LSHRREV_B32.byte_len(),
|
||||
));
|
||||
}
|
||||
if V_AND_B32.matches(first) {
|
||||
let (dst, src0, src1) = vop2_registers(first, "v_and_b32_e32")?;
|
||||
return Ok((
|
||||
Instruction::VectorAndB32 { dst, src0, src1 },
|
||||
V_AND_B32.byte_len(),
|
||||
));
|
||||
}
|
||||
if V_OR_B32.matches(first) {
|
||||
let (dst, src0, src1) = vop2_registers(first, "v_or_b32_e32")?;
|
||||
return Ok((
|
||||
Instruction::VectorOrB32 { dst, src0, src1 },
|
||||
V_OR_B32.byte_len(),
|
||||
));
|
||||
}
|
||||
if V_XOR_B32.matches(first) {
|
||||
let (dst, src0, src1) = vop2_registers(first, "v_xor_b32_e32")?;
|
||||
return Ok((
|
||||
Instruction::VectorXorB32 { dst, src0, src1 },
|
||||
V_XOR_B32.byte_len(),
|
||||
));
|
||||
}
|
||||
if V_ADD_F32.matches(first) {
|
||||
@@ -468,6 +353,15 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
|
||||
V_MUL_F32.byte_len(),
|
||||
));
|
||||
}
|
||||
if S_WAITCNT.matches(first) {
|
||||
return scalar_form(
|
||||
first,
|
||||
S_WAITCNT.byte_len(),
|
||||
0xbf8c_3f70,
|
||||
Instruction::WaitLoad,
|
||||
"expected vmcnt(0) alone",
|
||||
);
|
||||
}
|
||||
if S_WAITCNT_VSCNT.matches(first) {
|
||||
return scalar_form(
|
||||
first,
|
||||
@@ -477,43 +371,19 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
|
||||
"expected null, 0",
|
||||
);
|
||||
}
|
||||
if S_ENDPGM.matches(first) {
|
||||
return scalar_form(
|
||||
first,
|
||||
S_ENDPGM.byte_len(),
|
||||
0xbf81_0000,
|
||||
Instruction::EndProgram,
|
||||
"expected zero immediate",
|
||||
);
|
||||
}
|
||||
|
||||
Err(DecodeErrorKind::UnsupportedOpcode { word: first })
|
||||
}
|
||||
|
||||
/// SOP2: SSRC0 in bits 0-7, SSRC1 in bits 8-15, SDST in bits 16-22.
|
||||
/// Other SOP2 opcodes stay unsupported.
|
||||
fn scalar_alu(
|
||||
op: ScalarAluOp,
|
||||
first: u32,
|
||||
bytes: &[u8],
|
||||
) -> Result<(Instruction, u8), DecodeErrorKind> {
|
||||
let mnemonic = op.mnemonic();
|
||||
let dst = ((first >> 16) & 0x7f) as u8;
|
||||
if dst > 105 {
|
||||
return Err(unsupported(mnemonic, "expected a normal SGPR destination"));
|
||||
}
|
||||
let src0_bits = first as u8;
|
||||
let src1_bits = (first >> 8) as u8;
|
||||
if src0_bits == 255 && src1_bits == 255 {
|
||||
return Err(unsupported(
|
||||
mnemonic,
|
||||
"only one source may select a literal",
|
||||
));
|
||||
}
|
||||
let (src0, len0) = scalar_source(src0_bits, bytes, mnemonic)?;
|
||||
let (src1, len1) = scalar_source(src1_bits, bytes, mnemonic)?;
|
||||
Ok((
|
||||
Instruction::ScalarAlu {
|
||||
op,
|
||||
dst,
|
||||
src0,
|
||||
src1,
|
||||
},
|
||||
len0.max(len1),
|
||||
))
|
||||
}
|
||||
|
||||
fn scalar_source(
|
||||
bits: u8,
|
||||
bytes: &[u8],
|
||||
@@ -533,11 +403,11 @@ fn scalar_source(
|
||||
}
|
||||
|
||||
fn branch_target(
|
||||
immediate: u16,
|
||||
first: u32,
|
||||
offset: usize,
|
||||
mnemonic: &'static str,
|
||||
) -> Result<usize, DecodeErrorKind> {
|
||||
let displacement = immediate as i16;
|
||||
let displacement = first as u16 as i16;
|
||||
let words = usize::try_from(displacement)
|
||||
.map_err(|_| unsupported(mnemonic, "expected a forward branch"))?;
|
||||
offset
|
||||
@@ -655,72 +525,11 @@ fn buffer_operands(
|
||||
Ok((data, index, resource))
|
||||
}
|
||||
|
||||
/// VOPC: SRC0 in bits 0-8, VSRC1 in bits 9-16 (RDNA 2 ISA section 12.9). The
|
||||
/// destination is implicitly `vcc_lo`. SRC0 excludes inline float constants,
|
||||
/// `vcc_hi`, EXEC, M0, TTMPs and the condition selectors (SDWA 249, DPP 250/233).
|
||||
fn vector_compare(
|
||||
op: VectorCompareOp,
|
||||
first: u32,
|
||||
bytes: &[u8],
|
||||
) -> Result<(Instruction, u8), DecodeErrorKind> {
|
||||
let src1 = ((first >> 9) & 0xff) as u8;
|
||||
let mnemonic = op.assembly_name();
|
||||
if op.semantics().width == 64 {
|
||||
// Guide §3.6.3 requires even SGPR bases. Reject invalid selectors
|
||||
// before reading a literal word or considering the execution mask.
|
||||
let source = first & 0x1ff;
|
||||
if src1 == 255
|
||||
|| !matches!(source, 0..=104 | 128..=208 | 256..=510)
|
||||
|| (source <= 104 && !source.is_multiple_of(2))
|
||||
{
|
||||
return Err(unsupported(mnemonic, "invalid 64-bit compare source"));
|
||||
}
|
||||
}
|
||||
if op.semantics().width == 16 && first & 0x1ff == 255 {
|
||||
return Err(unsupported(mnemonic, "literal in 16-bit compare"));
|
||||
}
|
||||
let (src0, len) = vector_src0(first, bytes, mnemonic)?;
|
||||
Ok((Instruction::VectorCompare { op, src0, src1 }, len))
|
||||
}
|
||||
|
||||
/// The 9-bit SRC0 of a VOP1, VOP2 or VOPC word: a VGPR, `s0-s105`, `vcc_lo`, an
|
||||
/// inline integer -16..64 or a literal word; everything else is unsupported.
|
||||
fn vector_src0(
|
||||
first: u32,
|
||||
bytes: &[u8],
|
||||
mnemonic: &'static str,
|
||||
) -> Result<(VectorSource, u8), DecodeErrorKind> {
|
||||
let source = first & 0x1ff;
|
||||
let base_len = 4;
|
||||
Ok(match source {
|
||||
0..=106 => (VectorSource::Scalar(source as u8), base_len),
|
||||
128..=192 => (VectorSource::Immediate(source - 128), base_len),
|
||||
193..=208 => (
|
||||
VectorSource::Immediate(192u32.wrapping_sub(source)),
|
||||
base_len,
|
||||
),
|
||||
255 => {
|
||||
let len = base_len + 4;
|
||||
(VectorSource::Immediate(word(bytes, len)?), len)
|
||||
}
|
||||
256..=511 => (VectorSource::Register(source as u8), base_len),
|
||||
_ => {
|
||||
return Err(unsupported(
|
||||
mnemonic,
|
||||
"expected a VGPR, normal SGPR, vcc_lo, inline integer or literal",
|
||||
));
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn move_b32(first: u32, bytes: &[u8]) -> Result<(Instruction, u8), DecodeErrorKind> {
|
||||
let dst = (first >> 17) as u8;
|
||||
let source = first & 0x1ff;
|
||||
let base_len = V_MOV_B32.byte_len();
|
||||
let (src, len) = match source {
|
||||
0..=105 => (VectorSource::Scalar(source as u8), base_len),
|
||||
// vcc_lo, which may hold a lane-derived compare mask (docs/shaders/vector-compare.md).
|
||||
106 => (VectorSource::Scalar(VCC_LO), base_len),
|
||||
128..=192 => (VectorSource::Immediate(source - 128), base_len),
|
||||
193..=208 => (
|
||||
VectorSource::Immediate(192u32.wrapping_sub(source)),
|
||||
@@ -736,44 +545,29 @@ fn move_b32(first: u32, bytes: &[u8]) -> Result<(Instruction, u8), DecodeErrorKi
|
||||
_ => {
|
||||
return Err(unsupported(
|
||||
"v_mov_b32_e32",
|
||||
"expected a VGPR, normal SGPR, vcc_lo, inline integer, inline +1.0f or literal",
|
||||
"expected a VGPR, inline integer, inline +1.0f or literal",
|
||||
));
|
||||
}
|
||||
};
|
||||
Ok((Instruction::MoveB32 { dst, src }, len))
|
||||
}
|
||||
|
||||
fn vop3_vgpr2(
|
||||
op: VectorAluVop3Op,
|
||||
first: u32,
|
||||
second: u32,
|
||||
) -> Result<Instruction, DecodeErrorKind> {
|
||||
let (src0, src1) = vop3_vgpr2_sources(op.assembly_name(), first, second)?;
|
||||
Ok(Instruction::VectorAluVop3 {
|
||||
op,
|
||||
dst: first as u8,
|
||||
src0,
|
||||
src1,
|
||||
})
|
||||
}
|
||||
|
||||
/// Common VOP3A source and modifier checks (RDNA 2 ISA section 13.3.4).
|
||||
/// SRC0 and SRC1 are VGPRs, the unused SRC2 is inline zero, and ABS, OP_SEL,
|
||||
/// CLAMP, OMOD and NEG are clear.
|
||||
fn vop3_vgpr2_sources(
|
||||
mnemonic: &'static str,
|
||||
first: u32,
|
||||
second: u32,
|
||||
) -> Result<(u8, u8), DecodeErrorKind> {
|
||||
fn add_u32(first: u32, second: u32) -> Result<Instruction, DecodeErrorKind> {
|
||||
let src0 = second & 0x1ff;
|
||||
let src1 = (second >> 9) & 0x1ff;
|
||||
// All output and input modifiers are clear. The unused third source uses
|
||||
// the gfx1030 assembler's inline-zero operand encoding.
|
||||
if first & 0xff00 != 0 || second >> 18 != 128 || src0 < 256 || src1 < 256 {
|
||||
return Err(unsupported(
|
||||
mnemonic,
|
||||
"v_add_nc_u32_e64",
|
||||
"expected two VGPR sources and no modifiers",
|
||||
));
|
||||
}
|
||||
Ok((src0 as u8, src1 as u8))
|
||||
Ok(Instruction::AddNoCarryU32 {
|
||||
dst: first as u8,
|
||||
src0: src0 as u8,
|
||||
src1: src1 as u8,
|
||||
})
|
||||
}
|
||||
|
||||
fn scalar_form(
|
||||
|
||||
+32
-737
@@ -3,15 +3,10 @@ use std::path::PathBuf;
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
use xenora_decoder::{
|
||||
Architecture, CompareRelation, DecodeError, DecodeErrorKind, DecodedInstruction, Instruction,
|
||||
ScalarAluOp, ScalarImmediateOp, ScalarSource, ScalarUnaryOp, VectorAluOp, VectorAluVop3Op,
|
||||
VectorCompareOp, VectorCompareVop3Op, VectorSource, VectorUnaryOp, decode, decode_at,
|
||||
};
|
||||
use xenora_isa::semantics::Signedness;
|
||||
use xenora_ref::{
|
||||
BranchCondition, CompareSource, CompareWidth, Comparison, Op, ScalarAlu, ScalarImmediate,
|
||||
ScalarUnary, Source, VectorAlu, VectorInteger, VectorUnary,
|
||||
Architecture, DecodeError, DecodeErrorKind, DecodedInstruction, Instruction, ScalarSource,
|
||||
VectorSource, decode,
|
||||
};
|
||||
use xenora_ref::{BranchCondition, Op, Source, VectorAlu};
|
||||
|
||||
const FIXTURE: &[u8] = include_bytes!("../../../fixtures/rdna2/add.bin");
|
||||
const BITWISE_FIXTURE: &[u8] = include_bytes!("../../../fixtures/rdna2/bitwise-branch.bin");
|
||||
@@ -44,8 +39,7 @@ fn decodes_each_fixture_instruction_with_offset_and_length() {
|
||||
(
|
||||
20,
|
||||
8,
|
||||
Instruction::VectorAluVop3 {
|
||||
op: VectorAluVop3Op::AddNcU32,
|
||||
Instruction::AddNoCarryU32 {
|
||||
dst: 1,
|
||||
src0: 1,
|
||||
src1: 2,
|
||||
@@ -71,127 +65,6 @@ fn decodes_each_fixture_instruction_with_offset_and_length() {
|
||||
assert_eq!(instructions, wanted);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_wave32_vop3_compares_from_llvm_words() {
|
||||
use VectorCompareVop3Op::*;
|
||||
|
||||
// llvm-mc -triple=amdgcn -mcpu=gfx1030 -mattr=+wavefrontsize32 -show-encoding
|
||||
let cases: [(u32, VectorCompareVop3Op, u8); 19] = [
|
||||
// v_cmp_lt_i32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0x81,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd481_0004, CmpLtI32, 4),
|
||||
// v_cmp_eq_i32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0x82,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd482_0004, CmpEqI32, 4),
|
||||
// v_cmp_le_i32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0x83,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd483_0004, CmpLeI32, 4),
|
||||
// v_cmp_gt_i32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0x84,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd484_0004, CmpGtI32, 4),
|
||||
// v_cmp_ne_i32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0x85,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd485_0004, CmpNeI32, 4),
|
||||
// v_cmp_ge_i32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0x86,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd486_0004, CmpGeI32, 4),
|
||||
// v_cmp_lt_u32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0xc1,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd4c1_0004, CmpLtU32, 4),
|
||||
// v_cmp_eq_u32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0xc2,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd4c2_0004, CmpEqU32, 4),
|
||||
// v_cmp_le_u32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0xc3,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd4c3_0004, CmpLeU32, 4),
|
||||
// v_cmp_gt_u32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0xc4,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd4c4_0004, CmpGtU32, 4),
|
||||
// v_cmp_ne_u32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0xc5,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd4c5_0004, CmpNeU32, 4),
|
||||
// v_cmp_ge_u32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0xc6,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd4c6_0004, CmpGeU32, 4),
|
||||
// v_cmp_f_i32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0x80,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd480_0004, CmpFI32, 4),
|
||||
// v_cmp_t_i32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0x87,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd487_0004, CmpTI32, 4),
|
||||
// v_cmp_f_u32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0xc0,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd4c0_0004, CmpFU32, 4),
|
||||
// v_cmp_t_u32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0xc7,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd4c7_0004, CmpTU32, 4),
|
||||
// v_cmp_eq_u32_e64 s0, v1, v2 ; encoding: [0x00,0x00,0xc2,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd4c2_0000, CmpEqU32, 0),
|
||||
// v_cmp_eq_u32_e64 s105, v1, v2 ; encoding: [0x69,0x00,0xc2,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd4c2_0069, CmpEqU32, 105),
|
||||
// v_cmp_eq_u32_e64 vcc_lo, v1, v2 ; encoding: [0x6a,0x00,0xc2,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd4c2_006a, CmpEqU32, 106),
|
||||
];
|
||||
for (first, op, sdst) in cases {
|
||||
let code: Vec<_> = [first, 0x0202_0501]
|
||||
.into_iter()
|
||||
.flat_map(u32::to_le_bytes)
|
||||
.collect();
|
||||
let decoded = decode(Architecture::Gfx1030, &code).unwrap();
|
||||
let dst = if sdst == 106 {
|
||||
"vcc_lo".to_owned()
|
||||
} else {
|
||||
format!("s{sdst}")
|
||||
};
|
||||
assert_eq!(
|
||||
decoded,
|
||||
[DecodedInstruction {
|
||||
offset: 0,
|
||||
byte_len: 8,
|
||||
instruction: Instruction::VectorCompareVop3 {
|
||||
op,
|
||||
sdst,
|
||||
src0: 1,
|
||||
src1: 2
|
||||
},
|
||||
}],
|
||||
);
|
||||
assert_eq!(
|
||||
decoded[0].instruction.to_string(),
|
||||
format!("{} {dst}, v1, v2", op.assembly_name())
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_noncanonical_wave32_vop3_compare_operands() {
|
||||
// v_cmp_eq_u32_e64 s4, v1, v2
|
||||
let first = 0xd4c2_0004;
|
||||
let second = 0x0202_0501;
|
||||
let rejects = |first, second| {
|
||||
let code: Vec<_> = [first, second]
|
||||
.into_iter()
|
||||
.flat_map(u32::to_le_bytes)
|
||||
.collect();
|
||||
let error = decode(Architecture::Gfx1030, &code).unwrap_err();
|
||||
assert_eq!(error.offset, 0);
|
||||
assert!(
|
||||
matches!(
|
||||
error.kind,
|
||||
DecodeErrorKind::UnsupportedForm {
|
||||
mnemonic: "v_cmp_eq_u32_e64",
|
||||
..
|
||||
}
|
||||
),
|
||||
"{first:#010x} {second:#010x}: {error}"
|
||||
);
|
||||
};
|
||||
|
||||
// Includes vcc_hi (107), TTMPs (108-123), null (124), m0 (125) and EXEC (126-127).
|
||||
for sdst in 107..=255 {
|
||||
rejects((first & !0xff) | sdst, second);
|
||||
}
|
||||
for bit in 8..=15 {
|
||||
// ABS, OP_SEL and CLAMP.
|
||||
rejects(first | (1 << bit), second);
|
||||
}
|
||||
for bit in 27..=31 {
|
||||
// OMOD and NEG.
|
||||
rejects(first, second | (1 << bit));
|
||||
}
|
||||
rejects(first, second ^ (1 << 18)); // SRC2 = 129 instead of 128.
|
||||
for shift in [0, 9] {
|
||||
for selector in [4, 106, 128, 240, 255] {
|
||||
// SGPR, VCC_LO, inline integer/float, literal.
|
||||
rejects(first, (second & !(0x1ff << shift)) | (selector << shift));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_non_boundary_prefix_reports_the_incomplete_instruction() {
|
||||
let lengths = [8, 4, 8, 8, 8, 4, 4];
|
||||
@@ -224,12 +97,7 @@ fn rejects_other_opcodes_and_noncanonical_operands() {
|
||||
(&[0xe070_2000, 0x801b_0100], "buffer_store_dword"),
|
||||
(&[0xbf8c_3f71], "s_waitcnt"),
|
||||
(&[0xbbfd_0001], "s_waitcnt_vscnt"),
|
||||
(&[0x7e04_026b], "v_mov_b32_e32"), // VCC_HI is outside the source subset.
|
||||
(&[0x7d02_046b], "v_cmp_lt_i32_e32"), // VCC_HI source.
|
||||
(&[0x7d02_047e], "v_cmp_lt_i32_e32"), // EXEC_LO source.
|
||||
(&[0x7d02_04f0], "v_cmp_lt_i32_e32"), // Inline 0.5 source.
|
||||
(&[0x7d84_04f9, 0x0606_0601], "v_cmp_eq_u32_e32"), // SDWA.
|
||||
(&[0x7d84_04fa, 0], "v_cmp_eq_u32_e32"), // DPP16.
|
||||
(&[0x7e04_0200], "v_mov_b32_e32"),
|
||||
(&[0x7e04_02fa, 0], "v_mov_b32_e32"),
|
||||
(&[0xd525_8001, 0x0202_0501], "v_add_nc_u32_e64"),
|
||||
(&[0xd525_0001, 0x0202_0480], "v_add_nc_u32_e64"),
|
||||
@@ -413,7 +281,6 @@ fn reference_source(vector: VectorSource) -> Source {
|
||||
match vector {
|
||||
VectorSource::Register(reg) => Source::Register(reg),
|
||||
VectorSource::Immediate(bits) => Source::Immediate(bits),
|
||||
VectorSource::Scalar(_) => unreachable!("mapped to Op::MoveScalar"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -424,44 +291,6 @@ fn reference_scalar(scalar: ScalarSource) -> Source {
|
||||
}
|
||||
}
|
||||
|
||||
fn reference_comparison(op: VectorCompareOp) -> Comparison {
|
||||
Comparison {
|
||||
offset: match op.relation() {
|
||||
CompareRelation::Less => 1,
|
||||
CompareRelation::Equal => 2,
|
||||
CompareRelation::LessOrEqual => 3,
|
||||
CompareRelation::Greater => 4,
|
||||
CompareRelation::NotEqual => 5,
|
||||
CompareRelation::GreaterOrEqual => 6,
|
||||
CompareRelation::False => 0,
|
||||
CompareRelation::True => 7,
|
||||
},
|
||||
signed: op.signed(),
|
||||
}
|
||||
}
|
||||
|
||||
fn reference_vector_integer(op: VectorAluOp) -> VectorInteger {
|
||||
match op {
|
||||
VectorAluOp::CndmaskB32 => VectorInteger::Select,
|
||||
VectorAluOp::AddCoCiU32 => VectorInteger::AddCarry,
|
||||
VectorAluOp::SubCoCiU32 => VectorInteger::SubtractBorrow { reversed: false },
|
||||
VectorAluOp::SubrevCoCiU32 => VectorInteger::SubtractBorrow { reversed: true },
|
||||
VectorAluOp::MulI32I24 => VectorInteger::Multiply24 { signed: true },
|
||||
VectorAluOp::MulHiI32I24 => VectorInteger::MultiplyHigh24 { signed: true },
|
||||
VectorAluOp::MulU32U24 => VectorInteger::Multiply24 { signed: false },
|
||||
VectorAluOp::MulHiU32U24 => VectorInteger::MultiplyHigh24 { signed: false },
|
||||
VectorAluOp::MinI32 => VectorInteger::Minimum { signed: true },
|
||||
VectorAluOp::MaxI32 => VectorInteger::Maximum { signed: true },
|
||||
VectorAluOp::MinU32 => VectorInteger::Minimum { signed: false },
|
||||
VectorAluOp::MaxU32 => VectorInteger::Maximum { signed: false },
|
||||
VectorAluOp::XnorB32 => VectorInteger::Xnor,
|
||||
VectorAluOp::AddNcU32 => VectorInteger::Add,
|
||||
VectorAluOp::SubNcU32 => VectorInteger::Subtract,
|
||||
VectorAluOp::SubrevNcU32 => VectorInteger::SubtractReverse,
|
||||
_ => panic!("{op:?} decodes only with a VGPR SRC0 (operand rule vop2_vgpr2)"),
|
||||
}
|
||||
}
|
||||
|
||||
fn reference_op(instruction: Instruction) -> Op {
|
||||
match instruction {
|
||||
Instruction::BufferLoadDword {
|
||||
@@ -484,142 +313,12 @@ fn reference_op(instruction: Instruction) -> Op {
|
||||
},
|
||||
Instruction::WaitLoad => Op::WaitRead,
|
||||
Instruction::WaitStore => Op::WaitWrite,
|
||||
Instruction::MoveB32 {
|
||||
dst,
|
||||
src: VectorSource::Scalar(src),
|
||||
} => Op::MoveScalar(dst, src),
|
||||
Instruction::MoveB32 { dst, src } => Op::Move(dst, reference_source(src)),
|
||||
Instruction::VectorUnary { op, dst, src } => Op::VectorUnary(
|
||||
match op {
|
||||
VectorUnaryOp::NotB32 => VectorUnary::Not,
|
||||
VectorUnaryOp::BfrevB32 => VectorUnary::ReverseBits,
|
||||
VectorUnaryOp::FfbhU32 => VectorUnary::FindFirstOneFromMsb,
|
||||
VectorUnaryOp::FfblB32 => VectorUnary::FindFirstOneFromLsb,
|
||||
VectorUnaryOp::FfbhI32 => VectorUnary::FindSignChange,
|
||||
},
|
||||
dst,
|
||||
match src {
|
||||
VectorSource::Register(reg) => CompareSource::Vector(reg),
|
||||
VectorSource::Scalar(reg) => CompareSource::Scalar(reg),
|
||||
VectorSource::Immediate(bits) => CompareSource::Immediate(bits),
|
||||
},
|
||||
),
|
||||
Instruction::VectorSwap { dst, src, .. } => Op::Swap(dst, src),
|
||||
Instruction::ScalarAlu {
|
||||
op,
|
||||
dst,
|
||||
src0,
|
||||
src1,
|
||||
} => Op::Scalar(
|
||||
match op {
|
||||
ScalarAluOp::AddU32 => ScalarAlu::Add,
|
||||
ScalarAluOp::SubU32 => ScalarAlu::Subtract,
|
||||
ScalarAluOp::AddI32 => ScalarAlu::AddSigned,
|
||||
ScalarAluOp::SubI32 => ScalarAlu::SubtractSigned,
|
||||
ScalarAluOp::AddcU32 => ScalarAlu::AddWithCarry,
|
||||
ScalarAluOp::SubbU32 => ScalarAlu::SubtractWithBorrow,
|
||||
ScalarAluOp::AndB32 => ScalarAlu::And,
|
||||
ScalarAluOp::OrB32 => ScalarAlu::Or,
|
||||
ScalarAluOp::XorB32 => ScalarAlu::Xor,
|
||||
ScalarAluOp::Andn2B32 => ScalarAlu::AndNot,
|
||||
ScalarAluOp::Orn2B32 => ScalarAlu::OrNot,
|
||||
ScalarAluOp::NandB32 => ScalarAlu::Nand,
|
||||
ScalarAluOp::NorB32 => ScalarAlu::Nor,
|
||||
ScalarAluOp::XnorB32 => ScalarAlu::Xnor,
|
||||
ScalarAluOp::LshlB32 => ScalarAlu::ShiftLeft,
|
||||
ScalarAluOp::LshrB32 => ScalarAlu::ShiftRight,
|
||||
ScalarAluOp::AshrI32 => ScalarAlu::ArithmeticShiftRight,
|
||||
ScalarAluOp::MinI32 => ScalarAlu::Minimum { signed: true },
|
||||
ScalarAluOp::MinU32 => ScalarAlu::Minimum { signed: false },
|
||||
ScalarAluOp::MaxI32 => ScalarAlu::Maximum { signed: true },
|
||||
ScalarAluOp::MaxU32 => ScalarAlu::Maximum { signed: false },
|
||||
ScalarAluOp::CselectB32 => ScalarAlu::Select,
|
||||
ScalarAluOp::BfmB32 => ScalarAlu::BitfieldMask,
|
||||
ScalarAluOp::MulI32 => ScalarAlu::Multiply,
|
||||
ScalarAluOp::BfeU32 => ScalarAlu::BitfieldExtract { signed: false },
|
||||
ScalarAluOp::BfeI32 => ScalarAlu::BitfieldExtract { signed: true },
|
||||
ScalarAluOp::AbsdiffI32 => ScalarAlu::AbsoluteDifference,
|
||||
ScalarAluOp::Lshl1AddU32 => ScalarAlu::ShiftLeftAdd(1),
|
||||
ScalarAluOp::Lshl2AddU32 => ScalarAlu::ShiftLeftAdd(2),
|
||||
ScalarAluOp::Lshl3AddU32 => ScalarAlu::ShiftLeftAdd(3),
|
||||
ScalarAluOp::Lshl4AddU32 => ScalarAlu::ShiftLeftAdd(4),
|
||||
ScalarAluOp::MulHiU32 => ScalarAlu::MultiplyHigh { signed: false },
|
||||
ScalarAluOp::MulHiI32 => ScalarAlu::MultiplyHigh { signed: true },
|
||||
},
|
||||
dst,
|
||||
reference_scalar(src0),
|
||||
reference_scalar(src1),
|
||||
),
|
||||
Instruction::VectorAluVop3 {
|
||||
op: VectorAluVop3Op::AddNcU32,
|
||||
dst,
|
||||
src0,
|
||||
src1,
|
||||
} => Op::Add(dst, src0, src1),
|
||||
Instruction::VectorAluVop3 {
|
||||
op,
|
||||
dst,
|
||||
src0,
|
||||
src1,
|
||||
} => Op::VectorInteger(
|
||||
reference_vector_integer(op.base()),
|
||||
dst,
|
||||
CompareSource::Vector(src0),
|
||||
src1,
|
||||
),
|
||||
Instruction::ScalarUnary { op, dst, src } => {
|
||||
let src = reference_scalar(src);
|
||||
let unary = match op {
|
||||
ScalarUnaryOp::MovB32 => return Op::ScalarMove(dst, src),
|
||||
ScalarUnaryOp::NotB32 => ScalarUnary::Not,
|
||||
ScalarUnaryOp::BrevB32 => ScalarUnary::ReverseBits,
|
||||
ScalarUnaryOp::Bcnt0I32B32 => ScalarUnary::CountZeros,
|
||||
ScalarUnaryOp::Bcnt1I32B32 => ScalarUnary::CountOnes,
|
||||
ScalarUnaryOp::Ff0I32B32 => ScalarUnary::FindFirstZero,
|
||||
ScalarUnaryOp::Ff1I32B32 => ScalarUnary::FindFirstOne,
|
||||
ScalarUnaryOp::FlbitI32B32 => ScalarUnary::FindLastBit,
|
||||
ScalarUnaryOp::FlbitI32 => ScalarUnary::FindLastSignBit,
|
||||
ScalarUnaryOp::SextI32I8 => ScalarUnary::SignExtendByte,
|
||||
ScalarUnaryOp::SextI32I16 => ScalarUnary::SignExtendShort,
|
||||
ScalarUnaryOp::AbsI32 => ScalarUnary::Absolute,
|
||||
};
|
||||
Op::ScalarUnary(unary, dst, src)
|
||||
Instruction::AddNoCarryU32 { dst, src0, src1 } => Op::Add(dst, src0, src1),
|
||||
Instruction::ScalarMoveB32 { dst, src } => Op::ScalarMove(dst, reference_scalar(src)),
|
||||
Instruction::ScalarCompareEqU32 { src0, src1 } => {
|
||||
Op::CompareEqual(reference_scalar(src0), reference_scalar(src1))
|
||||
}
|
||||
Instruction::ScalarCompare { op, src0, src1 } => {
|
||||
let (src0, src1) = (reference_scalar(src0), reference_scalar(src1));
|
||||
// The reference keeps CompareEqual for EQ and uses its VOPC relation
|
||||
// offsets (LT 1, EQ 2, LE 3, GT 4, NE 5, GE 6) for the rest.
|
||||
match op.relation() {
|
||||
CompareRelation::Equal => Op::CompareEqual(src0, src1),
|
||||
relation => Op::ScalarCompare(
|
||||
Comparison {
|
||||
offset: relation as u8 + 1,
|
||||
signed: op.semantics().signedness == Signedness::Signed,
|
||||
},
|
||||
src0,
|
||||
src1,
|
||||
),
|
||||
}
|
||||
}
|
||||
Instruction::ScalarImmediate { op, dst, simm16 } => Op::ScalarImmediate(
|
||||
match op {
|
||||
ScalarImmediateOp::MovkI32 => ScalarImmediate::Move,
|
||||
ScalarImmediateOp::CmovkI32 => ScalarImmediate::ConditionalMove,
|
||||
ScalarImmediateOp::AddkI32 => ScalarImmediate::Add,
|
||||
ScalarImmediateOp::MulkI32 => ScalarImmediate::Multiply,
|
||||
},
|
||||
dst,
|
||||
simm16,
|
||||
),
|
||||
Instruction::ScalarImmediateCompare { op, src, simm16 } => Op::ScalarImmediate(
|
||||
ScalarImmediate::Compare(Comparison {
|
||||
// The reference's VOPC relation offsets, as for SOPC above.
|
||||
offset: op.relation() as u8 + 1,
|
||||
signed: op.semantics().signedness == Signedness::Signed,
|
||||
}),
|
||||
src,
|
||||
simm16,
|
||||
),
|
||||
Instruction::BranchSccZero { target } => Op::Branch {
|
||||
target,
|
||||
condition: BranchCondition::SccZero,
|
||||
@@ -636,32 +335,22 @@ fn reference_op(instruction: Instruction) -> Op {
|
||||
target,
|
||||
condition: BranchCondition::Always,
|
||||
},
|
||||
// The six logical and shift forms migrated from hand-written code
|
||||
// (#215 M27) keep the reference's VGPR-only VectorAlu ops.
|
||||
Instruction::VectorAlu {
|
||||
op:
|
||||
op @ (VectorAluOp::AndB32
|
||||
| VectorAluOp::OrB32
|
||||
| VectorAluOp::XorB32
|
||||
| VectorAluOp::LshlrevB32
|
||||
| VectorAluOp::LshrrevB32
|
||||
| VectorAluOp::AshrrevI32),
|
||||
dst,
|
||||
src0: VectorSource::Register(src0),
|
||||
src1,
|
||||
} => Op::Vector(
|
||||
match op {
|
||||
VectorAluOp::AndB32 => VectorAlu::And,
|
||||
VectorAluOp::OrB32 => VectorAlu::Or,
|
||||
VectorAluOp::XorB32 => VectorAlu::Xor,
|
||||
VectorAluOp::LshlrevB32 => VectorAlu::ShiftLeft,
|
||||
VectorAluOp::LshrrevB32 => VectorAlu::ShiftRight,
|
||||
_ => VectorAlu::ArithmeticShiftRight,
|
||||
},
|
||||
dst,
|
||||
src0,
|
||||
src1,
|
||||
),
|
||||
Instruction::VectorAndB32 { dst, src0, src1 } => {
|
||||
Op::Vector(VectorAlu::And, dst, src0, src1)
|
||||
}
|
||||
Instruction::VectorLshlrevB32 { dst, src0, src1 } => {
|
||||
Op::Vector(VectorAlu::ShiftLeft, dst, src0, src1)
|
||||
}
|
||||
Instruction::VectorAshrrevI32 { dst, src0, src1 } => {
|
||||
Op::Vector(VectorAlu::ArithmeticShiftRight, dst, src0, src1)
|
||||
}
|
||||
Instruction::VectorLshrrevB32 { dst, src0, src1 } => {
|
||||
Op::Vector(VectorAlu::ShiftRight, dst, src0, src1)
|
||||
}
|
||||
Instruction::VectorOrB32 { dst, src0, src1 } => Op::Vector(VectorAlu::Or, dst, src0, src1),
|
||||
Instruction::VectorXorB32 { dst, src0, src1 } => {
|
||||
Op::Vector(VectorAlu::Xor, dst, src0, src1)
|
||||
}
|
||||
Instruction::VectorAddF32 { dst, src0, src1 } => {
|
||||
Op::Vector(VectorAlu::FloatAdd, dst, src0, src1)
|
||||
}
|
||||
@@ -674,46 +363,6 @@ fn reference_op(instruction: Instruction) -> Op {
|
||||
panic!("compute reference matrix received a graphics/image instruction")
|
||||
}
|
||||
|
||||
Instruction::VectorCompare { op, src0, src1 } => {
|
||||
let comparison = reference_comparison(op);
|
||||
let src0 = match src0 {
|
||||
VectorSource::Register(reg) => CompareSource::Vector(reg),
|
||||
VectorSource::Scalar(reg) => CompareSource::Scalar(reg),
|
||||
VectorSource::Immediate(bits) => CompareSource::Immediate(bits),
|
||||
};
|
||||
match op.semantics().width {
|
||||
16 => Op::WideCompare(comparison, CompareWidth::Half, src0, src1),
|
||||
32 => Op::Compare(comparison, src0, src1),
|
||||
64 => Op::WideCompare(comparison, CompareWidth::Double, src0, src1),
|
||||
width => panic!("unexpected VOPC operand width {width}"),
|
||||
}
|
||||
}
|
||||
Instruction::VectorCompareVop3 {
|
||||
op,
|
||||
sdst,
|
||||
src0,
|
||||
src1,
|
||||
} => Op::CompareVop3(
|
||||
sdst,
|
||||
reference_comparison(op.base()),
|
||||
CompareSource::Vector(src0),
|
||||
src1,
|
||||
),
|
||||
Instruction::VectorAlu {
|
||||
op,
|
||||
dst,
|
||||
src0,
|
||||
src1,
|
||||
} => Op::VectorInteger(
|
||||
reference_vector_integer(op),
|
||||
dst,
|
||||
match src0 {
|
||||
VectorSource::Register(reg) => CompareSource::Vector(reg),
|
||||
VectorSource::Scalar(reg) => CompareSource::Scalar(reg),
|
||||
VectorSource::Immediate(bits) => CompareSource::Immediate(bits),
|
||||
},
|
||||
src1,
|
||||
),
|
||||
Instruction::EndProgram => Op::End,
|
||||
}
|
||||
}
|
||||
@@ -734,26 +383,12 @@ fn compares_fixture_instructions_against_llvm() {
|
||||
OR_FIXTURE,
|
||||
SHIFT_FIXTURE,
|
||||
include_bytes!("../../../fixtures/rdna2/ashr.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/scalar-alu.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/scalar-logic.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/scalar-compare.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/scalar-unary.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/scalar-arith.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/scalar-immediate.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/vector-integer.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/vector-vcc.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/vector-compare.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/vector-compare-ft.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/vector-unary.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/vector-compare-16.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/vop3-integer.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/vop3-compare.bin"),
|
||||
high_registers,
|
||||
&matrix,
|
||||
] {
|
||||
count += compare_against_llvm(fixture, &mut forms);
|
||||
}
|
||||
assert_eq!(forms.len(), 169, "forms compared: {forms:?}");
|
||||
assert_eq!(forms.len(), 21, "forms compared: {forms:?}");
|
||||
eprintln!(
|
||||
"{count} three-way instruction comparisons across {} forms",
|
||||
forms.len()
|
||||
@@ -761,7 +396,6 @@ fn compares_fixture_instructions_against_llvm() {
|
||||
}
|
||||
|
||||
fn assemble_matrix() -> Vec<u8> {
|
||||
use std::fmt::Write as _;
|
||||
// Cover register banks and extrema, immediate classes in both scalar
|
||||
// compare positions, zero displacement and branches over literal words.
|
||||
let mut assembly = String::from(
|
||||
@@ -799,63 +433,13 @@ fn assemble_matrix() -> Vec<u8> {
|
||||
v_mov_b32_e32 v255, lit(0x1)
|
||||
s_mov_b32 s105, lit(0x1)
|
||||
s_cmp_eq_u32 s105, lit(0x1)
|
||||
s_add_u32 s105, s104, 0xdeadbeef
|
||||
s_add_u32 s8, -16, 64
|
||||
s_sub_u32 s105, s1, s2
|
||||
s_sub_u32 s9, 0xdeadbeef, -16
|
||||
s_addc_u32 s104, 0xdeadbeef, s105
|
||||
s_subb_u32 s0, s0, s0
|
||||
s_add_i32 s101, 0x7fffffff, s100
|
||||
s_sub_i32 s100, -16, 0x80000000
|
||||
s_and_b32 s1, -1, s2
|
||||
s_or_b32 s103, s3, 0x80000000
|
||||
s_xor_b32 s102, s104, -16
|
||||
s_xor_b32 s7, s7, lit(0x1)
|
||||
s_movk_i32 s105, 0xffff
|
||||
s_movk_i32 s8, 0
|
||||
s_cmovk_i32 s105, 0x8000
|
||||
s_addk_i32 s9, 0x7fff
|
||||
s_addk_i32 s105, 0xffff
|
||||
s_mulk_i32 s8, 0x8001
|
||||
v_mov_b32_e32 v255, s105
|
||||
v_mov_b32_e32 v0, s0
|
||||
v_mov_b32_e32 v128, vcc_lo
|
||||
",
|
||||
);
|
||||
// Every supported VOPC form with each source class: VGPR, SGPR, vcc_lo,
|
||||
// inline integers at both ends, inline zero and a literal.
|
||||
for relation in ["f", "lt", "eq", "le", "gt", "ne", "ge", "t"] {
|
||||
for kind in ["i32", "u32"] {
|
||||
for src0 in [
|
||||
"v255",
|
||||
"v0",
|
||||
"s0",
|
||||
"s105",
|
||||
"vcc_lo",
|
||||
"-16",
|
||||
"64",
|
||||
"0",
|
||||
"0x80000000",
|
||||
] {
|
||||
writeln!(assembly, "v_cmp_{relation}_{kind}_e32 vcc_lo, {src0}, v128").unwrap();
|
||||
}
|
||||
writeln!(assembly, "v_cmp_{relation}_{kind}_e32 vcc_lo, v1, v255").unwrap();
|
||||
}
|
||||
}
|
||||
// Every SOPK compare on the lowest and highest readable SGPR.
|
||||
for relation in ["eq", "lg", "gt", "ge", "lt", "le"] {
|
||||
for kind in ["i32", "u32"] {
|
||||
for register in ["s0", "s7", "s8", "s105"] {
|
||||
writeln!(assembly, "s_cmpk_{relation}_{kind} {register}, 0x8000").unwrap();
|
||||
}
|
||||
writeln!(assembly, "s_cmpk_{relation}_{kind} s9, 0").unwrap();
|
||||
}
|
||||
}
|
||||
use std::fmt::Write as _;
|
||||
for value in -16..=64 {
|
||||
writeln!(assembly, "v_mov_b32_e32 v255, {value}").unwrap();
|
||||
writeln!(assembly, "s_mov_b32 s105, {value}").unwrap();
|
||||
writeln!(assembly, "s_cmp_eq_u32 {value}, {value}").unwrap();
|
||||
writeln!(assembly, "s_add_u32 s10, {value}, s11").unwrap();
|
||||
}
|
||||
assembly.push_str("s_endpgm\n");
|
||||
let output = llvm_mc(&[], assembly.as_bytes());
|
||||
@@ -979,15 +563,7 @@ fn distinguishes_llvm_invalid_encodings_from_xenora_subset_rejections() {
|
||||
&[0xd516_0001],
|
||||
];
|
||||
let outside_subset: &[&[u32]] = &[
|
||||
&[0x7e04_026b], // VOP1 VCC_HI source
|
||||
&[0x7da2_0501], // v_cmpx_eq_u32_e32
|
||||
&[0xd482_006a, 0x0002_0501], // v_cmp_eq_i32_e64 with SRC2 = 0
|
||||
&[0x8788_0908], // s_and_b64
|
||||
&[0x8008_ffff, 0x1234_5678], // SOP2 with two literal sources
|
||||
&[0x806c_0908], // SOP2 TTMP destination
|
||||
&[0x807e_0908], // SOP2 EXEC_LO destination
|
||||
&[0x806a_0908], // SOP2 VCC_LO destination
|
||||
&[0x8008_096a], // SOP2 VCC_LO source
|
||||
&[0x7e04_0200], // VOP1 SGPR source
|
||||
&[0x3803_fe80], // OR with an inline SRC0
|
||||
&[0x3803_fe08], // OR with an SGPR SRC0
|
||||
&[0x3803_feff, 0xdead_beef], // OR with a literal SRC0
|
||||
@@ -1050,24 +626,6 @@ fn normalize_llvm_assembly(assembly: &str, next_offset: usize) -> String {
|
||||
let target = next_offset + displacement * 4;
|
||||
format!("{mnemonic} -> 0x{target:04x}")
|
||||
}
|
||||
// VOPC and registry VOP2 forms print SRC0 as bits.
|
||||
mnemonic
|
||||
if mnemonic.starts_with("v_cmp_")
|
||||
|| VectorAluOp::ALL
|
||||
.iter()
|
||||
.any(|op| op.assembly_name() == mnemonic) =>
|
||||
{
|
||||
let mut parts: Vec<String> = operands.split(", ").map(str::to_owned).collect();
|
||||
let src = if parts.len() == 5 { 2 } else { 1 };
|
||||
parts[src] = match literal_bits(&parts[src]) {
|
||||
Some(bits) => format!("0x{bits:x}"),
|
||||
None => parts[src].parse::<i32>().map_or_else(
|
||||
|_| parts[src].clone(),
|
||||
|value| format!("0x{:x}", value as u32),
|
||||
),
|
||||
};
|
||||
format!("{mnemonic} {}", parts.join(", "))
|
||||
}
|
||||
"v_mov_b32_e32" => {
|
||||
let (destination, source) = operands.split_once(", ").unwrap();
|
||||
let normalized = match source {
|
||||
@@ -1093,18 +651,6 @@ fn normalize_llvm_assembly(assembly: &str, next_offset: usize) -> String {
|
||||
};
|
||||
format!("{mnemonic} {}, {}", scalar(left), scalar(right))
|
||||
}
|
||||
"s_add_u32" | "s_sub_u32" | "s_add_i32" | "s_sub_i32" | "s_addc_u32" | "s_subb_u32"
|
||||
| "s_and_b32" | "s_or_b32" | "s_xor_b32" => {
|
||||
let scalar = |operand: &str| match literal_bits(operand) {
|
||||
Some(bits) => match bits as i32 {
|
||||
inline @ -16..=64 => inline.to_string(),
|
||||
_ => format!("0x{bits:x}"),
|
||||
},
|
||||
None => operand.to_owned(),
|
||||
};
|
||||
let operands: Vec<_> = operands.split(", ").map(scalar).collect();
|
||||
format!("{mnemonic} {}", operands.join(", "))
|
||||
}
|
||||
_ => assembly.to_owned(),
|
||||
}
|
||||
}
|
||||
@@ -1172,16 +718,14 @@ fn decodes_inline_negative_and_register_sources() {
|
||||
let decoded = decode(Architecture::Gfx1030, &bytes).unwrap();
|
||||
assert_eq!(
|
||||
decoded[0].instruction,
|
||||
Instruction::ScalarUnary {
|
||||
op: ScalarUnaryOp::MovB32,
|
||||
Instruction::ScalarMoveB32 {
|
||||
dst: 10,
|
||||
src: ScalarSource::Immediate(5)
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
decoded[1].instruction,
|
||||
Instruction::ScalarUnary {
|
||||
op: ScalarUnaryOp::MovB32,
|
||||
Instruction::ScalarMoveB32 {
|
||||
dst: 11,
|
||||
src: ScalarSource::Immediate(0xffff_fffd)
|
||||
}
|
||||
@@ -1215,8 +759,7 @@ fn accepts_scalar_destination_105_and_vgpr_zero_add_sources() {
|
||||
let valid = 0xbee9_0380u32.to_le_bytes();
|
||||
assert_eq!(
|
||||
decode(Architecture::Gfx1030, &valid).unwrap()[0].instruction,
|
||||
Instruction::ScalarUnary {
|
||||
op: ScalarUnaryOp::MovB32,
|
||||
Instruction::ScalarMoveB32 {
|
||||
dst: 105,
|
||||
src: ScalarSource::Immediate(0)
|
||||
}
|
||||
@@ -1236,258 +779,10 @@ fn accepts_scalar_destination_105_and_vgpr_zero_add_sources() {
|
||||
let bytes: Vec<_> = words.iter().flat_map(|word| word.to_le_bytes()).collect();
|
||||
assert_eq!(
|
||||
decode(Architecture::Gfx1030, &bytes).unwrap()[0].instruction,
|
||||
Instruction::VectorAluVop3 {
|
||||
op: VectorAluVop3Op::AddNcU32,
|
||||
Instruction::AddNoCarryU32 {
|
||||
dst: 1,
|
||||
src0: 0,
|
||||
src1: 0
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decode_at_resolves_branch_targets_from_the_stream_offset() {
|
||||
let decoded = decode_at(Architecture::Gfx1030, BITWISE_FIXTURE, 0x1c).unwrap();
|
||||
assert_eq!(decoded.offset, 0x1c);
|
||||
assert_eq!(decoded.byte_len, 4);
|
||||
assert_eq!(decoded.branch_target(), Some(0x3c));
|
||||
// Alone, the same branch still reports its stream target; only the whole
|
||||
// stream can say whether that target is an instruction boundary.
|
||||
let isolated = decode_at(Architecture::Gfx1030, &BITWISE_FIXTURE[..0x20], 0x1c).unwrap();
|
||||
assert_eq!(isolated.branch_target(), Some(0x3c));
|
||||
assert_eq!(
|
||||
decode_at(
|
||||
Architecture::Gfx1030,
|
||||
BITWISE_FIXTURE,
|
||||
BITWISE_FIXTURE.len()
|
||||
),
|
||||
Err(DecodeError {
|
||||
offset: BITWISE_FIXTURE.len(),
|
||||
kind: DecodeErrorKind::Truncated {
|
||||
needed: 4,
|
||||
available: 0
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
// llvm-mc -triple=amdgcn -mcpu=gfx1030 -show-encoding
|
||||
const VOP3_INTEGER_ENCODINGS: [(VectorAluVop3Op, u32); 11] = [
|
||||
// v_mul_i32_i24_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x09,0xd5,0x00,0xff,0x02,0x02]
|
||||
(VectorAluVop3Op::MulI32I24, 0xd50900ff),
|
||||
// v_mul_hi_i32_i24_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x0a,0xd5,0x00,0xff,0x02,0x02]
|
||||
(VectorAluVop3Op::MulHiI32I24, 0xd50a00ff),
|
||||
// v_mul_u32_u24_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x0b,0xd5,0x00,0xff,0x02,0x02]
|
||||
(VectorAluVop3Op::MulU32U24, 0xd50b00ff),
|
||||
// v_mul_hi_u32_u24_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x0c,0xd5,0x00,0xff,0x02,0x02]
|
||||
(VectorAluVop3Op::MulHiU32U24, 0xd50c00ff),
|
||||
// v_min_i32_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x11,0xd5,0x00,0xff,0x02,0x02]
|
||||
(VectorAluVop3Op::MinI32, 0xd51100ff),
|
||||
// v_max_i32_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x12,0xd5,0x00,0xff,0x02,0x02]
|
||||
(VectorAluVop3Op::MaxI32, 0xd51200ff),
|
||||
// v_min_u32_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x13,0xd5,0x00,0xff,0x02,0x02]
|
||||
(VectorAluVop3Op::MinU32, 0xd51300ff),
|
||||
// v_max_u32_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x14,0xd5,0x00,0xff,0x02,0x02]
|
||||
(VectorAluVop3Op::MaxU32, 0xd51400ff),
|
||||
// v_xnor_b32_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x1e,0xd5,0x00,0xff,0x02,0x02]
|
||||
(VectorAluVop3Op::XnorB32, 0xd51e00ff),
|
||||
// v_sub_nc_u32_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x26,0xd5,0x00,0xff,0x02,0x02]
|
||||
(VectorAluVop3Op::SubNcU32, 0xd52600ff),
|
||||
// v_subrev_nc_u32_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x27,0xd5,0x00,0xff,0x02,0x02]
|
||||
(VectorAluVop3Op::SubrevNcU32, 0xd52700ff),
|
||||
];
|
||||
const VOP3_INTEGER_SOURCE_WORD: u32 = 0x0202_ff00;
|
||||
|
||||
#[test]
|
||||
fn decodes_registry_vop3_integer_encodings() {
|
||||
for (op, first) in VOP3_INTEGER_ENCODINGS {
|
||||
let bytes = [first.to_le_bytes(), VOP3_INTEGER_SOURCE_WORD.to_le_bytes()].concat();
|
||||
let decoded = decode(Architecture::Gfx1030, &bytes).unwrap();
|
||||
assert_eq!(decoded.len(), 1);
|
||||
assert_eq!(decoded[0].byte_len, 8);
|
||||
assert_eq!(
|
||||
decoded[0].instruction,
|
||||
Instruction::VectorAluVop3 {
|
||||
op,
|
||||
dst: 255,
|
||||
src0: 0,
|
||||
src1: 127,
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_vop3_integer_fixture() {
|
||||
use VectorAluVop3Op::*;
|
||||
|
||||
let code = include_bytes!("../../../fixtures/rdna2/vop3-integer.bin");
|
||||
let decoded = decode(Architecture::Gfx1030, code).unwrap();
|
||||
let expected = [
|
||||
(MulI32I24, 2, 1, 1),
|
||||
(MulHiI32I24, 3, 2, 1),
|
||||
(MulU32U24, 4, 2, 1),
|
||||
(MulHiU32U24, 255, 4, 1),
|
||||
(MinI32, 6, 1, 2),
|
||||
(MaxI32, 7, 1, 4),
|
||||
(MinU32, 8, 3, 1),
|
||||
(MaxU32, 9, 255, 2),
|
||||
(XnorB32, 10, 1, 255),
|
||||
(SubNcU32, 11, 6, 10),
|
||||
(SubrevNcU32, 1, 1, 9),
|
||||
];
|
||||
let actual: Vec<_> = decoded
|
||||
.iter()
|
||||
.filter_map(|decoded| match decoded.instruction {
|
||||
Instruction::VectorAluVop3 {
|
||||
op,
|
||||
dst,
|
||||
src0,
|
||||
src1,
|
||||
} => Some((decoded.offset, decoded.byte_len, op, dst, src0, src1)),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let expected: Vec<_> = expected
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(index, (op, dst, src0, src1))| (12 + 8 * index, 8, op, dst, src0, src1))
|
||||
.collect();
|
||||
assert_eq!(actual, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_registry_vop3_integer_modifiers_and_other_sources() {
|
||||
for (op, first) in VOP3_INTEGER_ENCODINGS {
|
||||
let second = VOP3_INTEGER_SOURCE_WORD;
|
||||
let reject = |first: u32, second: u32| {
|
||||
let bytes = [first.to_le_bytes(), second.to_le_bytes()].concat();
|
||||
let error = decode(Architecture::Gfx1030, &bytes)
|
||||
.expect_err(&format!("{op:?} accepted {first:#010x} {second:#010x}"));
|
||||
assert_eq!(error.offset, 0);
|
||||
assert!(matches!(
|
||||
error.kind,
|
||||
DecodeErrorKind::UnsupportedForm { mnemonic, .. }
|
||||
if mnemonic == op.assembly_name()
|
||||
));
|
||||
};
|
||||
|
||||
// First word: ABS[10:8], OP_SEL[14:11], CLAMP[15].
|
||||
for bit in 8..=15 {
|
||||
reject(first | (1 << bit), second);
|
||||
}
|
||||
// Second word: OMOD[28:27], NEG[31:29].
|
||||
for bit in 27..=31 {
|
||||
reject(first, second | (1 << bit));
|
||||
}
|
||||
|
||||
reject(first, second & !0x1ff); // SRC0 = s0
|
||||
reject(first, (second & !(0x1ff << 9)) | (128 << 9)); // SRC1 = inline zero
|
||||
reject(first, second | (1 << 18)); // SRC2 = inline one
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_sopk_immediates_and_rejects_non_sgpr_operands() {
|
||||
use xenora_decoder::ScalarImmediateCompareOp;
|
||||
let decode_word = |word: u32| decode(Architecture::Gfx1030, &word.to_le_bytes());
|
||||
// Words assembled by LLVM for gfx1030 (llvm-mc --show-encoding).
|
||||
// s_movk_i32 s8, 0x8000
|
||||
let decoded = decode_word(0xb008_8000).unwrap();
|
||||
assert_eq!(decoded[0].byte_len, 4);
|
||||
assert_eq!(
|
||||
decoded[0].instruction,
|
||||
Instruction::ScalarImmediate {
|
||||
op: ScalarImmediateOp::MovkI32,
|
||||
dst: 8,
|
||||
simm16: 0x8000
|
||||
}
|
||||
);
|
||||
// s_cmovk_i32 s105, 0xffff keeps the full 16 bits: the sign extension is
|
||||
// the translator's job, not the decoder's.
|
||||
assert_eq!(
|
||||
decode_word(0xb169_ffff).unwrap()[0].instruction,
|
||||
Instruction::ScalarImmediate {
|
||||
op: ScalarImmediateOp::CmovkI32,
|
||||
dst: 105,
|
||||
simm16: 0xffff
|
||||
}
|
||||
);
|
||||
// s_cmpk_gt_u32 s0, 0x1234 and s_cmpk_le_i32 s7, 0xffff read SDST s0-s7.
|
||||
assert_eq!(
|
||||
decode_word(0xb580_1234).unwrap()[0].instruction,
|
||||
Instruction::ScalarImmediateCompare {
|
||||
op: ScalarImmediateCompareOp::CmpkGtU32,
|
||||
src: 0,
|
||||
simm16: 0x1234
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
decode_word(0xb407_ffff).unwrap()[0].instruction,
|
||||
Instruction::ScalarImmediateCompare {
|
||||
op: ScalarImmediateCompareOp::CmpkLeI32,
|
||||
src: 7,
|
||||
simm16: 0xffff
|
||||
}
|
||||
);
|
||||
// s_addk_i32 s9, 0x7fff and s_mulk_i32 s105, 0
|
||||
assert_eq!(
|
||||
decode_word(0xb789_7fff).unwrap()[0].instruction,
|
||||
Instruction::ScalarImmediate {
|
||||
op: ScalarImmediateOp::AddkI32,
|
||||
dst: 9,
|
||||
simm16: 0x7fff
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
decode_word(0xb869_0000).unwrap()[0].instruction,
|
||||
Instruction::ScalarImmediate {
|
||||
op: ScalarImmediateOp::MulkI32,
|
||||
dst: 105,
|
||||
simm16: 0
|
||||
}
|
||||
);
|
||||
// vcc_lo, exec_lo, null and ttmp0 as SDST, and s_cmpk_eq_i32 m0: refused.
|
||||
for (word, mnemonic, detail) in [
|
||||
(
|
||||
0xb06a_0001,
|
||||
"s_movk_i32",
|
||||
"expected a normal SGPR destination",
|
||||
),
|
||||
(
|
||||
0xb07e_0001,
|
||||
"s_movk_i32",
|
||||
"expected a normal SGPR destination",
|
||||
),
|
||||
(
|
||||
0xb07d_0001,
|
||||
"s_movk_i32",
|
||||
"expected a normal SGPR destination",
|
||||
),
|
||||
(
|
||||
0xb06c_0001,
|
||||
"s_movk_i32",
|
||||
"expected a normal SGPR destination",
|
||||
),
|
||||
(
|
||||
0xb1fc_0001,
|
||||
"s_cmpk_eq_i32",
|
||||
"expected a normal SGPR operand",
|
||||
),
|
||||
] {
|
||||
assert_eq!(
|
||||
decode_word(word).unwrap_err().kind,
|
||||
DecodeErrorKind::UnsupportedForm { mnemonic, detail },
|
||||
"{word:#010x}"
|
||||
);
|
||||
}
|
||||
// Other SOPK opcodes (opcode 1 s_version, 17 s_getreg_b32) stay unsupported.
|
||||
for word in [0xb080_0000u32, 0xb888_0000] {
|
||||
assert!(decode_word(word).is_err(), "{word:#010x}");
|
||||
}
|
||||
// The fixed store fence is still the one decoded SOPK word outside the registry.
|
||||
assert_eq!(
|
||||
decode_word(0xbbfd_0000).unwrap()[0].instruction,
|
||||
Instruction::WaitStore
|
||||
);
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
//! Ties the decoder's declared semantic forms to what it decodes from LLVM-assembled fixtures.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
use xenora_decoder::{Architecture, SEMANTIC_FORMS, decode};
|
||||
use xenora_isa::meta::{FORMS, identify};
|
||||
|
||||
#[test]
|
||||
fn declared_semantic_forms_are_exactly_those_decoded_from_fixtures() {
|
||||
let directory = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/rdna2");
|
||||
let mut decoded = BTreeSet::new();
|
||||
for entry in fs::read_dir(directory).unwrap() {
|
||||
let path = entry.unwrap().path();
|
||||
if path.extension().is_none_or(|extension| extension != "bin") {
|
||||
continue;
|
||||
}
|
||||
let binary = fs::read(&path).unwrap();
|
||||
for instruction in decode(Architecture::Gfx1030, &binary).unwrap() {
|
||||
let found = identify(&binary[instruction.offset..]).unwrap();
|
||||
assert_eq!(
|
||||
found.len,
|
||||
usize::from(instruction.byte_len),
|
||||
"{}",
|
||||
path.display()
|
||||
);
|
||||
decoded.insert((found.form.name, found.form.family));
|
||||
}
|
||||
}
|
||||
let declared: BTreeSet<_> = SEMANTIC_FORMS.into_iter().collect();
|
||||
assert!(
|
||||
decoded.is_subset(&declared),
|
||||
"{:?}",
|
||||
decoded.difference(&declared)
|
||||
);
|
||||
// Covered by inline words in tests/gfx1030.rs rather than fixture binaries.
|
||||
let inline_only: BTreeSet<_> = declared
|
||||
.difference(&decoded)
|
||||
.map(|(name, _)| *name)
|
||||
.collect();
|
||||
assert_eq!(inline_only, BTreeSet::from(["IMAGE_SAMPLE_LZ"]));
|
||||
for (name, family) in SEMANTIC_FORMS {
|
||||
assert!(
|
||||
FORMS
|
||||
.iter()
|
||||
.any(|form| form.name == name && form.family == family),
|
||||
"{name}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registry_forms_do_not_duplicate_hand_written_forms() {
|
||||
// A form declared in the semantic registry and also decoded by hand-written
|
||||
// code would have two implementations; the hand-written one would win.
|
||||
let unique: BTreeSet<_> = SEMANTIC_FORMS.into_iter().collect();
|
||||
assert_eq!(unique.len(), SEMANTIC_FORMS.len());
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
[package]
|
||||
name = "xenora-ffi"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
description = "Versioned C interface between the native macOS application and the Xenora runtime"
|
||||
|
||||
[lib]
|
||||
crate-type = ["staticlib", "rlib"]
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[features]
|
||||
# Runs the tests that need a native Metal device (scripts/test-gpu.sh).
|
||||
gpu-tests = []
|
||||
|
||||
[dependencies]
|
||||
xenora-loader = { path = "../loader" }
|
||||
xenora-metal = { path = "../metal" }
|
||||
xenora-shader = { path = "../shader" }
|
||||
@@ -1,397 +0,0 @@
|
||||
/* SPDX-License-Identifier: GPL-3.0-or-later */
|
||||
/*
|
||||
* Xenora native application interface, version 1.
|
||||
*
|
||||
* Every function returns a xenora_status. Sessions are identified by opaque
|
||||
* 64-bit handles, never by pointers; 0 is never a valid handle. A destroyed
|
||||
* handle stays invalid even if its slot is reused. Output pointers are owned
|
||||
* by the caller and are written only when the call returns XENORA_OK.
|
||||
* All functions are thread-safe. No Rust panic crosses this boundary: one is
|
||||
* reported as XENORA_INTERNAL_ERROR.
|
||||
*/
|
||||
#ifndef XENORA_H
|
||||
#define XENORA_H
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
#define XENORA_ABI_VERSION 1u
|
||||
|
||||
typedef int32_t xenora_status;
|
||||
enum {
|
||||
XENORA_OK = 0,
|
||||
XENORA_INVALID_ARGUMENT = 1,
|
||||
XENORA_INVALID_HANDLE = 2,
|
||||
XENORA_VERSION_MISMATCH = 3,
|
||||
XENORA_INTERNAL_ERROR = 4,
|
||||
XENORA_PE_ERROR = 5,
|
||||
XENORA_LIMIT_EXCEEDED = 6,
|
||||
XENORA_BUFFER_TOO_SMALL = 7,
|
||||
XENORA_EXECUTION_FAILED = 8,
|
||||
XENORA_INVALID_STATE = 9,
|
||||
XENORA_FILE_NOT_FOUND = 10,
|
||||
XENORA_ACCESS_DENIED = 11,
|
||||
XENORA_IO_ERROR = 12,
|
||||
};
|
||||
|
||||
/* Frame-loop states reported by xenora_session_frame_loop_status. */
|
||||
enum {
|
||||
XENORA_LOOP_NONE = 0,
|
||||
XENORA_LOOP_RUNNING = 1,
|
||||
XENORA_LOOP_PAUSED = 2,
|
||||
XENORA_LOOP_FINISHED = 3,
|
||||
XENORA_LOOP_STOPPED = 4,
|
||||
XENORA_LOOP_FAILED = 5,
|
||||
};
|
||||
|
||||
#define XENORA_FRAME_LOOP_MAX_FRAMES 100000u
|
||||
/* Frame id reported when no frame has been completed yet. */
|
||||
#define XENORA_NO_FRAME 0xFFFFFFFFu
|
||||
|
||||
/* Input snapshot delivered to guest runtime services (Gate 4, #276). */
|
||||
typedef struct {
|
||||
uint32_t buttons;
|
||||
int16_t stick_x;
|
||||
int16_t stick_y;
|
||||
int16_t mouse_dx;
|
||||
int16_t mouse_dy;
|
||||
uint8_t mouse_buttons;
|
||||
uint8_t connected;
|
||||
uint16_t reserved;
|
||||
} xenora_input_state;
|
||||
|
||||
/* Extended controller snapshot. Trigger values span 0 to 65535. */
|
||||
typedef struct {
|
||||
xenora_input_state state;
|
||||
uint16_t left_trigger;
|
||||
uint16_t right_trigger;
|
||||
} xenora_controller_input;
|
||||
|
||||
#define XENORA_INPUT_NONE 0u
|
||||
#define XENORA_INPUT_RIGHT (1u << 0)
|
||||
#define XENORA_INPUT_LEFT (1u << 1)
|
||||
#define XENORA_INPUT_UP (1u << 2)
|
||||
#define XENORA_INPUT_DOWN (1u << 3)
|
||||
#define XENORA_INPUT_ACTION_A (1u << 4)
|
||||
#define XENORA_INPUT_ACTION_B (1u << 5)
|
||||
|
||||
/* Size of the frame drawn by the trusted fixture: RGBA8, rows top to bottom. */
|
||||
#define XENORA_FIXTURE_FRAME_WIDTH 4u
|
||||
#define XENORA_FIXTURE_FRAME_HEIGHT 3u
|
||||
|
||||
typedef uint64_t xenora_session;
|
||||
|
||||
/* The interface version this library implements. */
|
||||
uint32_t xenora_abi_version(void);
|
||||
|
||||
/* Create a session. `abi_version` must equal XENORA_ABI_VERSION. */
|
||||
xenora_status xenora_session_create(uint32_t abi_version, xenora_session *out_session);
|
||||
|
||||
/* Destroy a session. Destroying it again returns XENORA_INVALID_HANDLE. */
|
||||
xenora_status xenora_session_destroy(xenora_session session);
|
||||
|
||||
/* Parse the bundled trusted PE fixture with the runtime loader. No guest code runs. */
|
||||
xenora_status xenora_session_inspect_trusted_fixture(
|
||||
xenora_session session,
|
||||
uint32_t *out_section_count,
|
||||
uint32_t *out_entry_rva);
|
||||
|
||||
/*
|
||||
* Run the bundled trusted PE fixture: its x86-64 code is translated and executed,
|
||||
* and its single draw request is rendered on the native Metal device. On XENORA_OK,
|
||||
* `out_rgba` holds width * height * 4 bytes of the read-back frame, which has been
|
||||
* checked against the fixture shader's known output. `capacity` is the size of
|
||||
* `out_rgba` in bytes. Blocks the calling thread; call it off the main thread.
|
||||
* Only the embedded fixture can run; no caller-supplied executable is accepted.
|
||||
*/
|
||||
xenora_status xenora_session_run_trusted_fixture(
|
||||
xenora_session session,
|
||||
uint8_t *out_rgba,
|
||||
uint64_t capacity,
|
||||
uint32_t *out_width,
|
||||
uint32_t *out_height);
|
||||
|
||||
/*
|
||||
* Persistent rendering (one frame loop per session). Start runs the embedded
|
||||
* frame-loop fixture on a session-owned guest thread: the guest submits frames
|
||||
* 0, 1, 2, ... and each is rendered on native Metal and verified before it
|
||||
* becomes the latest frame. The guest stops after `frame_count` frames
|
||||
* (1..=XENORA_FRAME_LOOP_MAX_FRAMES). Pause holds the guest at its next frame
|
||||
* submission; resume continues it; stop makes it leave its loop and halt, and
|
||||
* waits for its thread. Destroying the session stops the loop first. Starting a
|
||||
* second loop on the same session returns XENORA_INVALID_STATE.
|
||||
*/
|
||||
xenora_status xenora_session_start_frame_loop(xenora_session session, uint32_t frame_count);
|
||||
xenora_status xenora_session_start_interactive_loop(xenora_session session, uint32_t frame_count);
|
||||
xenora_status xenora_session_send_input(xenora_session session, const xenora_input_state *input);
|
||||
xenora_status xenora_session_send_controller_input(xenora_session session, const xenora_controller_input *input);
|
||||
xenora_status xenora_session_queue_input(xenora_session session, const xenora_input_state *input);
|
||||
xenora_status xenora_session_pause_frame_loop(xenora_session session);
|
||||
xenora_status xenora_session_resume_frame_loop(xenora_session session);
|
||||
xenora_status xenora_session_stop_frame_loop(xenora_session session);
|
||||
|
||||
/*
|
||||
* Retrieve a previously completed frame by sequence index (0 <= frame_index < completed).
|
||||
* Used for deterministic replay verification and frame inspection.
|
||||
*/
|
||||
xenora_status xenora_session_get_recorded_frame(
|
||||
xenora_session session,
|
||||
uint32_t frame_index,
|
||||
uint32_t *out_frame_id,
|
||||
uint8_t *out_rgba,
|
||||
uint64_t capacity
|
||||
);
|
||||
|
||||
/*
|
||||
* Report the loop's state, the number of completed frames, and the latest
|
||||
* verified frame: its id (XENORA_NO_FRAME if none yet) and, when one exists,
|
||||
* its RGBA8 pixels (XENORA_FIXTURE_FRAME_WIDTH x HEIGHT) in `out_rgba`.
|
||||
*/
|
||||
xenora_status xenora_session_frame_loop_status(
|
||||
xenora_session session,
|
||||
uint32_t *out_state,
|
||||
uint32_t *out_completed,
|
||||
uint32_t *out_frame_id,
|
||||
uint8_t *out_rgba,
|
||||
uint64_t capacity);
|
||||
|
||||
/* Largest file xenora_inspect_executable accepts, in bytes. */
|
||||
#define XENORA_MAX_INSPECT_BYTES 268435456u
|
||||
|
||||
/* Opaque persistent GPU resource handle (Gate 5, #279) */
|
||||
typedef uint64_t xenora_resource;
|
||||
#define XENORA_NO_RESOURCE 0u
|
||||
|
||||
enum {
|
||||
XENORA_RESOURCE_TYPE_TEXTURE_2D = 1,
|
||||
XENORA_RESOURCE_TYPE_BUFFER = 2,
|
||||
};
|
||||
|
||||
/*
|
||||
* Create a persistent RGBA8 2D texture owned by the session.
|
||||
* If `initial_rgba` is non-null, it must point to at least width * height * 4 bytes.
|
||||
*/
|
||||
xenora_status xenora_session_create_texture(
|
||||
xenora_session session,
|
||||
uint32_t width,
|
||||
uint32_t height,
|
||||
const uint8_t *initial_rgba,
|
||||
xenora_resource *out_resource
|
||||
);
|
||||
|
||||
/*
|
||||
* Dynamically update a subregion of a persistent texture.
|
||||
*/
|
||||
xenora_status xenora_session_update_texture(
|
||||
xenora_session session,
|
||||
xenora_resource resource,
|
||||
uint32_t x,
|
||||
uint32_t y,
|
||||
uint32_t width,
|
||||
uint32_t height,
|
||||
const uint8_t *rgba,
|
||||
uint64_t byte_count
|
||||
);
|
||||
|
||||
/*
|
||||
* Destroy or retire a persistent resource. If in-flight GPU execution is using
|
||||
* the resource, destruction is deferred until the execution completes.
|
||||
*/
|
||||
xenora_status xenora_session_destroy_resource(
|
||||
xenora_session session,
|
||||
xenora_resource resource
|
||||
);
|
||||
|
||||
/*
|
||||
* Query type, dimensions, and in-flight status of a persistent resource.
|
||||
*/
|
||||
xenora_status xenora_session_resource_info(
|
||||
xenora_session session,
|
||||
xenora_resource resource,
|
||||
uint32_t *out_type,
|
||||
uint32_t *out_width,
|
||||
uint32_t *out_height,
|
||||
uint32_t *out_in_flight
|
||||
);
|
||||
|
||||
/*
|
||||
* Render a frame using a persistent texture resource.
|
||||
*/
|
||||
xenora_status xenora_session_render_textured(
|
||||
xenora_session session,
|
||||
xenora_resource resource,
|
||||
uint8_t *out_rgba,
|
||||
uint64_t capacity,
|
||||
uint32_t *out_width,
|
||||
uint32_t *out_height
|
||||
);
|
||||
|
||||
/*
|
||||
* Run the original textured PE fixture and verify its read-back frame.
|
||||
*/
|
||||
xenora_status xenora_session_run_textured_fixture(
|
||||
xenora_session session,
|
||||
uint8_t *out_rgba,
|
||||
uint64_t capacity,
|
||||
uint32_t *out_width,
|
||||
uint32_t *out_height
|
||||
);
|
||||
|
||||
/* Audio subsystem (Gate 6, #284) */
|
||||
typedef uint32_t xenora_audio_format;
|
||||
enum {
|
||||
XENORA_AUDIO_FORMAT_PCM_S16LE = 1,
|
||||
XENORA_AUDIO_FORMAT_PCM_F32LE = 2,
|
||||
};
|
||||
|
||||
/*
|
||||
* Initialize the audio subsystem for a session.
|
||||
*/
|
||||
xenora_status xenora_session_audio_init(
|
||||
xenora_session session,
|
||||
uint32_t sample_rate,
|
||||
uint32_t channels,
|
||||
xenora_audio_format format
|
||||
);
|
||||
|
||||
/*
|
||||
* Submit PCM audio bytes into the session audio queue.
|
||||
* byte_count must contain a whole number of interleaved sample frames.
|
||||
*/
|
||||
xenora_status xenora_session_audio_submit(
|
||||
xenora_session session,
|
||||
const uint8_t *pcm_bytes,
|
||||
uint64_t byte_count
|
||||
);
|
||||
|
||||
/*
|
||||
* Read PCM audio bytes from the session audio queue.
|
||||
* Only whole frames are returned. Any remaining output bytes are untouched.
|
||||
*/
|
||||
xenora_status xenora_session_audio_read(
|
||||
xenora_session session,
|
||||
uint8_t *out_pcm,
|
||||
uint64_t capacity,
|
||||
uint64_t *out_bytes_read
|
||||
);
|
||||
|
||||
/*
|
||||
* Fill one playback block with whole frames, padding a shortfall with silence.
|
||||
* out_source_bytes reports how much PCM was supplied before padding.
|
||||
*/
|
||||
xenora_status xenora_session_audio_render(
|
||||
xenora_session session,
|
||||
uint8_t *out_pcm,
|
||||
uint64_t byte_count,
|
||||
uint64_t *out_source_bytes
|
||||
);
|
||||
|
||||
/*
|
||||
* Query queued bytes, render calls that ran short, and total bytes submitted.
|
||||
*/
|
||||
xenora_status xenora_session_audio_status(
|
||||
xenora_session session,
|
||||
uint32_t *out_queued_bytes,
|
||||
uint32_t *out_underruns,
|
||||
uint64_t *out_total_submitted
|
||||
);
|
||||
|
||||
/*
|
||||
* Set audio volume (0.0 to 1.0) and mute state (non-zero = muted).
|
||||
*/
|
||||
xenora_status xenora_session_audio_set_volume(
|
||||
xenora_session session,
|
||||
float volume,
|
||||
uint32_t muted
|
||||
);
|
||||
|
||||
/* Virtual Filesystem (Gate 6, #284) */
|
||||
typedef uint64_t xenora_file;
|
||||
#define XENORA_NO_FILE 0u
|
||||
|
||||
enum {
|
||||
XENORA_SEEK_SET = 0,
|
||||
XENORA_SEEK_CUR = 1,
|
||||
XENORA_SEEK_END = 2,
|
||||
};
|
||||
|
||||
/*
|
||||
* Set the sandboxed root directory for the session virtual filesystem.
|
||||
*/
|
||||
xenora_status xenora_session_vfs_set_root(
|
||||
xenora_session session,
|
||||
const char *root_path
|
||||
);
|
||||
|
||||
/*
|
||||
* Open a file within the virtual filesystem sandboxed root.
|
||||
* Missing files return XENORA_FILE_NOT_FOUND. Host permission failures return
|
||||
* XENORA_ACCESS_DENIED. Other host I/O failures return XENORA_IO_ERROR.
|
||||
*/
|
||||
xenora_status xenora_session_vfs_open(
|
||||
xenora_session session,
|
||||
const char *rel_path,
|
||||
uint32_t flags,
|
||||
xenora_file *out_file
|
||||
);
|
||||
|
||||
/*
|
||||
* Read bytes from an open virtual file.
|
||||
*/
|
||||
xenora_status xenora_session_vfs_read(
|
||||
xenora_session session,
|
||||
xenora_file file,
|
||||
uint8_t *out_buffer,
|
||||
uint64_t count,
|
||||
uint64_t *out_bytes_read
|
||||
);
|
||||
|
||||
/*
|
||||
* Seek within an open virtual file.
|
||||
*/
|
||||
xenora_status xenora_session_vfs_seek(
|
||||
xenora_session session,
|
||||
xenora_file file,
|
||||
int64_t offset,
|
||||
uint32_t whence,
|
||||
uint64_t *out_new_offset
|
||||
);
|
||||
|
||||
/*
|
||||
* Close an open virtual file.
|
||||
*/
|
||||
xenora_status xenora_session_vfs_close(
|
||||
xenora_session session,
|
||||
xenora_file file
|
||||
);
|
||||
|
||||
/*
|
||||
* Run the original audio and VFS PE fixture.
|
||||
*/
|
||||
xenora_status xenora_session_run_audio_vfs_fixture(
|
||||
xenora_session session,
|
||||
uint8_t *out_rgba,
|
||||
uint64_t capacity,
|
||||
uint32_t *out_width,
|
||||
uint32_t *out_height,
|
||||
uint32_t *out_audio_samples
|
||||
);
|
||||
|
||||
/*
|
||||
* Read-only compatibility inspection of a caller-supplied PE file. Nothing in
|
||||
* `bytes` is executed: it is parsed and statically disassembled (bounded) only.
|
||||
* On XENORA_OK, XENORA_PE_ERROR or XENORA_INTERNAL_ERROR, `out_report` holds a
|
||||
* NUL-terminated UTF-8 report of `*out_required` bytes including the NUL.
|
||||
* XENORA_PE_ERROR means the file is not an acceptable PE32+ image;
|
||||
* XENORA_INTERNAL_ERROR means Xenora's own probe failed on it. The report says which. If `capacity`
|
||||
* is too small the call returns XENORA_BUFFER_TOO_SMALL with `*out_required`
|
||||
* set and nothing else written. Files over XENORA_MAX_INSPECT_BYTES return
|
||||
* XENORA_LIMIT_EXCEEDED.
|
||||
*/
|
||||
xenora_status xenora_inspect_executable(
|
||||
const uint8_t *bytes,
|
||||
uint64_t length,
|
||||
char *out_report,
|
||||
uint64_t capacity,
|
||||
uint64_t *out_required);
|
||||
|
||||
#endif
|
||||
@@ -1,407 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Persistent guest rendering for one session (Gate 3, #266).
|
||||
//!
|
||||
//! The embedded `frame-loop.exe` fixture calls `xenora.dll!frame_submit(index)`
|
||||
//! with index 0, 1, 2, ... and halts when the call returns 0. The guest runs on
|
||||
//! its own thread for the session's lifetime. Pause, resume and stop act at the
|
||||
//! frame-submit boundary: a paused guest waits inside that call with its
|
||||
//! architectural state untouched, and a stop request makes the call return 0 so
|
||||
//! the guest leaves its loop and halts.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock};
|
||||
use std::thread::JoinHandle;
|
||||
|
||||
use xenora_loader::startup::{StartupLayout, run_synthetic_startup};
|
||||
use xenora_loader::{ExitReason, ImportRegistry, Register};
|
||||
use xenora_metal::NativeCompute;
|
||||
use xenora_shader::{Architecture, PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics};
|
||||
|
||||
const FIXTURE: &[u8] = include_bytes!("../../../fixtures/pe/frame-loop.exe");
|
||||
const INTERACTIVE_FIXTURE: &[u8] = include_bytes!("../../../fixtures/pe/interactive.exe");
|
||||
pub const WIDTH: usize = 4;
|
||||
pub const HEIGHT: usize = 3;
|
||||
pub const FRAME_BYTES: usize = WIDTH * HEIGHT * 4;
|
||||
pub const MAX_FRAMES: u32 = 100_000;
|
||||
/// Guest instructions per loop iteration (mov, call, inc, test, jnz) plus slack.
|
||||
const STEPS_PER_FRAME: usize = 8;
|
||||
const STEPS_PER_INTERACTIVE_FRAME: usize = 24;
|
||||
/// `x9-constant-ps.s` exports (1, 0, 0, 1): opaque red. Everything else is the clear colour.
|
||||
const RED: [u8; 4] = [255, 0, 0, 255];
|
||||
const CLEAR: [u8; 4] = [19, 43, 93, 251];
|
||||
|
||||
pub const RUNNING: u32 = 1;
|
||||
pub const PAUSED: u32 = 2;
|
||||
pub const FINISHED: u32 = 3;
|
||||
pub const STOPPED: u32 = 4;
|
||||
pub const FAILED: u32 = 5;
|
||||
|
||||
#[derive(Default, Copy, Clone)]
|
||||
#[repr(C)]
|
||||
pub struct InputState {
|
||||
pub buttons: u32,
|
||||
pub stick_x: i16,
|
||||
pub stick_y: i16,
|
||||
pub mouse_dx: i16,
|
||||
pub mouse_dy: i16,
|
||||
pub mouse_buttons: u8,
|
||||
pub connected: u8,
|
||||
pub reserved: u16,
|
||||
}
|
||||
|
||||
#[derive(Default, Copy, Clone)]
|
||||
#[repr(C)]
|
||||
pub struct ControllerInput {
|
||||
pub state: InputState,
|
||||
pub left_trigger: u16,
|
||||
pub right_trigger: u16,
|
||||
}
|
||||
|
||||
impl ControllerInput {
|
||||
fn guest_bytes(self) -> [u8; 20] {
|
||||
let mut bytes = [0; 20];
|
||||
bytes[..4].copy_from_slice(&self.state.buttons.to_le_bytes());
|
||||
for (slot, value) in bytes[4..12].as_chunks_mut::<2>().0.iter_mut().zip([
|
||||
self.state.stick_x,
|
||||
self.state.stick_y,
|
||||
self.state.mouse_dx,
|
||||
self.state.mouse_dy,
|
||||
]) {
|
||||
*slot = value.to_le_bytes();
|
||||
}
|
||||
bytes[12] = self.state.mouse_buttons;
|
||||
bytes[13] = self.state.connected;
|
||||
bytes[16..18].copy_from_slice(&self.left_trigger.to_le_bytes());
|
||||
bytes[18..20].copy_from_slice(&self.right_trigger.to_le_bytes());
|
||||
bytes
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
status: u32,
|
||||
paused: bool,
|
||||
stop: bool,
|
||||
interactive: bool,
|
||||
limit: u32,
|
||||
completed: u32,
|
||||
input: ControllerInput,
|
||||
input_queue: std::collections::VecDeque<InputState>,
|
||||
recorded_frames: Vec<(u32, Vec<u8>)>,
|
||||
/// Every `frame_submit` call the guest made, including the one answered with 0.
|
||||
calls: u64,
|
||||
latest: Option<(u32, Vec<u8>)>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct FrameLoop {
|
||||
state: Mutex<State>,
|
||||
wake: Condvar,
|
||||
thread: Mutex<Option<JoinHandle<()>>>,
|
||||
}
|
||||
|
||||
pub struct Snapshot {
|
||||
pub status: u32,
|
||||
pub completed: u32,
|
||||
pub latest: Option<(u32, Vec<u8>)>,
|
||||
}
|
||||
|
||||
impl FrameLoop {
|
||||
fn lock(&self) -> MutexGuard<'_, State> {
|
||||
self.state
|
||||
.lock()
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner())
|
||||
}
|
||||
|
||||
pub fn start(limit: u32, interactive: bool) -> Arc<Self> {
|
||||
let shared = Arc::new(Self::default());
|
||||
{
|
||||
let mut state = shared.lock();
|
||||
state.status = RUNNING;
|
||||
state.limit = limit;
|
||||
state.interactive = interactive;
|
||||
}
|
||||
let guest = Arc::clone(&shared);
|
||||
let handle = std::thread::Builder::new()
|
||||
.name("xenora-guest".into())
|
||||
.spawn(move || guest.run())
|
||||
.ok();
|
||||
if handle.is_none() {
|
||||
shared.lock().status = FAILED;
|
||||
}
|
||||
*shared.thread.lock().unwrap_or_else(|p| p.into_inner()) = handle;
|
||||
shared
|
||||
}
|
||||
|
||||
/// Pause or resume. Returns false unless the loop is running or paused.
|
||||
pub fn set_paused(&self, paused: bool) -> bool {
|
||||
let mut state = self.lock();
|
||||
if !matches!(state.status, RUNNING | PAUSED) {
|
||||
return false;
|
||||
}
|
||||
state.paused = paused;
|
||||
state.status = if paused { PAUSED } else { RUNNING };
|
||||
self.wake.notify_all();
|
||||
true
|
||||
}
|
||||
|
||||
/// Ask the guest to stop at its next frame submission and wait for its thread.
|
||||
pub fn stop(&self) {
|
||||
{
|
||||
let mut state = self.lock();
|
||||
state.stop = true;
|
||||
self.wake.notify_all();
|
||||
}
|
||||
if let Some(handle) = self.thread.lock().unwrap_or_else(|p| p.into_inner()).take() {
|
||||
let _ = handle.join();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn send_input(&self, input: InputState) {
|
||||
self.send_controller_input(ControllerInput {
|
||||
state: input,
|
||||
..ControllerInput::default()
|
||||
});
|
||||
}
|
||||
|
||||
pub fn send_controller_input(&self, input: ControllerInput) {
|
||||
let mut state = self.lock();
|
||||
state.input = input;
|
||||
}
|
||||
|
||||
pub fn queue_input(&self, input: InputState) {
|
||||
let mut state = self.lock();
|
||||
state.input_queue.push_back(input);
|
||||
}
|
||||
|
||||
pub fn get_recorded_frame(&self, index: usize) -> Option<(u32, Vec<u8>)> {
|
||||
let state = self.lock();
|
||||
state.recorded_frames.get(index).cloned()
|
||||
}
|
||||
|
||||
pub fn snapshot(&self) -> Snapshot {
|
||||
let state = self.lock();
|
||||
Snapshot {
|
||||
status: state.status,
|
||||
completed: state.completed,
|
||||
latest: state.latest.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
fn run(self: Arc<Self>) {
|
||||
let outcome = self.execute();
|
||||
let mut state = self.lock();
|
||||
state.status = match outcome {
|
||||
Err(_) => FAILED,
|
||||
Ok(()) if state.stop && state.completed < state.limit => STOPPED,
|
||||
Ok(()) => FINISHED,
|
||||
};
|
||||
}
|
||||
|
||||
fn execute(self: &Arc<Self>) -> Result<(), String> {
|
||||
let shader = compile_graphics(
|
||||
Architecture::Gfx1030,
|
||||
include_bytes!("../../../fixtures/rdna2/x9-constant-vs.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/x9-constant-ps.bin"),
|
||||
)
|
||||
.map_err(|e| format!("shader translation: {e}"))?;
|
||||
let gpu = shared_gpu()?;
|
||||
// The import runs on the guest thread, so the session's shader lives there too.
|
||||
GPU.with(|slot| *slot.borrow_mut() = Some((gpu, shader.msl)));
|
||||
|
||||
let shared = Arc::clone(self);
|
||||
let mut imports = ImportRegistry::new();
|
||||
imports.register("xenora.dll", "frame_submit", move |args, _, memory| {
|
||||
let index = args.get(0, memory).map_err(ExitReason::MemoryFault)?;
|
||||
shared
|
||||
.submit(index)
|
||||
.ok_or(ExitReason::IllegalInstruction(0xff))
|
||||
});
|
||||
if self.lock().interactive {
|
||||
let shared_poll = Arc::clone(self);
|
||||
imports.register("xenora.dll", "input_poll", move |_args, _, _memory| {
|
||||
let mut state = shared_poll.lock();
|
||||
let input = state.input_queue.pop_front().unwrap_or(state.input.state);
|
||||
let cmd = if input.buttons & crate::XENORA_INPUT_RIGHT != 0 {
|
||||
1u64
|
||||
} else if input.buttons & crate::XENORA_INPUT_LEFT != 0 {
|
||||
2u64
|
||||
} else {
|
||||
0u64
|
||||
};
|
||||
Ok(cmd)
|
||||
});
|
||||
let snapshot = Arc::clone(self);
|
||||
imports.register(
|
||||
"xenora.dll",
|
||||
"input_poll_snapshot",
|
||||
move |args, _, memory| {
|
||||
let input = snapshot.lock().input;
|
||||
memory
|
||||
.write_bytes(args.rcx, &input.guest_bytes())
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
Ok(1)
|
||||
},
|
||||
);
|
||||
}
|
||||
let limit = self.lock().limit as usize;
|
||||
let is_interactive = self.lock().interactive;
|
||||
let fixture_bytes = if is_interactive {
|
||||
INTERACTIVE_FIXTURE
|
||||
} else {
|
||||
FIXTURE
|
||||
};
|
||||
let steps_per_frame = if is_interactive {
|
||||
STEPS_PER_INTERACTIVE_FRAME
|
||||
} else {
|
||||
STEPS_PER_FRAME
|
||||
};
|
||||
let startup = run_synthetic_startup(
|
||||
fixture_bytes,
|
||||
StartupLayout {
|
||||
image_base: 0x1_4000_0000,
|
||||
stack_top: 0x2_0001_0000,
|
||||
tls_base: 0x3_0000_0000,
|
||||
},
|
||||
imports,
|
||||
(limit + 1) * steps_per_frame + 32,
|
||||
)
|
||||
.map_err(|e| format!("startup: {e}"));
|
||||
GPU.with(|slot| slot.borrow_mut().take());
|
||||
let startup = startup?;
|
||||
let calls = self.lock().calls;
|
||||
let rbx = startup.execution.final_state.get(Register::Rbx);
|
||||
if startup.execution.exit_reason != ExitReason::Halt {
|
||||
return Err(format!(
|
||||
"guest ended with {:?}",
|
||||
startup.execution.exit_reason
|
||||
));
|
||||
}
|
||||
if !is_interactive && rbx != calls {
|
||||
return Err(format!("guest ended with rbx={rbx}, calls={calls}"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Handle one `frame_submit`: wait while paused, then render and verify the
|
||||
/// frame. `None` fails the guest; `Some(0)` tells it to stop.
|
||||
fn submit(&self, index: u64) -> Option<u64> {
|
||||
let mut state = self.lock();
|
||||
state.calls += 1;
|
||||
while state.paused && !state.stop {
|
||||
state = self.wake.wait(state).unwrap_or_else(|p| p.into_inner());
|
||||
}
|
||||
if state.stop || state.completed >= state.limit {
|
||||
return Some(0);
|
||||
}
|
||||
if state.interactive {
|
||||
if index >= WIDTH as u64 {
|
||||
return None; // column must be inside 0..WIDTH
|
||||
}
|
||||
} else if index != u64::from(state.completed) {
|
||||
return None; // frame identities must arrive in order
|
||||
}
|
||||
drop(state);
|
||||
let pixels = render(index as u32)?;
|
||||
let mut state = self.lock();
|
||||
state.completed += 1;
|
||||
state.latest = Some((index as u32, pixels.clone()));
|
||||
if state.interactive {
|
||||
state.recorded_frames.push((index as u32, pixels));
|
||||
}
|
||||
Some(u64::from(state.completed < state.limit && !state.stop))
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static GPU: RefCell<Option<(&'static NativeCompute, String)>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// One Metal device and command queue shared by every frame-loop session (#290).
|
||||
///
|
||||
/// The first command buffer submitted on a queue makes the GPU driver allocate a
|
||||
/// working set for it (about 45 MiB on an Apple M5 with Metal validation), and the
|
||||
/// driver frees that memory asynchronously, 10–50 ms after the queue is released.
|
||||
/// A queue per session therefore allocated and freed it once per session, and the
|
||||
/// process footprint depended on how far that release had progressed. One queue
|
||||
/// for the process allocates the working set once and keeps it: bounded caching,
|
||||
/// not per-session churn. `NativeCompute` is `Send + Sync`, and rendering takes
|
||||
/// `&self`, so concurrent sessions can share it. A device that cannot be opened
|
||||
/// is reported to every session that asks.
|
||||
fn shared_gpu() -> Result<&'static NativeCompute, String> {
|
||||
static SHARED: OnceLock<Result<NativeCompute, String>> = OnceLock::new();
|
||||
SHARED
|
||||
.get_or_init(|| NativeCompute::new().map_err(|e| format!("Metal device: {e}")))
|
||||
.as_ref()
|
||||
.map_err(Clone::clone)
|
||||
}
|
||||
|
||||
/// Frame `index` is a red strip in column `index % 4` on the clear colour.
|
||||
///
|
||||
/// The triangle (x0, -10), (x0 + 0.7, 0), (x0, 10) in clip space, with x0 the
|
||||
/// column's left edge, covers that column's pixel centres in all three rows and
|
||||
/// none of its neighbours'.
|
||||
fn render(index: u32) -> Option<Vec<u8>> {
|
||||
let column = (index as usize % WIDTH) as f32;
|
||||
let x0 = -1.0 + column * (2.0 / WIDTH as f32);
|
||||
let pixels = GPU.with(|slot| {
|
||||
let slot = slot.borrow();
|
||||
let (gpu, msl) = slot.as_ref()?;
|
||||
gpu.render_rgba8(
|
||||
msl,
|
||||
[VERTEX_ENTRY_POINT, PIXEL_ENTRY_POINT],
|
||||
&[
|
||||
[x0, -10.0, 0.5, 1.0],
|
||||
[x0 + 0.7, 0.0, 0.5, 1.0],
|
||||
[x0, 10.0, 0.5, 1.0],
|
||||
],
|
||||
&[[0.0; 4]; 3],
|
||||
[WIDTH, HEIGHT],
|
||||
CLEAR,
|
||||
)
|
||||
.ok()
|
||||
})?;
|
||||
(pixels == expected(index)).then_some(pixels)
|
||||
}
|
||||
|
||||
/// The expected frame for `index`, from the strip rule alone.
|
||||
pub fn expected(index: u32) -> Vec<u8> {
|
||||
(0..WIDTH * HEIGHT)
|
||||
.flat_map(|pixel| {
|
||||
if pixel % WIDTH == index as usize % WIDTH {
|
||||
RED
|
||||
} else {
|
||||
CLEAR
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[test]
|
||||
fn extended_controller_snapshot_retains_trigger_bytes_and_legacy_input_resets_them() {
|
||||
let running = FrameLoop::default();
|
||||
running.send_controller_input(ControllerInput {
|
||||
state: InputState {
|
||||
buttons: 0x10,
|
||||
stick_x: -32767,
|
||||
stick_y: 9,
|
||||
connected: 1,
|
||||
reserved: u16::MAX,
|
||||
..InputState::default()
|
||||
},
|
||||
left_trigger: 0x1234,
|
||||
right_trigger: u16::MAX,
|
||||
});
|
||||
let bytes = running.lock().input.guest_bytes();
|
||||
assert_eq!(std::mem::size_of::<ControllerInput>(), 20);
|
||||
assert_eq!(
|
||||
bytes,
|
||||
[
|
||||
16, 0, 0, 0, 1, 128, 9, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0x34, 0x12, 255, 255
|
||||
]
|
||||
);
|
||||
running.send_input(InputState::default());
|
||||
assert_eq!(running.lock().input.guest_bytes(), [0; 20]);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,379 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Gate 6 acceptance on a native Metal device: audio PCM streaming and
|
||||
//! sandboxed virtual filesystem (VFS) integration through the C interface (#284).
|
||||
//! Needs `--features gpu-tests` (scripts/test-gpu.sh).
|
||||
#![cfg(feature = "gpu-tests")]
|
||||
|
||||
use std::sync::Mutex;
|
||||
use xenora_ffi::*;
|
||||
|
||||
/// Tests share the process-wide session table and one GPU; run them one at a time.
|
||||
static SERIAL: Mutex<()> = Mutex::new(());
|
||||
|
||||
fn lock_serial() -> std::sync::MutexGuard<'static, ()> {
|
||||
SERIAL.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
fn session() -> u64 {
|
||||
let mut handle = 0;
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_create(XENORA_ABI_VERSION, &mut handle) },
|
||||
XENORA_OK
|
||||
);
|
||||
assert_ne!(handle, 0);
|
||||
handle
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn audio_pcm_queue_streaming_ordering_and_volume() {
|
||||
let _guard = lock_serial();
|
||||
let sess = session();
|
||||
|
||||
// Rejection on invalid arguments
|
||||
assert_eq!(
|
||||
xenora_session_audio_init(sess, 0, 2, XENORA_AUDIO_FORMAT_PCM_S16LE),
|
||||
XENORA_INVALID_ARGUMENT
|
||||
);
|
||||
assert_eq!(
|
||||
xenora_session_audio_init(0xdead_beef, 48000, 2, XENORA_AUDIO_FORMAT_PCM_S16LE),
|
||||
XENORA_INVALID_HANDLE
|
||||
);
|
||||
|
||||
// Initialize 48000 Hz stereo 16-bit PCM
|
||||
assert_eq!(
|
||||
xenora_session_audio_init(sess, 48000, 2, XENORA_AUDIO_FORMAT_PCM_S16LE),
|
||||
XENORA_OK
|
||||
);
|
||||
|
||||
// Initial status should be empty
|
||||
let (mut queued, mut underruns, mut total) = (0u32, 0u32, 0u64);
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_audio_status(sess, &mut queued, &mut underruns, &mut total) },
|
||||
XENORA_OK
|
||||
);
|
||||
assert_eq!(queued, 0);
|
||||
assert_eq!(underruns, 0);
|
||||
assert_eq!(total, 0);
|
||||
|
||||
// Generate known PCM samples: 100 stereo samples (400 bytes)
|
||||
let mut pcm = Vec::with_capacity(400);
|
||||
for i in 0..100i16 {
|
||||
let left = i * 100;
|
||||
let right = -left;
|
||||
pcm.extend_from_slice(&left.to_le_bytes());
|
||||
pcm.extend_from_slice(&right.to_le_bytes());
|
||||
}
|
||||
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_audio_submit(sess, pcm.as_ptr(), pcm.len() as u64) },
|
||||
XENORA_OK
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_audio_status(sess, &mut queued, &mut underruns, &mut total) },
|
||||
XENORA_OK
|
||||
);
|
||||
assert_eq!(queued, 400);
|
||||
assert_eq!(total, 400);
|
||||
assert_eq!(underruns, 0);
|
||||
|
||||
// Read back first 50 samples (200 bytes)
|
||||
let mut read_buf = vec![0u8; 200];
|
||||
let mut bytes_read = 0u64;
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_audio_read(sess, read_buf.as_mut_ptr(), 200, &mut bytes_read) },
|
||||
XENORA_OK
|
||||
);
|
||||
assert_eq!(bytes_read, 200);
|
||||
assert_eq!(&read_buf[..], &pcm[..200]);
|
||||
|
||||
// Volume attenuation: set to 0.5
|
||||
assert_eq!(xenora_session_audio_set_volume(sess, 0.5, 0), XENORA_OK);
|
||||
|
||||
// Submit 2 stereo samples (8 bytes): 2000, -2000, 4000, -4000
|
||||
let mut half_vol_in = Vec::new();
|
||||
half_vol_in.extend_from_slice(&2000i16.to_le_bytes());
|
||||
half_vol_in.extend_from_slice(&(-2000i16).to_le_bytes());
|
||||
half_vol_in.extend_from_slice(&4000i16.to_le_bytes());
|
||||
half_vol_in.extend_from_slice(&(-4000i16).to_le_bytes());
|
||||
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
xenora_session_audio_submit(sess, half_vol_in.as_ptr(), half_vol_in.len() as u64)
|
||||
},
|
||||
XENORA_OK
|
||||
);
|
||||
|
||||
// Read remaining 200 bytes from first batch
|
||||
let mut drain = vec![0u8; 200];
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_audio_read(sess, drain.as_mut_ptr(), 200, &mut bytes_read) },
|
||||
XENORA_OK
|
||||
);
|
||||
assert_eq!(bytes_read, 200);
|
||||
assert_eq!(&drain[..], &pcm[200..]);
|
||||
|
||||
// Now read the 8 bytes attenuated samples
|
||||
let mut attenuated = vec![0u8; 8];
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_audio_read(sess, attenuated.as_mut_ptr(), 8, &mut bytes_read) },
|
||||
XENORA_OK
|
||||
);
|
||||
assert_eq!(bytes_read, 8);
|
||||
let s0 = i16::from_le_bytes([attenuated[0], attenuated[1]]);
|
||||
let s1 = i16::from_le_bytes([attenuated[2], attenuated[3]]);
|
||||
let s2 = i16::from_le_bytes([attenuated[4], attenuated[5]]);
|
||||
let s3 = i16::from_le_bytes([attenuated[6], attenuated[7]]);
|
||||
assert_eq!(s0, 1000);
|
||||
assert_eq!(s1, -1000);
|
||||
assert_eq!(s2, 2000);
|
||||
assert_eq!(s3, -2000);
|
||||
|
||||
// Test mute (muted = 1)
|
||||
assert_eq!(xenora_session_audio_set_volume(sess, 1.0, 1), XENORA_OK);
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
xenora_session_audio_submit(sess, half_vol_in.as_ptr(), half_vol_in.len() as u64)
|
||||
},
|
||||
XENORA_OK
|
||||
);
|
||||
let mut muted_out = vec![0u8; 8];
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_audio_read(sess, muted_out.as_mut_ptr(), 8, &mut bytes_read) },
|
||||
XENORA_OK
|
||||
);
|
||||
assert_eq!(muted_out, vec![0u8; 8]);
|
||||
|
||||
xenora_session_destroy(sess);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn virtual_filesystem_sandboxing_and_traversal_rejection() {
|
||||
let _guard = lock_serial();
|
||||
let sess = session();
|
||||
|
||||
let mut file = 0u64;
|
||||
|
||||
// Reject non-existent root
|
||||
let bad_root = std::ffi::CString::new("/nonexistent_dir_xenora").unwrap();
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_vfs_set_root(sess, bad_root.as_ptr()) },
|
||||
XENORA_INVALID_ARGUMENT
|
||||
);
|
||||
|
||||
// Set valid root
|
||||
let root_path = if std::path::Path::new("fixtures/assets").exists() {
|
||||
"fixtures/assets"
|
||||
} else {
|
||||
"../../fixtures/assets"
|
||||
};
|
||||
let c_root = std::ffi::CString::new(root_path).unwrap();
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_vfs_set_root(sess, c_root.as_ptr()) },
|
||||
XENORA_OK
|
||||
);
|
||||
|
||||
// Traversal attacks rejected
|
||||
for bad in &[
|
||||
"../escape.txt",
|
||||
"../../etc/passwd",
|
||||
"/etc/passwd",
|
||||
"sub/../../secret",
|
||||
"",
|
||||
] {
|
||||
let bad_c = std::ffi::CString::new(*bad).unwrap();
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_vfs_open(sess, bad_c.as_ptr(), 0, &mut file) },
|
||||
XENORA_INVALID_ARGUMENT,
|
||||
"traversal attempt '{}' was not rejected",
|
||||
bad
|
||||
);
|
||||
}
|
||||
|
||||
let missing = std::ffi::CString::new("missing-xenora-test-asset.bin").unwrap();
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_vfs_open(sess, missing.as_ptr(), 0, &mut file) },
|
||||
XENORA_FILE_NOT_FOUND
|
||||
);
|
||||
assert_eq!(file, XENORA_NO_FILE);
|
||||
|
||||
// Open existing valid asset
|
||||
let good = std::ffi::CString::new("asset.bin").unwrap();
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_vfs_open(sess, good.as_ptr(), 0, &mut file) },
|
||||
XENORA_OK
|
||||
);
|
||||
assert_ne!(file, XENORA_NO_FILE);
|
||||
|
||||
// Read header (20 bytes: 4B magic + 4B ver + 4B width + 4B height + 4B audio_samples)
|
||||
let mut header = [0u8; 20];
|
||||
let mut read_bytes = 0u64;
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_vfs_read(sess, file, header.as_mut_ptr(), 20, &mut read_bytes) },
|
||||
XENORA_OK
|
||||
);
|
||||
assert_eq!(read_bytes, 20);
|
||||
assert_eq!(&header[0..4], b"XAST");
|
||||
let version = u32::from_le_bytes([header[4], header[5], header[6], header[7]]);
|
||||
assert_eq!(version, 1);
|
||||
let width = u32::from_le_bytes([header[8], header[9], header[10], header[11]]);
|
||||
assert_eq!(width, 2);
|
||||
let height = u32::from_le_bytes([header[12], header[13], header[14], header[15]]);
|
||||
assert_eq!(height, 2);
|
||||
let audio_samples = u32::from_le_bytes([header[16], header[17], header[18], header[19]]);
|
||||
assert_eq!(audio_samples, 256);
|
||||
|
||||
// Seek to audio offset (36) using SEEK_SET
|
||||
let mut new_pos = 0u64;
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_vfs_seek(sess, file, 36, XENORA_SEEK_SET, &mut new_pos) },
|
||||
XENORA_OK
|
||||
);
|
||||
assert_eq!(new_pos, 36);
|
||||
|
||||
// Read 4 bytes of audio
|
||||
let mut sample_bytes = [0u8; 4];
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
xenora_session_vfs_read(sess, file, sample_bytes.as_mut_ptr(), 4, &mut read_bytes)
|
||||
},
|
||||
XENORA_OK
|
||||
);
|
||||
assert_eq!(read_bytes, 4);
|
||||
|
||||
// Seek using SEEK_END
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_vfs_seek(sess, file, 0, XENORA_SEEK_END, &mut new_pos) },
|
||||
XENORA_OK
|
||||
);
|
||||
assert_eq!(new_pos, 20 + 16 + 512); // total asset size = 548 bytes
|
||||
|
||||
// Close file
|
||||
assert_eq!(xenora_session_vfs_close(sess, file), XENORA_OK);
|
||||
|
||||
// Double close rejected
|
||||
assert_eq!(xenora_session_vfs_close(sess, file), XENORA_INVALID_HANDLE);
|
||||
|
||||
xenora_session_destroy(sess);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn audio_vfs_guest_fixture_executes_asset_load_and_pcm_stream() {
|
||||
let _guard = lock_serial();
|
||||
let sess = session();
|
||||
|
||||
let mut out_rgba = [0u8; 16];
|
||||
let mut out_w = 0u32;
|
||||
let mut out_h = 0u32;
|
||||
let mut out_samples = 0u32;
|
||||
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
xenora_session_run_audio_vfs_fixture(
|
||||
sess,
|
||||
out_rgba.as_mut_ptr(),
|
||||
16,
|
||||
&mut out_w,
|
||||
&mut out_h,
|
||||
&mut out_samples,
|
||||
)
|
||||
},
|
||||
XENORA_OK
|
||||
);
|
||||
|
||||
assert_eq!(out_w, 2);
|
||||
assert_eq!(out_h, 2);
|
||||
assert_eq!(out_samples, 256);
|
||||
|
||||
// Expected texture from asset.bin: 2x2 RGBA8:
|
||||
// (0,0): Orange [255, 128, 0, 255]
|
||||
// (1,0): Purple [128, 0, 255, 255]
|
||||
// (0,1): Teal [0, 255, 128, 255]
|
||||
// (1,1): Pink [255, 0, 128, 255]
|
||||
let expected_rgba: [u8; 16] = [
|
||||
255, 128, 0, 255, 128, 0, 255, 255, 0, 255, 128, 255, 255, 0, 128, 255,
|
||||
];
|
||||
assert_eq!(
|
||||
out_rgba, expected_rgba,
|
||||
"Metal rendered frame did not match asset texture"
|
||||
);
|
||||
|
||||
// Audio status: guest submitted 256 samples (512 bytes)
|
||||
let (mut queued, mut underruns, mut total) = (0u32, 0u32, 0u64);
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_audio_status(sess, &mut queued, &mut underruns, &mut total) },
|
||||
XENORA_OK
|
||||
);
|
||||
assert_eq!(queued, 512);
|
||||
assert_eq!(total, 512);
|
||||
assert_eq!(underruns, 0);
|
||||
|
||||
// Read back submitted audio samples and verify
|
||||
let mut pcm_buf = vec![0u8; 512];
|
||||
let mut read_bytes = 0u64;
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_audio_read(sess, pcm_buf.as_mut_ptr(), 512, &mut read_bytes) },
|
||||
XENORA_OK
|
||||
);
|
||||
assert_eq!(read_bytes, 512);
|
||||
|
||||
// The first sample in asset.bin sine wave is 0
|
||||
let s0 = i16::from_le_bytes([pcm_buf[0], pcm_buf[1]]);
|
||||
assert_eq!(s0, 0);
|
||||
|
||||
xenora_session_destroy(sess);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn audio_vfs_rejection_of_invalid_and_stale_handles() {
|
||||
let _guard = lock_serial();
|
||||
let dead_sess = 0xdead_beefu64;
|
||||
|
||||
let mut queued = 0u32;
|
||||
let mut underruns = 0u32;
|
||||
let mut total = 0u64;
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_audio_status(dead_sess, &mut queued, &mut underruns, &mut total) },
|
||||
XENORA_INVALID_HANDLE
|
||||
);
|
||||
|
||||
let mut file = 0u64;
|
||||
let path = std::ffi::CString::new("asset.bin").unwrap();
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_vfs_open(dead_sess, path.as_ptr(), 0, &mut file) },
|
||||
XENORA_INVALID_HANDLE
|
||||
);
|
||||
|
||||
let sess = session();
|
||||
// Null pointer checks
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_vfs_open(sess, std::ptr::null(), 0, &mut file) },
|
||||
XENORA_INVALID_ARGUMENT
|
||||
);
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_vfs_open(sess, path.as_ptr(), 0, std::ptr::null_mut()) },
|
||||
XENORA_INVALID_ARGUMENT
|
||||
);
|
||||
|
||||
// Buffer too small for fixture
|
||||
let mut small_buf = [0u8; 8];
|
||||
let mut w = 0u32;
|
||||
let mut h = 0u32;
|
||||
let mut samples = 0u32;
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
xenora_session_run_audio_vfs_fixture(
|
||||
sess,
|
||||
small_buf.as_mut_ptr(),
|
||||
8,
|
||||
&mut w,
|
||||
&mut h,
|
||||
&mut samples,
|
||||
)
|
||||
},
|
||||
XENORA_BUFFER_TOO_SMALL
|
||||
);
|
||||
|
||||
xenora_session_destroy(sess);
|
||||
}
|
||||
@@ -1,396 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Gate 3 acceptance on a native Metal device: persistent guest rendering through
|
||||
//! the C interface. Needs `--features gpu-tests` (scripts/test-gpu.sh).
|
||||
#![cfg(feature = "gpu-tests")]
|
||||
|
||||
use std::sync::Mutex;
|
||||
use std::time::{Duration, Instant};
|
||||
use xenora_ffi::*;
|
||||
|
||||
/// Tests share the process-wide session table and one GPU; run them one at a time.
|
||||
static SERIAL: Mutex<()> = Mutex::new(());
|
||||
|
||||
/// Expected frame `id`, derived only from the geometry: the guest's frame index picks
|
||||
/// column `id % 4`, which is opaque red (x9-constant-ps exports (1, 0, 0, 1)); the
|
||||
/// other columns keep the clear colour (19, 43, 93, 251).
|
||||
fn expected(id: u32) -> Vec<u8> {
|
||||
let mut frame = Vec::new();
|
||||
for _row in 0..3 {
|
||||
for column in 0..4 {
|
||||
if column == id % 4 {
|
||||
frame.extend([255, 0, 0, 255]);
|
||||
} else {
|
||||
frame.extend([19, 43, 93, 251]);
|
||||
}
|
||||
}
|
||||
}
|
||||
frame
|
||||
}
|
||||
|
||||
struct Status {
|
||||
state: u32,
|
||||
completed: u32,
|
||||
frame_id: u32,
|
||||
rgba: [u8; 48],
|
||||
}
|
||||
|
||||
fn status(session: u64) -> Status {
|
||||
let mut s = Status {
|
||||
state: 99,
|
||||
completed: 0,
|
||||
frame_id: 0,
|
||||
rgba: [0; 48],
|
||||
};
|
||||
let code = unsafe {
|
||||
xenora_session_frame_loop_status(
|
||||
session,
|
||||
&mut s.state,
|
||||
&mut s.completed,
|
||||
&mut s.frame_id,
|
||||
s.rgba.as_mut_ptr(),
|
||||
48,
|
||||
)
|
||||
};
|
||||
assert_eq!(code, XENORA_OK);
|
||||
s
|
||||
}
|
||||
|
||||
fn session() -> u64 {
|
||||
let mut session = 0;
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_create(XENORA_ABI_VERSION, &mut session) },
|
||||
XENORA_OK
|
||||
);
|
||||
session
|
||||
}
|
||||
|
||||
fn wait_until(session: u64, what: &str, done: impl Fn(&Status) -> bool) -> Status {
|
||||
let deadline = Instant::now() + Duration::from_secs(60);
|
||||
loop {
|
||||
let s = status(session);
|
||||
if done(&s) {
|
||||
return s;
|
||||
}
|
||||
assert!(
|
||||
Instant::now() < deadline,
|
||||
"timed out waiting for {what} (state {}, completed {})",
|
||||
s.state,
|
||||
s.completed
|
||||
);
|
||||
std::thread::sleep(Duration::from_millis(2));
|
||||
}
|
||||
}
|
||||
|
||||
/// Physical memory footprint of this process (macOS `proc_pid_rusage`, RUSAGE_INFO_V2).
|
||||
fn footprint() -> u64 {
|
||||
unsafe extern "C" {
|
||||
fn proc_pid_rusage(pid: i32, flavor: i32, buffer: *mut [u64; 32]) -> i32;
|
||||
}
|
||||
let mut info = [0u64; 32];
|
||||
assert_eq!(
|
||||
unsafe { proc_pid_rusage(std::process::id() as i32, 2, &mut info) },
|
||||
0
|
||||
);
|
||||
info[9] // after the 16-byte UUID: user, system, idle wakeups, interrupts, pageins, wired, resident, footprint
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn three_hundred_guest_frames_arrive_verified_and_in_order() {
|
||||
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
|
||||
let session = session();
|
||||
assert_eq!(xenora_session_start_frame_loop(session, 300), XENORA_OK);
|
||||
assert_eq!(
|
||||
xenora_session_start_frame_loop(session, 300),
|
||||
XENORA_INVALID_STATE
|
||||
);
|
||||
let s = wait_until(session, "300 frames", |s| s.state != XENORA_LOOP_RUNNING);
|
||||
assert_eq!(s.state, XENORA_LOOP_FINISHED);
|
||||
assert_eq!(s.completed, 300);
|
||||
assert_eq!(s.frame_id, 299);
|
||||
assert_eq!(s.rgba.to_vec(), expected(299));
|
||||
assert_eq!(xenora_session_destroy(session), XENORA_OK);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn observed_frame_ids_never_go_backwards_and_match_their_pixels() {
|
||||
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
|
||||
let session = session();
|
||||
assert_eq!(xenora_session_start_frame_loop(session, 2_000), XENORA_OK);
|
||||
let mut previous = None;
|
||||
let mut samples = 0;
|
||||
loop {
|
||||
let s = status(session);
|
||||
if s.frame_id != XENORA_NO_FRAME {
|
||||
if let Some(p) = previous {
|
||||
assert!(s.frame_id >= p, "frame id went from {p} to {}", s.frame_id);
|
||||
}
|
||||
assert!(
|
||||
s.frame_id < s.completed,
|
||||
"id {} not below completed {}",
|
||||
s.frame_id,
|
||||
s.completed
|
||||
);
|
||||
assert_eq!(
|
||||
s.rgba.to_vec(),
|
||||
expected(s.frame_id),
|
||||
"frame {}",
|
||||
s.frame_id
|
||||
);
|
||||
previous = Some(s.frame_id);
|
||||
samples += 1;
|
||||
}
|
||||
if s.state != XENORA_LOOP_RUNNING {
|
||||
assert_eq!(s.state, XENORA_LOOP_FINISHED);
|
||||
assert_eq!((s.completed, s.frame_id), (2_000, 1_999));
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(samples > 1);
|
||||
xenora_session_destroy(session);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pause_holds_the_guest_resume_continues_and_stop_halts_it() {
|
||||
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
|
||||
let session = session();
|
||||
assert_eq!(
|
||||
xenora_session_start_frame_loop(session, XENORA_FRAME_LOOP_MAX_FRAMES),
|
||||
XENORA_OK
|
||||
);
|
||||
wait_until(session, "10 frames", |s| s.completed >= 10);
|
||||
|
||||
assert_eq!(xenora_session_pause_frame_loop(session), XENORA_OK);
|
||||
// At most the frame already being rendered can still complete after pausing.
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
let held = status(session);
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
let later = status(session);
|
||||
assert_eq!(later.state, XENORA_LOOP_PAUSED);
|
||||
assert_eq!(later.completed, held.completed, "no frames while paused");
|
||||
assert_eq!(later.frame_id, held.completed - 1);
|
||||
assert_eq!(later.rgba.to_vec(), expected(later.frame_id));
|
||||
|
||||
assert_eq!(xenora_session_resume_frame_loop(session), XENORA_OK);
|
||||
let resumed = wait_until(session, "progress after resume", |s| {
|
||||
s.completed >= held.completed + 10
|
||||
});
|
||||
assert_eq!(resumed.state, XENORA_LOOP_RUNNING);
|
||||
|
||||
assert_eq!(xenora_session_stop_frame_loop(session), XENORA_OK);
|
||||
let stopped = status(session);
|
||||
assert_eq!(stopped.state, XENORA_LOOP_STOPPED);
|
||||
assert!(stopped.completed < XENORA_FRAME_LOOP_MAX_FRAMES);
|
||||
assert_eq!(stopped.frame_id, stopped.completed - 1);
|
||||
assert_eq!(stopped.rgba.to_vec(), expected(stopped.frame_id));
|
||||
// Pause and resume are refused once the guest has halted.
|
||||
assert_eq!(
|
||||
xenora_session_pause_frame_loop(session),
|
||||
XENORA_INVALID_STATE
|
||||
);
|
||||
assert_eq!(
|
||||
xenora_session_resume_frame_loop(session),
|
||||
XENORA_INVALID_STATE
|
||||
);
|
||||
assert_eq!(xenora_session_destroy(session), XENORA_OK);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn destroying_a_running_or_paused_session_stops_it() {
|
||||
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
|
||||
for pause_first in [false, true] {
|
||||
let session = session();
|
||||
assert_eq!(
|
||||
xenora_session_start_frame_loop(session, XENORA_FRAME_LOOP_MAX_FRAMES),
|
||||
XENORA_OK
|
||||
);
|
||||
wait_until(session, "a frame", |s| s.completed >= 1);
|
||||
if pause_first {
|
||||
assert_eq!(xenora_session_pause_frame_loop(session), XENORA_OK);
|
||||
}
|
||||
let started = Instant::now();
|
||||
assert_eq!(xenora_session_destroy(session), XENORA_OK);
|
||||
assert!(
|
||||
started.elapsed() < Duration::from_secs(5),
|
||||
"destroy joined promptly"
|
||||
);
|
||||
let mut x = 0;
|
||||
let mut rgba = [0u8; 48];
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
xenora_session_frame_loop_status(
|
||||
session,
|
||||
&mut x,
|
||||
&mut x,
|
||||
&mut x,
|
||||
rgba.as_mut_ptr(),
|
||||
48,
|
||||
)
|
||||
},
|
||||
XENORA_INVALID_HANDLE
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_sessions_do_not_grow_the_memory_footprint() {
|
||||
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
|
||||
let run = || {
|
||||
let session = session();
|
||||
assert_eq!(xenora_session_start_frame_loop(session, 300), XENORA_OK);
|
||||
let s = wait_until(session, "300 frames", |s| s.state != XENORA_LOOP_RUNNING);
|
||||
assert_eq!((s.state, s.completed), (XENORA_LOOP_FINISHED, 300));
|
||||
assert_eq!(xenora_session_destroy(session), XENORA_OK);
|
||||
};
|
||||
// Warm up so one-time allocations (Metal device, shader compiler) are excluded.
|
||||
run();
|
||||
run();
|
||||
let baseline = footprint();
|
||||
for _ in 0..5 {
|
||||
run();
|
||||
}
|
||||
let after = footprint();
|
||||
let growth = after.saturating_sub(baseline);
|
||||
println!("footprint baseline={baseline} after_5_sessions={after} growth={growth}");
|
||||
assert!(
|
||||
growth < 16 << 20,
|
||||
"footprint grew by {growth} bytes over 5 sessions of 300 frames"
|
||||
);
|
||||
}
|
||||
|
||||
/// Regression test for #290: the footprint read right after each destroy must stay
|
||||
/// flat across many sessions. Each session used to open its own Metal command queue,
|
||||
/// and the GPU driver frees a queue's working set (about 45 MiB on an Apple M5 with
|
||||
/// validation) asynchronously after release, so these readings swung by about 50 MiB
|
||||
/// from session to session. Sessions now share one queue. The mix of sessions covers
|
||||
/// normal completion, pause and resume, and destruction while running.
|
||||
#[test]
|
||||
fn fifty_sessions_keep_a_flat_footprint_after_each_destroy() {
|
||||
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
|
||||
let one = |kind: usize| {
|
||||
let session = session();
|
||||
match kind {
|
||||
0 => {
|
||||
assert_eq!(xenora_session_start_frame_loop(session, 100), XENORA_OK);
|
||||
let s = wait_until(session, "100 frames", |s| s.state != XENORA_LOOP_RUNNING);
|
||||
assert_eq!((s.state, s.completed), (XENORA_LOOP_FINISHED, 100));
|
||||
}
|
||||
1 => {
|
||||
assert_eq!(xenora_session_start_frame_loop(session, 100), XENORA_OK);
|
||||
wait_until(session, "10 frames", |s| s.completed >= 10);
|
||||
assert_eq!(xenora_session_pause_frame_loop(session), XENORA_OK);
|
||||
assert_eq!(xenora_session_resume_frame_loop(session), XENORA_OK);
|
||||
let s = wait_until(session, "100 frames", |s| s.state != XENORA_LOOP_RUNNING);
|
||||
assert_eq!((s.state, s.completed), (XENORA_LOOP_FINISHED, 100));
|
||||
}
|
||||
_ => {
|
||||
assert_eq!(
|
||||
xenora_session_start_frame_loop(session, XENORA_FRAME_LOOP_MAX_FRAMES),
|
||||
XENORA_OK
|
||||
);
|
||||
wait_until(session, "a frame", |s| s.completed >= 1);
|
||||
}
|
||||
}
|
||||
assert_eq!(xenora_session_destroy(session), XENORA_OK);
|
||||
footprint()
|
||||
};
|
||||
one(0); // the first session allocates the shared queue's working set
|
||||
let readings: Vec<u64> = (0..50).map(|i| one(i % 3)).collect();
|
||||
let mib: Vec<u64> = readings.iter().map(|r| r >> 20).collect();
|
||||
println!("footprint after each destroy (MiB): {mib:?}");
|
||||
let median = |values: &[u64]| {
|
||||
let mut sorted = values.to_vec();
|
||||
sorted.sort_unstable();
|
||||
sorted[sorted.len() / 2]
|
||||
};
|
||||
// Sustained growth: the typical reading at the end against the start.
|
||||
let (start, end) = (median(&readings[..10]), median(&readings[40..]));
|
||||
assert!(
|
||||
end.saturating_sub(start) < 16 << 20,
|
||||
"footprint grew from {start} to {end} bytes (median of first and last ten sessions)"
|
||||
);
|
||||
// Per-session churn, the cause fixed in #290: with a queue per session, about half
|
||||
// of all readings sat some 45 MiB away from the median. With the shared queue,
|
||||
// a reading is still occasionally caught while the driver frees a batch of
|
||||
// per-frame render resources: graphics-tagged memory only, 16 to 44 MiB, gone
|
||||
// within about 100 ms, measured in 13 of 6,000 sessions (0.22%). Allowing two such
|
||||
// readings in 50 keeps a false failure near 1 in 5,000 runs while per-session
|
||||
// churn would exceed it every time.
|
||||
let centre = median(&readings);
|
||||
let outliers: Vec<u64> = readings
|
||||
.iter()
|
||||
.filter(|&&r| r.abs_diff(centre) >= 16 << 20)
|
||||
.map(|r| r >> 20)
|
||||
.collect();
|
||||
assert!(
|
||||
outliers.len() <= 2,
|
||||
"{} of 50 readings were 16 MiB or more from the median {} MiB: {outliers:?}",
|
||||
outliers.len(),
|
||||
centre >> 20
|
||||
);
|
||||
}
|
||||
|
||||
/// Two sessions render at the same time through the shared Metal queue (#290). Each
|
||||
/// must keep its own frame sequence and pixels, pausing one must not stop the other,
|
||||
/// and destroying one mid-run must not disturb the other.
|
||||
#[test]
|
||||
fn concurrent_sessions_share_the_queue_but_stay_isolated() {
|
||||
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
|
||||
let (a, b) = (session(), session());
|
||||
assert_eq!(xenora_session_start_frame_loop(a, 400), XENORA_OK);
|
||||
assert_eq!(xenora_session_start_frame_loop(b, 250), XENORA_OK);
|
||||
wait_until(a, "session A started", |s| s.completed >= 5);
|
||||
wait_until(b, "session B started", |s| s.completed >= 5);
|
||||
|
||||
// Pausing A holds only A.
|
||||
assert_eq!(xenora_session_pause_frame_loop(a), XENORA_OK);
|
||||
let a_held = wait_until(a, "session A paused", |s| s.state == XENORA_LOOP_PAUSED);
|
||||
let b_before = status(b).completed;
|
||||
let b_moving = wait_until(b, "session B progress while A is paused", |s| {
|
||||
s.completed >= b_before + 20 || s.state != XENORA_LOOP_RUNNING
|
||||
});
|
||||
assert!(
|
||||
b_moving.completed > b_before,
|
||||
"B kept rendering while A was paused"
|
||||
);
|
||||
let a_still = status(a);
|
||||
assert_eq!(a_still.state, XENORA_LOOP_PAUSED);
|
||||
// At most the frame A was rendering when paused can still complete.
|
||||
assert!(a_still.completed <= a_held.completed + 1);
|
||||
assert_eq!(a_still.rgba.to_vec(), expected(a_still.frame_id));
|
||||
assert_eq!(xenora_session_resume_frame_loop(a), XENORA_OK);
|
||||
|
||||
// Both finish with their own counts and their own final frames.
|
||||
let a_done = wait_until(a, "session A finished", |s| s.state != XENORA_LOOP_RUNNING);
|
||||
let b_done = wait_until(b, "session B finished", |s| s.state != XENORA_LOOP_RUNNING);
|
||||
assert_eq!(
|
||||
(a_done.state, a_done.completed, a_done.frame_id),
|
||||
(XENORA_LOOP_FINISHED, 400, 399)
|
||||
);
|
||||
assert_eq!(
|
||||
(b_done.state, b_done.completed, b_done.frame_id),
|
||||
(XENORA_LOOP_FINISHED, 250, 249)
|
||||
);
|
||||
assert_eq!(a_done.rgba.to_vec(), expected(399));
|
||||
assert_eq!(b_done.rgba.to_vec(), expected(249));
|
||||
assert_eq!(xenora_session_destroy(a), XENORA_OK);
|
||||
assert_eq!(xenora_session_destroy(b), XENORA_OK);
|
||||
|
||||
// Destroying one running session leaves the other running to completion.
|
||||
let (c, d) = (session(), session());
|
||||
assert_eq!(
|
||||
xenora_session_start_frame_loop(c, XENORA_FRAME_LOOP_MAX_FRAMES),
|
||||
XENORA_OK
|
||||
);
|
||||
assert_eq!(xenora_session_start_frame_loop(d, 300), XENORA_OK);
|
||||
wait_until(c, "session C started", |s| s.completed >= 5);
|
||||
wait_until(d, "session D started", |s| s.completed >= 5);
|
||||
assert_eq!(xenora_session_destroy(c), XENORA_OK);
|
||||
let d_done = wait_until(d, "session D finished", |s| s.state != XENORA_LOOP_RUNNING);
|
||||
assert_eq!(
|
||||
(d_done.state, d_done.completed, d_done.frame_id),
|
||||
(XENORA_LOOP_FINISHED, 300, 299)
|
||||
);
|
||||
assert_eq!(d_done.rgba.to_vec(), expected(299));
|
||||
assert_eq!(xenora_session_destroy(d), XENORA_OK);
|
||||
}
|
||||
@@ -1,298 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Gate 4 acceptance on a native Metal device: interactive guest execution with
|
||||
//! dynamic input handling and rendering through the C interface.
|
||||
//! Needs `--features gpu-tests` (scripts/test-gpu.sh).
|
||||
#![cfg(feature = "gpu-tests")]
|
||||
|
||||
use std::sync::Mutex;
|
||||
use std::time::{Duration, Instant};
|
||||
use xenora_ffi::*;
|
||||
|
||||
/// Tests share the process-wide session table and one GPU; run them one at a time.
|
||||
static SERIAL: Mutex<()> = Mutex::new(());
|
||||
|
||||
/// Expected frame `column` (0..3): column `column` is opaque red (255, 0, 0, 255);
|
||||
/// all other columns keep the clear colour (19, 43, 93, 251).
|
||||
fn expected(column: u32) -> Vec<u8> {
|
||||
let mut frame = Vec::new();
|
||||
for _row in 0..3 {
|
||||
for col in 0..4 {
|
||||
if col == column % 4 {
|
||||
frame.extend([255, 0, 0, 255]);
|
||||
} else {
|
||||
frame.extend([19, 43, 93, 251]);
|
||||
}
|
||||
}
|
||||
}
|
||||
frame
|
||||
}
|
||||
|
||||
struct Status {
|
||||
state: u32,
|
||||
completed: u32,
|
||||
frame_id: u32,
|
||||
rgba: [u8; 48],
|
||||
}
|
||||
|
||||
fn status(session: u64) -> Status {
|
||||
let mut s = Status {
|
||||
state: 99,
|
||||
completed: 0,
|
||||
frame_id: 0,
|
||||
rgba: [0; 48],
|
||||
};
|
||||
let code = unsafe {
|
||||
xenora_session_frame_loop_status(
|
||||
session,
|
||||
&mut s.state,
|
||||
&mut s.completed,
|
||||
&mut s.frame_id,
|
||||
s.rgba.as_mut_ptr(),
|
||||
48,
|
||||
)
|
||||
};
|
||||
assert_eq!(code, XENORA_OK);
|
||||
s
|
||||
}
|
||||
|
||||
fn session() -> u64 {
|
||||
let mut session = 0;
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_create(XENORA_ABI_VERSION, &mut session) },
|
||||
XENORA_OK
|
||||
);
|
||||
session
|
||||
}
|
||||
|
||||
fn send_buttons(session: u64, buttons: u32) {
|
||||
let input = xenora_input_state {
|
||||
buttons,
|
||||
stick_x: 0,
|
||||
stick_y: 0,
|
||||
mouse_dx: 0,
|
||||
mouse_dy: 0,
|
||||
mouse_buttons: 0,
|
||||
connected: 1,
|
||||
reserved: 0,
|
||||
};
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_send_input(session, &input) },
|
||||
XENORA_OK
|
||||
);
|
||||
}
|
||||
|
||||
fn queue_buttons(session: u64, buttons: u32) {
|
||||
let input = xenora_input_state {
|
||||
buttons,
|
||||
stick_x: 0,
|
||||
stick_y: 0,
|
||||
mouse_dx: 0,
|
||||
mouse_dy: 0,
|
||||
mouse_buttons: 0,
|
||||
connected: 1,
|
||||
reserved: 0,
|
||||
};
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_queue_input(session, &input) },
|
||||
XENORA_OK
|
||||
);
|
||||
}
|
||||
|
||||
fn wait_until(session: u64, what: &str, done: impl Fn(&Status) -> bool) -> Status {
|
||||
let deadline = Instant::now() + Duration::from_secs(60);
|
||||
loop {
|
||||
let s = status(session);
|
||||
if done(&s) {
|
||||
return s;
|
||||
}
|
||||
assert!(
|
||||
Instant::now() < deadline,
|
||||
"timed out waiting for {what} (state {}, completed {})",
|
||||
s.state,
|
||||
s.completed
|
||||
);
|
||||
std::thread::sleep(Duration::from_millis(2));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interactive_input_moves_guest_column_and_updates_pixels() {
|
||||
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
|
||||
let session = session();
|
||||
|
||||
// Start interactive loop with 120 frames
|
||||
assert_eq!(
|
||||
xenora_session_start_interactive_loop(session, 120),
|
||||
XENORA_OK
|
||||
);
|
||||
|
||||
// Initial frames without input stay at column 0
|
||||
let s = wait_until(session, "initial frames", |s| s.completed >= 5);
|
||||
assert_eq!(s.frame_id, 0);
|
||||
assert_eq!(s.rgba.to_vec(), expected(0));
|
||||
|
||||
// Send Right input: column should advance 0 -> 1 -> 2 -> 3 -> 0
|
||||
send_buttons(session, XENORA_INPUT_RIGHT);
|
||||
let s_right = wait_until(session, "column moves right", |s| {
|
||||
s.completed >= 15 && s.frame_id != 0
|
||||
});
|
||||
assert_eq!(s_right.rgba.to_vec(), expected(s_right.frame_id));
|
||||
|
||||
// Release input: position stops moving
|
||||
send_buttons(session, XENORA_INPUT_NONE);
|
||||
let s_hold_start = wait_until(session, "wait for release frame", |s| {
|
||||
s.completed >= s_right.completed + 2
|
||||
});
|
||||
let hold_col = s_hold_start.frame_id;
|
||||
let s_hold = wait_until(session, "position holds on release", |s| {
|
||||
s.completed >= s_hold_start.completed + 10
|
||||
});
|
||||
assert_eq!(s_hold.frame_id, hold_col);
|
||||
assert_eq!(s_hold.rgba.to_vec(), expected(s_hold.frame_id));
|
||||
|
||||
// Send Left input: column should move left
|
||||
send_buttons(session, XENORA_INPUT_LEFT);
|
||||
let s_left = wait_until(session, "column moves left", |s| {
|
||||
s.completed >= s_hold.completed + 10 && s.frame_id != hold_col
|
||||
});
|
||||
assert_eq!(s_left.rgba.to_vec(), expected(s_left.frame_id));
|
||||
|
||||
// Wait until finished
|
||||
let s_end = wait_until(session, "loop finish", |s| s.state == XENORA_LOOP_FINISHED);
|
||||
assert_eq!(s_end.completed, 120);
|
||||
|
||||
assert_eq!(xenora_session_destroy(session), XENORA_OK);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deterministic_input_replay_produces_identical_frames() {
|
||||
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
|
||||
|
||||
// Timeline of inputs across 60 frames:
|
||||
// frames 0..15: Right
|
||||
// frames 15..30: None
|
||||
// frames 30..45: Left
|
||||
// frames 45..60: Right
|
||||
let replay_sequence: Vec<u32> = (0..60)
|
||||
.map(|f| {
|
||||
if f < 15 {
|
||||
XENORA_INPUT_RIGHT
|
||||
} else if f < 30 {
|
||||
XENORA_INPUT_NONE
|
||||
} else if f < 45 {
|
||||
XENORA_INPUT_LEFT
|
||||
} else {
|
||||
XENORA_INPUT_RIGHT
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
let run_replay = || {
|
||||
let session = session();
|
||||
assert_eq!(
|
||||
xenora_session_start_interactive_loop(session, 60),
|
||||
XENORA_OK
|
||||
);
|
||||
|
||||
// Pre-queue the complete input sequence
|
||||
for &btn in &replay_sequence {
|
||||
queue_buttons(session, btn);
|
||||
}
|
||||
|
||||
// Wait until all 60 frames are rendered
|
||||
let s = wait_until(session, "replay completion", |s| {
|
||||
s.state == XENORA_LOOP_FINISHED && s.completed == 60
|
||||
});
|
||||
assert_eq!(s.completed, 60);
|
||||
|
||||
// Inspect all 60 recorded frames
|
||||
let mut frames = Vec::with_capacity(60);
|
||||
for i in 0..60 {
|
||||
let mut id = 0u32;
|
||||
let mut rgba = [0u8; 48];
|
||||
let code = unsafe {
|
||||
xenora_session_get_recorded_frame(session, i, &mut id, rgba.as_mut_ptr(), 48)
|
||||
};
|
||||
assert_eq!(code, XENORA_OK);
|
||||
assert_eq!(rgba.to_vec(), expected(id));
|
||||
frames.push((id, rgba));
|
||||
}
|
||||
|
||||
assert_eq!(xenora_session_destroy(session), XENORA_OK);
|
||||
frames
|
||||
};
|
||||
|
||||
let run1 = run_replay();
|
||||
let run2 = run_replay();
|
||||
|
||||
assert_eq!(run1.len(), 60);
|
||||
assert_eq!(run2.len(), 60);
|
||||
for i in 0..60 {
|
||||
assert_eq!(
|
||||
run1[i].0, run2[i].0,
|
||||
"frame {} column mismatch: {} vs {}",
|
||||
i, run1[i].0, run2[i].0
|
||||
);
|
||||
assert_eq!(run1[i].1, run2[i].1, "frame {} pixel mismatch", i);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn focus_loss_and_release_resets_input_cleanly() {
|
||||
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
|
||||
let session = session();
|
||||
|
||||
assert_eq!(
|
||||
xenora_session_start_interactive_loop(session, 100),
|
||||
XENORA_OK
|
||||
);
|
||||
|
||||
// Send Right
|
||||
send_buttons(session, XENORA_INPUT_RIGHT);
|
||||
let s1 = wait_until(session, "moving right", |s| s.completed >= 10);
|
||||
|
||||
// Simulate focus loss / key release
|
||||
send_buttons(session, XENORA_INPUT_NONE);
|
||||
// Wait for the release to take effect in the guest
|
||||
let s_released = wait_until(session, "release takes effect", |s| {
|
||||
s.completed >= s1.completed + 2
|
||||
});
|
||||
let stopped_col = s_released.frame_id;
|
||||
|
||||
// Check next 15 frames: frame_id must remain fixed at stopped_col
|
||||
let s2 = wait_until(session, "hold after release", |s| {
|
||||
s.completed >= s_released.completed + 15
|
||||
});
|
||||
assert_eq!(s2.frame_id, stopped_col);
|
||||
assert_eq!(s2.rgba.to_vec(), expected(stopped_col));
|
||||
|
||||
// Clean stop
|
||||
assert_eq!(xenora_session_stop_frame_loop(session), XENORA_OK);
|
||||
let s_stopped = wait_until(session, "stopped", |s| s.state == XENORA_LOOP_STOPPED);
|
||||
assert_eq!(s_stopped.state, XENORA_LOOP_STOPPED);
|
||||
|
||||
assert_eq!(xenora_session_destroy(session), XENORA_OK);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn destroying_interactive_session_stops_cleanly() {
|
||||
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
|
||||
let session = session();
|
||||
|
||||
assert_eq!(
|
||||
xenora_session_start_interactive_loop(session, 5000),
|
||||
XENORA_OK
|
||||
);
|
||||
|
||||
// Wait until it actually starts rendering
|
||||
wait_until(session, "running", |s| s.completed >= 5);
|
||||
|
||||
let start = Instant::now();
|
||||
assert_eq!(xenora_session_destroy(session), XENORA_OK);
|
||||
assert!(
|
||||
start.elapsed() < Duration::from_millis(500),
|
||||
"destroy took too long: {:?}",
|
||||
start.elapsed()
|
||||
);
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Runs the trusted fixture through the C interface on a native Metal device.
|
||||
//! Needs `--features gpu-tests` (scripts/test-gpu.sh).
|
||||
#![cfg(feature = "gpu-tests")]
|
||||
|
||||
use xenora_ffi::*;
|
||||
|
||||
/// fixtures/rdna2/x9-constant-ps.s: `v_mov_b32 v8, 1.0; v_mov_b32 v9, 0;
|
||||
/// exp mrt0, v8, v9, v9, v8` writes (1, 0, 0, 1); as RGBA8 unorm that is (255, 0, 0, 255).
|
||||
const SHADER_OUTPUT: [u8; 4] = [255, 0, 0, 255];
|
||||
|
||||
#[test]
|
||||
fn guest_fixture_frame_reaches_the_caller_through_metal() {
|
||||
for run in 0..3 {
|
||||
let mut session = 0;
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_create(XENORA_ABI_VERSION, &mut session) },
|
||||
XENORA_OK
|
||||
);
|
||||
let (mut rgba, mut width, mut height) = ([0u8; 64], 0u32, 0u32);
|
||||
let status = unsafe {
|
||||
xenora_session_run_trusted_fixture(
|
||||
session,
|
||||
rgba.as_mut_ptr(),
|
||||
64,
|
||||
&mut width,
|
||||
&mut height,
|
||||
)
|
||||
};
|
||||
assert_eq!(status, XENORA_OK, "run {run}");
|
||||
assert_eq!((width, height), (4, 3));
|
||||
assert_eq!(&rgba[..48], SHADER_OUTPUT.repeat(12).as_slice());
|
||||
assert!(
|
||||
rgba[48..].iter().all(|&b| b == 0),
|
||||
"no write past the frame"
|
||||
);
|
||||
assert_eq!(xenora_session_destroy(session), XENORA_OK);
|
||||
}
|
||||
}
|
||||
@@ -1,375 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Gate 5 acceptance on a native Metal device: persistent GPU resources,
|
||||
//! dynamic texture updates, and completion-aware resource retirement through
|
||||
//! the C interface (#279).
|
||||
//! Needs `--features gpu-tests` (scripts/test-gpu.sh).
|
||||
#![cfg(feature = "gpu-tests")]
|
||||
|
||||
use std::sync::Mutex;
|
||||
use xenora_ffi::*;
|
||||
|
||||
/// Tests share the process-wide session table and one GPU; run them one at a time.
|
||||
static SERIAL: Mutex<()> = Mutex::new(());
|
||||
|
||||
fn session() -> u64 {
|
||||
let mut handle = 0;
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_create(XENORA_ABI_VERSION, &mut handle) },
|
||||
XENORA_OK
|
||||
);
|
||||
assert_ne!(handle, 0);
|
||||
handle
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn persistent_texture_lifecycle_survives_across_multiple_frames() {
|
||||
let _guard = SERIAL.lock().unwrap();
|
||||
let sess = session();
|
||||
|
||||
// 2x2 initial texture:
|
||||
// (0,0)=red, (1,0)=green, (0,1)=blue, (1,1)=white
|
||||
let initial_rgba: [u8; 16] = [
|
||||
255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255,
|
||||
];
|
||||
|
||||
let mut res = 0u64;
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_create_texture(sess, 2, 2, initial_rgba.as_ptr(), &mut res) },
|
||||
XENORA_OK
|
||||
);
|
||||
assert_ne!(res, XENORA_NO_RESOURCE);
|
||||
|
||||
// Render 5 consecutive frames from this single persistent texture resource without re-allocation.
|
||||
for frame_idx in 0..5 {
|
||||
let mut out_rgba = [0u8; 16];
|
||||
let mut out_w = 0u32;
|
||||
let mut out_h = 0u32;
|
||||
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
xenora_session_render_textured(
|
||||
sess,
|
||||
res,
|
||||
out_rgba.as_mut_ptr(),
|
||||
16,
|
||||
&mut out_w,
|
||||
&mut out_h,
|
||||
)
|
||||
},
|
||||
XENORA_OK,
|
||||
"render frame {} failed",
|
||||
frame_idx
|
||||
);
|
||||
|
||||
assert_eq!(out_w, 2);
|
||||
assert_eq!(out_h, 2);
|
||||
assert_eq!(
|
||||
out_rgba, initial_rgba,
|
||||
"frame {} pixel mismatch with persistent texture",
|
||||
frame_idx
|
||||
);
|
||||
}
|
||||
|
||||
// Verify resource is still live and un-retired after all frames
|
||||
let (mut r_type, mut r_w, mut r_h, mut r_flight) = (0u32, 0u32, 0u32, 0u32);
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
xenora_session_resource_info(sess, res, &mut r_type, &mut r_w, &mut r_h, &mut r_flight)
|
||||
},
|
||||
XENORA_OK
|
||||
);
|
||||
assert_eq!(r_type, XENORA_RESOURCE_TYPE_TEXTURE_2D);
|
||||
assert_eq!(r_w, 2);
|
||||
assert_eq!(r_h, 2);
|
||||
assert_eq!(r_flight, 0);
|
||||
|
||||
assert_eq!(xenora_session_destroy_resource(sess, res), XENORA_OK);
|
||||
assert_eq!(xenora_session_destroy(sess), XENORA_OK);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dynamic_texture_subregion_update_is_reflected_on_metal() {
|
||||
let _guard = SERIAL.lock().unwrap();
|
||||
let sess = session();
|
||||
|
||||
// 2x2 initial texture:
|
||||
// (0,0)=red, (1,0)=green, (0,1)=blue, (1,1)=white
|
||||
let initial_rgba: [u8; 16] = [
|
||||
255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255,
|
||||
];
|
||||
|
||||
let mut res = 0u64;
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_create_texture(sess, 2, 2, initial_rgba.as_ptr(), &mut res) },
|
||||
XENORA_OK
|
||||
);
|
||||
|
||||
// 1. Update 1x1 subregion at (x=1, y=0) from green to yellow [255, 255, 0, 255]
|
||||
let yellow_pixel = [255u8, 255, 0, 255];
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_update_texture(sess, res, 1, 0, 1, 1, yellow_pixel.as_ptr(), 4) },
|
||||
XENORA_OK
|
||||
);
|
||||
|
||||
let mut frame1 = [0u8; 16];
|
||||
let (mut w, mut h) = (0u32, 0u32);
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
xenora_session_render_textured(sess, res, frame1.as_mut_ptr(), 16, &mut w, &mut h)
|
||||
},
|
||||
XENORA_OK
|
||||
);
|
||||
|
||||
let expected_frame1: [u8; 16] = [
|
||||
255, 0, 0, 255, // (0,0) red (untouched)
|
||||
255, 255, 0, 255, // (1,0) yellow (updated)
|
||||
0, 0, 255, 255, // (0,1) blue (untouched)
|
||||
255, 255, 255, 255, // (1,1) white (untouched)
|
||||
];
|
||||
assert_eq!(
|
||||
frame1, expected_frame1,
|
||||
"Metal read-back did not reflect 1x1 subregion update"
|
||||
);
|
||||
|
||||
// 2. Update 2x1 subregion across the bottom row: (0,1) and (1,1)
|
||||
// (0,1)=magenta [255, 0, 255, 255], (1,1)=cyan [0, 255, 255, 255]
|
||||
let bottom_row = [255u8, 0, 255, 255, 0, 255, 255, 255];
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_update_texture(sess, res, 0, 1, 2, 1, bottom_row.as_ptr(), 8) },
|
||||
XENORA_OK
|
||||
);
|
||||
|
||||
let mut frame2 = [0u8; 16];
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
xenora_session_render_textured(sess, res, frame2.as_mut_ptr(), 16, &mut w, &mut h)
|
||||
},
|
||||
XENORA_OK
|
||||
);
|
||||
|
||||
let expected_frame2: [u8; 16] = [
|
||||
255, 0, 0, 255, // (0,0) red
|
||||
255, 255, 0, 255, // (1,0) yellow
|
||||
255, 0, 255, 255, // (0,1) magenta
|
||||
0, 255, 255, 255, // (1,1) cyan
|
||||
];
|
||||
assert_eq!(
|
||||
frame2, expected_frame2,
|
||||
"Metal read-back did not reflect 2x1 bottom row update"
|
||||
);
|
||||
|
||||
assert_eq!(xenora_session_destroy_resource(sess, res), XENORA_OK);
|
||||
assert_eq!(xenora_session_destroy(sess), XENORA_OK);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deferred_resource_retirement_safely_waits_for_completion() {
|
||||
let _guard = SERIAL.lock().unwrap();
|
||||
let sess = session();
|
||||
|
||||
let mut res = 0u64;
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_create_texture(sess, 2, 2, std::ptr::null(), &mut res) },
|
||||
XENORA_OK
|
||||
);
|
||||
|
||||
// Acquire an in-flight reference simulating active GPU encoding/submission
|
||||
assert_eq!(test_acquire_resource_in_flight(sess, res), Ok(()));
|
||||
|
||||
let (mut r_type, mut r_w, mut r_h, mut r_flight) = (0u32, 0u32, 0u32, 0u32);
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
xenora_session_resource_info(sess, res, &mut r_type, &mut r_w, &mut r_h, &mut r_flight)
|
||||
},
|
||||
XENORA_OK
|
||||
);
|
||||
assert_eq!(r_flight, 1);
|
||||
|
||||
// Calling destroy while in-flight marks the resource retired without dangling pointers
|
||||
assert_eq!(xenora_session_destroy_resource(sess, res), XENORA_OK);
|
||||
|
||||
// Subsequent caller operations on the retired handle are rejected
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
xenora_session_resource_info(sess, res, &mut r_type, &mut r_w, &mut r_h, &mut r_flight)
|
||||
},
|
||||
XENORA_INVALID_HANDLE
|
||||
);
|
||||
assert_eq!(
|
||||
xenora_session_destroy_resource(sess, res),
|
||||
XENORA_INVALID_HANDLE
|
||||
);
|
||||
|
||||
let dummy_pixel = [0u8; 4];
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_update_texture(sess, res, 0, 0, 1, 1, dummy_pixel.as_ptr(), 4) },
|
||||
XENORA_INVALID_HANDLE
|
||||
);
|
||||
|
||||
let mut out_rgba = [0u8; 16];
|
||||
let (mut w, mut h) = (0u32, 0u32);
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
xenora_session_render_textured(sess, res, out_rgba.as_mut_ptr(), 16, &mut w, &mut h)
|
||||
},
|
||||
XENORA_INVALID_HANDLE
|
||||
);
|
||||
|
||||
// Now in-flight execution completes and releases its reference
|
||||
assert_eq!(test_release_resource_in_flight(sess, res), Ok(()));
|
||||
|
||||
// The slot is now safely reclaimed; the next allocation reuses the slot with a new generation
|
||||
let mut res2 = 0u64;
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_create_texture(sess, 2, 2, std::ptr::null(), &mut res2) },
|
||||
XENORA_OK
|
||||
);
|
||||
assert_eq!((res & 0xFFFF_FFFF), (res2 & 0xFFFF_FFFF)); // same slot index
|
||||
assert_ne!(res >> 32, res2 >> 32); // higher generation
|
||||
|
||||
assert_eq!(xenora_session_destroy_resource(sess, res2), XENORA_OK);
|
||||
assert_eq!(xenora_session_destroy(sess), XENORA_OK);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_stale_and_double_destroyed_resource_handles_are_rejected() {
|
||||
let _guard = SERIAL.lock().unwrap();
|
||||
let sess = session();
|
||||
|
||||
// Zero handle
|
||||
assert_eq!(
|
||||
xenora_session_destroy_resource(sess, XENORA_NO_RESOURCE),
|
||||
XENORA_INVALID_HANDLE
|
||||
);
|
||||
|
||||
// Unallocated slot index
|
||||
let unallocated_handle = (1u64 << 32) | 999u64;
|
||||
assert_eq!(
|
||||
xenora_session_destroy_resource(sess, unallocated_handle),
|
||||
XENORA_INVALID_HANDLE
|
||||
);
|
||||
|
||||
// Create and destroy a valid resource
|
||||
let mut res = 0u64;
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_create_texture(sess, 2, 2, std::ptr::null(), &mut res) },
|
||||
XENORA_OK
|
||||
);
|
||||
assert_eq!(xenora_session_destroy_resource(sess, res), XENORA_OK);
|
||||
|
||||
// Double destroy
|
||||
assert_eq!(
|
||||
xenora_session_destroy_resource(sess, res),
|
||||
XENORA_INVALID_HANDLE
|
||||
);
|
||||
|
||||
// Stale handle queries
|
||||
let (mut r_type, mut r_w, mut r_h, mut r_flight) = (0u32, 0u32, 0u32, 0u32);
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
xenora_session_resource_info(sess, res, &mut r_type, &mut r_w, &mut r_h, &mut r_flight)
|
||||
},
|
||||
XENORA_INVALID_HANDLE
|
||||
);
|
||||
|
||||
let pixel = [0u8; 4];
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_update_texture(sess, res, 0, 0, 1, 1, pixel.as_ptr(), 4) },
|
||||
XENORA_INVALID_HANDLE
|
||||
);
|
||||
|
||||
let mut out_rgba = [0u8; 16];
|
||||
let (mut w, mut h) = (0u32, 0u32);
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
xenora_session_render_textured(sess, res, out_rgba.as_mut_ptr(), 16, &mut w, &mut h)
|
||||
},
|
||||
XENORA_INVALID_HANDLE
|
||||
);
|
||||
|
||||
assert_eq!(xenora_session_destroy(sess), XENORA_OK);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_resource_allocations_and_retirements_do_not_leak_slots() {
|
||||
let _guard = SERIAL.lock().unwrap();
|
||||
let sess = session();
|
||||
|
||||
let initial = [
|
||||
255u8, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255,
|
||||
];
|
||||
let update = [255u8, 255, 0, 255];
|
||||
|
||||
// Run 200 cycles of create -> update -> render -> destroy
|
||||
for i in 0..200 {
|
||||
let mut res = 0u64;
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_create_texture(sess, 2, 2, initial.as_ptr(), &mut res) },
|
||||
XENORA_OK,
|
||||
"create failed at cycle {}",
|
||||
i
|
||||
);
|
||||
|
||||
// Verify slot index is reused (res_idx is 0)
|
||||
let slot_idx = (res & 0xFFFF_FFFF) as usize;
|
||||
assert_eq!(slot_idx, 0, "slot index leaked at cycle {}", i);
|
||||
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_update_texture(sess, res, 0, 0, 1, 1, update.as_ptr(), 4) },
|
||||
XENORA_OK
|
||||
);
|
||||
|
||||
let mut out = [0u8; 16];
|
||||
let (mut w, mut h) = (0u32, 0u32);
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
xenora_session_render_textured(sess, res, out.as_mut_ptr(), 16, &mut w, &mut h)
|
||||
},
|
||||
XENORA_OK
|
||||
);
|
||||
|
||||
assert_eq!(xenora_session_destroy_resource(sess, res), XENORA_OK);
|
||||
}
|
||||
|
||||
assert_eq!(xenora_session_destroy(sess), XENORA_OK);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn textured_pe_fixture_executes_dynamic_updates_and_retirement() {
|
||||
let _guard = SERIAL.lock().unwrap();
|
||||
let sess = session();
|
||||
|
||||
let mut out_rgba = [0u8; 16];
|
||||
let mut out_w = 0u32;
|
||||
let mut out_h = 0u32;
|
||||
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
xenora_session_run_textured_fixture(
|
||||
sess,
|
||||
out_rgba.as_mut_ptr(),
|
||||
16,
|
||||
&mut out_w,
|
||||
&mut out_h,
|
||||
)
|
||||
},
|
||||
XENORA_OK
|
||||
);
|
||||
|
||||
assert_eq!(out_w, 2);
|
||||
assert_eq!(out_h, 2);
|
||||
|
||||
let expected_final: [u8; 16] = [
|
||||
255, 255, 0, 255, // (0,0) yellow
|
||||
0, 255, 255, 255, // (1,0) cyan
|
||||
255, 0, 255, 255, // (0,1) magenta
|
||||
64, 64, 64, 255, // (1,1) dark grey
|
||||
];
|
||||
assert_eq!(
|
||||
out_rgba, expected_final,
|
||||
"guest textured fixture read-back frame mismatch"
|
||||
);
|
||||
|
||||
assert_eq!(xenora_session_destroy(sess), XENORA_OK);
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
[package]
|
||||
name = "xenora-import-gen"
|
||||
description = "Deterministic Win32/CRT import binding generator for Xenora"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
# No external dependencies: pure-Rust code generation, no LLM, no network.
|
||||
@@ -1,125 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! API-Set Redirection and Alias Resolution.
|
||||
//!
|
||||
//! Windows uses virtual DLL names (e.g. `api-ms-win-core-processthreads-l1-1-0.dll`)
|
||||
//! that are redirected to canonical underlying modules (e.g. `kernel32.dll`, `KernelBase.dll`).
|
||||
//!
|
||||
//! This module resolves these virtual API-sets to canonical modules and vice-versa,
|
||||
//! preventing duplicate stub generation and allowing unified handler lookup.
|
||||
//! Source: Public Windows SDK `apisetcounters.h` and documented Microsoft API-set schema.
|
||||
|
||||
/// Resolve an API-set virtual DLL name to its canonical Windows module name.
|
||||
///
|
||||
/// API sets are matched exactly against [`get_api_sets_for_canonical`]. A name
|
||||
/// that merely starts like a known family is not assumed to forward anywhere.
|
||||
pub fn resolve_api_set_canonical(module: &str) -> &'static str {
|
||||
let lower = module.to_ascii_lowercase();
|
||||
for canonical in ["kernel32.dll", "ucrtbase.dll"] {
|
||||
if get_api_sets_for_canonical(canonical).contains(&lower.as_str()) {
|
||||
return canonical;
|
||||
}
|
||||
}
|
||||
match lower.as_str() {
|
||||
"kernel32.dll" | "kernelbase.dll" => "kernel32.dll",
|
||||
"ucrtbase.dll" => "ucrtbase.dll",
|
||||
"ntdll.dll" => "ntdll.dll",
|
||||
"ws2_32.dll" => "ws2_32.dll",
|
||||
"advapi32.dll" => "advapi32.dll",
|
||||
"vcruntime140.dll" | "vcruntime140_1.dll" => "vcruntime140.dll",
|
||||
"msvcp140.dll" | "msvcp140_1.dll" | "msvcp140_2.dll" => "msvcp140.dll",
|
||||
_ => "unknown.dll",
|
||||
}
|
||||
}
|
||||
|
||||
/// Known API sets that forward to the given canonical host module.
|
||||
pub fn get_api_sets_for_canonical(canonical: &str) -> &'static [&'static str] {
|
||||
match canonical {
|
||||
"kernel32.dll" => &[
|
||||
"api-ms-win-core-processthreads-l1-1-0.dll",
|
||||
"api-ms-win-core-processthreads-l1-1-1.dll",
|
||||
"api-ms-win-core-processthreads-l1-1-2.dll",
|
||||
"api-ms-win-core-synch-l1-1-0.dll",
|
||||
"api-ms-win-core-synch-l1-2-0.dll",
|
||||
"api-ms-win-core-synch-l1-2-1.dll",
|
||||
"api-ms-win-core-sysinfo-l1-1-0.dll",
|
||||
"api-ms-win-core-sysinfo-l1-2-0.dll",
|
||||
"api-ms-win-core-profile-l1-1-0.dll",
|
||||
"api-ms-win-core-libraryloader-l1-2-0.dll",
|
||||
"api-ms-win-core-libraryloader-l1-2-1.dll",
|
||||
"api-ms-win-core-file-l1-1-0.dll",
|
||||
"api-ms-win-core-file-l2-1-0.dll",
|
||||
"api-ms-win-core-errorhandling-l1-1-0.dll",
|
||||
"api-ms-win-core-debug-l1-1-0.dll",
|
||||
"api-ms-win-core-handle-l1-1-0.dll",
|
||||
"api-ms-win-core-interlocked-l1-1-0.dll",
|
||||
"api-ms-win-core-fibers-l1-1-0.dll",
|
||||
"api-ms-win-core-datetime-l1-1-1.dll",
|
||||
"api-ms-win-core-timezone-l1-1-0.dll",
|
||||
"api-ms-win-core-realtime-l1-1-0.dll",
|
||||
"api-ms-win-core-memory-l1-1-0.dll",
|
||||
],
|
||||
"ucrtbase.dll" => &[
|
||||
"api-ms-win-crt-math-l1-1-0.dll",
|
||||
"api-ms-win-crt-string-l1-1-0.dll",
|
||||
"api-ms-win-crt-stdio-l1-1-0.dll",
|
||||
"api-ms-win-crt-runtime-l1-1-0.dll",
|
||||
"api-ms-win-crt-heap-l1-1-0.dll",
|
||||
"api-ms-win-crt-time-l1-1-0.dll",
|
||||
"api-ms-win-crt-convert-l1-1-0.dll",
|
||||
"api-ms-win-crt-utility-l1-1-0.dll",
|
||||
"api-ms-win-crt-filesystem-l1-1-0.dll",
|
||||
"api-ms-win-crt-locale-l1-1-0.dll",
|
||||
"api-ms-win-crt-environment-l1-1-0.dll",
|
||||
// The API set a program built with the mingw-w64 UCRT runtime
|
||||
// imports `memcpy` and `__C_specific_handler` from. That it
|
||||
// forwards to ucrtbase.dll is inferred from its name and from
|
||||
// Microsoft's "Universal CRT deployment" page, which says the
|
||||
// Universal CRT ships as ucrtbase.dll plus `api-ms-win-*.dll`
|
||||
// forwarders. No document naming this set was found.
|
||||
"api-ms-win-crt-private-l1-1-0.dll",
|
||||
],
|
||||
_ => &[],
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn only_listed_api_sets_resolve() {
|
||||
for unknown in [
|
||||
"api-ms-win-core-file-l9-9-9.dll",
|
||||
"api-ms-win-core-processthreads",
|
||||
"api-ms-win-core-filesomething.dll",
|
||||
"api-ms-win-crt-unknown-l1-1-0.dll",
|
||||
] {
|
||||
assert_eq!(
|
||||
resolve_api_set_canonical(unknown),
|
||||
"unknown.dll",
|
||||
"{unknown}"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
resolve_api_set_canonical("API-MS-Win-Core-Memory-L1-1-0.DLL"),
|
||||
"kernel32.dll"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_api_set_resolution() {
|
||||
assert_eq!(
|
||||
resolve_api_set_canonical("api-ms-win-core-processthreads-l1-1-0.dll"),
|
||||
"kernel32.dll"
|
||||
);
|
||||
assert_eq!(
|
||||
resolve_api_set_canonical("api-ms-win-crt-math-l1-1-0.dll"),
|
||||
"ucrtbase.dll"
|
||||
);
|
||||
assert_eq!(
|
||||
resolve_api_set_canonical("api-ms-win-core-synch-l1-2-1.dll"),
|
||||
"kernel32.dll"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Generate the typed runtime adapters and report. Run from the repository root.
|
||||
//! `--check` regenerates in memory and fails if a committed file differs.
|
||||
|
||||
use std::process::ExitCode;
|
||||
use xenora_import_gen::typed::{generate_report, generate_rust, parse};
|
||||
|
||||
const REGISTRY: &str = "crates/loader/runtime/services.txt";
|
||||
const TESTS: &str = "crates/loader/tests/runtime_services.rs";
|
||||
const RUST: &str = "crates/loader/src/runtime_table.rs";
|
||||
const REPORT: &str = "docs/runtime/services.md";
|
||||
|
||||
fn run() -> Result<String, String> {
|
||||
let mode = std::env::args().nth(1).unwrap_or_default();
|
||||
let read = |path: &str| std::fs::read_to_string(path).map_err(|e| format!("{path}: {e}"));
|
||||
let services =
|
||||
parse(&read(REGISTRY)?, &read(TESTS)?).map_err(|e| format!("{REGISTRY}: {e}"))?;
|
||||
let outputs = [
|
||||
(RUST, generate_rust(&services)),
|
||||
(REPORT, generate_report(&services)),
|
||||
];
|
||||
for (path, text) in &outputs {
|
||||
match mode.as_str() {
|
||||
"generate" => std::fs::write(path, text).map_err(|e| format!("{path}: {e}"))?,
|
||||
"--check" if read(path)? != *text => {
|
||||
return Err(format!(
|
||||
"{path} is out of date; run xenora-runtime-gen generate"
|
||||
));
|
||||
}
|
||||
"--check" | "validate" => {}
|
||||
_ => return Err("usage: xenora-runtime-gen validate|generate|--check".into()),
|
||||
}
|
||||
}
|
||||
Ok(format!("{} services", services.len()))
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
match run() {
|
||||
Ok(message) => {
|
||||
println!("{message}");
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(message) => {
|
||||
eprintln!("{message}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,399 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Rust source code generator.
|
||||
//!
|
||||
//! Produces three files:
|
||||
//! - `generated_crt.rs` — `register_generated_crt_services(registry)`
|
||||
//! - `generated_stubs.rs` — `register_generated_stubs(registry)`
|
||||
//! - `generated_tests.rs` — `#[cfg(test)] mod generated_tests { ... }`
|
||||
//!
|
||||
//! All generated code uses only the existing `ImportRegistry` / `ServiceHandler` types.
|
||||
//! No unsafe code is emitted in the registration layer; `extern "C"` libc calls are
|
||||
//! wrapped in `unsafe` blocks with explicit guest-memory bounds checks.
|
||||
|
||||
use crate::classify::Classification;
|
||||
use crate::classify::SymbolDb;
|
||||
use crate::manifest::Manifest;
|
||||
|
||||
/// The three output files plus the Markdown manifest summary.
|
||||
pub struct GeneratedFiles {
|
||||
pub crt_rs: String,
|
||||
pub stubs_rs: String,
|
||||
pub tests_rs: String,
|
||||
pub manifest_md: String,
|
||||
}
|
||||
|
||||
impl GeneratedFiles {
|
||||
/// Write all files into `out_dir`, creating it if needed.
|
||||
pub fn write_all(&self, out_dir: &str) -> Result<(), String> {
|
||||
std::fs::create_dir_all(out_dir).map_err(|e| format!("create dir {out_dir}: {e}"))?;
|
||||
write_file(out_dir, "generated_crt.rs", &self.crt_rs)?;
|
||||
write_file(out_dir, "generated_stubs.rs", &self.stubs_rs)?;
|
||||
write_file(out_dir, "generated_tests.rs", &self.tests_rs)?;
|
||||
write_file(out_dir, "generated_manifest.md", &self.manifest_md)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn write_file(dir: &str, name: &str, content: &str) -> Result<(), String> {
|
||||
let path = format!("{dir}/{name}");
|
||||
std::fs::write(&path, content).map_err(|e| format!("write {path}: {e}"))
|
||||
}
|
||||
|
||||
fn unique_entries(manifest: &Manifest) -> impl Iterator<Item = &crate::manifest::ManifestEntry> {
|
||||
let mut seen = std::collections::BTreeSet::new();
|
||||
manifest
|
||||
.entries
|
||||
.iter()
|
||||
.filter(move |entry| seen.insert(entry.key()))
|
||||
}
|
||||
|
||||
/// Generate all files from the manifest.
|
||||
pub fn generate(manifest: &Manifest, _db: &SymbolDb) -> GeneratedFiles {
|
||||
let crt_rs = gen_crt(manifest);
|
||||
let stubs_rs = gen_stubs(manifest);
|
||||
let tests_rs = gen_tests(manifest);
|
||||
let manifest_md = manifest.render_markdown();
|
||||
GeneratedFiles {
|
||||
crt_rs,
|
||||
stubs_rs,
|
||||
tests_rs,
|
||||
manifest_md,
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// CRT native bindings
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
fn gen_crt(manifest: &Manifest) -> String {
|
||||
let mut out = file_header("generated_crt.rs");
|
||||
out.push_str(
|
||||
r#"
|
||||
//! Auto-generated CRT service registrations.
|
||||
//! Maps Windows CRT API-set names to native macOS libc equivalents.
|
||||
//! All mappings are derived from public ISO C / POSIX documentation.
|
||||
//! Do not edit manually — regenerate with `xenora imports generate`.
|
||||
|
||||
use crate::cpu::{CpuState, ExitReason, Register};
|
||||
use crate::imports::{ImportRegistry, ServiceStatus, Win64Args};
|
||||
use crate::memory::GuestMemory;
|
||||
|
||||
/// Register all automatically generated CRT bindings into `registry`.
|
||||
///
|
||||
/// These implementations are STUB-VERIFIED, not independently confirmed against
|
||||
/// a live Xbox runtime. They must pass the conformance tests in
|
||||
/// `generated_tests.rs` before being marked `ServiceStatus::Implemented`.
|
||||
#[allow(unused_variables)]
|
||||
pub fn register_generated_crt_services(registry: &mut ImportRegistry) {
|
||||
"#,
|
||||
);
|
||||
|
||||
for entry in unique_entries(manifest) {
|
||||
match &entry.classification {
|
||||
Classification::CrtNative { libc_sym, note } => {
|
||||
out.push_str(&gen_crt_native_registration(
|
||||
&entry.module,
|
||||
&entry.symbol,
|
||||
libc_sym,
|
||||
note,
|
||||
));
|
||||
}
|
||||
Classification::CrtWrapper {
|
||||
libc_sym,
|
||||
wrapper_note,
|
||||
} => {
|
||||
out.push_str(&gen_crt_wrapper_registration(
|
||||
&entry.module,
|
||||
&entry.symbol,
|
||||
libc_sym,
|
||||
wrapper_note,
|
||||
));
|
||||
}
|
||||
Classification::RuntimeHelper { note } => {
|
||||
out.push_str(&gen_runtime_helper_registration(
|
||||
&entry.module,
|
||||
&entry.symbol,
|
||||
note,
|
||||
));
|
||||
}
|
||||
_ => {} // Win32Stub and Manual go to stubs_rs
|
||||
}
|
||||
}
|
||||
|
||||
out.push_str("}\n");
|
||||
out
|
||||
}
|
||||
|
||||
/// Generate a registration block for a CrtNative symbol.
|
||||
/// These use a simple `Win64Args` → libc dispatch pattern.
|
||||
fn gen_crt_native_registration(module: &str, symbol: &str, _libc_sym: &str, note: &str) -> String {
|
||||
// Determine the calling pattern based on symbol name
|
||||
let (status, dispatch) = match crt_dispatch_expr(symbol) {
|
||||
Some(dispatch) => ("Partial", dispatch),
|
||||
None => (
|
||||
"Stub",
|
||||
"Err(ExitReason::IllegalInstruction(0xFE))".to_owned(),
|
||||
),
|
||||
};
|
||||
|
||||
format!(
|
||||
r#"
|
||||
// {note}
|
||||
// Source: ISO C / POSIX public specification.
|
||||
registry.register_with_status(
|
||||
"{module}", "{symbol}",
|
||||
ServiceStatus::{status},
|
||||
|args: &Win64Args, _cpu: &mut CpuState, mem: &mut GuestMemory| -> Result<u64, ExitReason> {{
|
||||
{dispatch}
|
||||
}},
|
||||
);
|
||||
"#,
|
||||
module = module,
|
||||
symbol = symbol,
|
||||
note = note,
|
||||
dispatch = dispatch,
|
||||
)
|
||||
}
|
||||
|
||||
/// Generate a stub-wrapper registration for a CrtWrapper symbol (e.g. strcat_s → strcat).
|
||||
fn gen_crt_wrapper_registration(module: &str, symbol: &str, _libc_sym: &str, note: &str) -> String {
|
||||
format!(
|
||||
r#"
|
||||
// {note}
|
||||
registry.register_with_status(
|
||||
"{module}", "{symbol}",
|
||||
ServiceStatus::Stub,
|
||||
|args: &Win64Args, _cpu: &mut CpuState, mem: &mut GuestMemory| -> Result<u64, ExitReason> {{
|
||||
Err(ExitReason::IllegalInstruction(0xFE))
|
||||
}},
|
||||
);
|
||||
"#,
|
||||
)
|
||||
}
|
||||
|
||||
/// Generate a registration for a runtime helper (EH frame handlers, etc.).
|
||||
fn gen_runtime_helper_registration(module: &str, symbol: &str, note: &str) -> String {
|
||||
// Not implemented: fails explicitly instead of reporting success.
|
||||
let body = "Err(ExitReason::IllegalInstruction(0xFE)) // 0xFE = Unsupported Host Service Call";
|
||||
format!(
|
||||
r#"
|
||||
// {note}
|
||||
registry.register_with_status(
|
||||
"{module}", "{symbol}",
|
||||
ServiceStatus::Stub,
|
||||
|args: &Win64Args, _cpu: &mut CpuState, mem: &mut GuestMemory| -> Result<u64, ExitReason> {{
|
||||
{body}
|
||||
}},
|
||||
);
|
||||
"#,
|
||||
)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Win32 stubs
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
fn gen_stubs(manifest: &Manifest) -> String {
|
||||
let mut out = file_header("generated_stubs.rs");
|
||||
out.push_str(
|
||||
r#"
|
||||
//! Auto-generated Win32 service stubs.
|
||||
//! Each stub stops the guest with an explicit unsupported-service exit.
|
||||
//! Do not edit manually — regenerate with `xenora imports generate`.
|
||||
|
||||
use crate::cpu::{CpuState, ExitReason};
|
||||
use crate::imports::{ImportRegistry, ServiceStatus, Win64Args};
|
||||
use crate::memory::GuestMemory;
|
||||
|
||||
/// Register all automatically generated Win32 stubs into `registry`.
|
||||
#[allow(unused_variables)]
|
||||
pub fn register_generated_stubs(registry: &mut ImportRegistry) {
|
||||
"#,
|
||||
);
|
||||
|
||||
for entry in unique_entries(manifest) {
|
||||
if let Classification::Win32Stub { note, .. } = &entry.classification {
|
||||
out.push_str(&format!(
|
||||
r#"
|
||||
// {note}
|
||||
// STUB: Fails explicitly with unsupported status instead of fabricating success.
|
||||
registry.register_with_status(
|
||||
"{module}", "{symbol}",
|
||||
ServiceStatus::Stub,
|
||||
|_args: &Win64Args, _cpu: &mut CpuState, _mem: &mut GuestMemory| -> Result<u64, ExitReason> {{
|
||||
Err(ExitReason::IllegalInstruction(0xFE)) // 0xFE = Unsupported Host Service Call
|
||||
}},
|
||||
);
|
||||
"#,
|
||||
module = entry.module,
|
||||
symbol = entry.symbol,
|
||||
note = note,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
out.push_str("}\n");
|
||||
out
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Conformance tests
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
fn gen_tests(manifest: &Manifest) -> String {
|
||||
let mut out = file_header("generated_tests.rs");
|
||||
out.push_str(
|
||||
r#"
|
||||
//! Conformance tests for emitted service registrations.
|
||||
//! Place this file and the two generated registration files together as
|
||||
//! an integration test in a Cargo package that depends on xenora-loader.
|
||||
|
||||
pub use xenora_loader::{cpu, imports, memory};
|
||||
|
||||
#[path = "generated_crt.rs"]
|
||||
mod generated_crt;
|
||||
#[path = "generated_stubs.rs"]
|
||||
mod generated_stubs;
|
||||
|
||||
use cpu::{CpuState, ExitReason};
|
||||
use imports::{ImportRegistry, ServiceStatus, Win64Args};
|
||||
use memory::GuestMemory;
|
||||
|
||||
fn check(module: &str, symbol: &str, input: u64, status: ServiceStatus, expected: Result<u64, ExitReason>) {
|
||||
let mut registry = ImportRegistry::new();
|
||||
generated_crt::register_generated_crt_services(&mut registry);
|
||||
generated_stubs::register_generated_stubs(&mut registry);
|
||||
let service = registry.binding(module, symbol).expect("generated binding");
|
||||
assert_eq!(service.status, status);
|
||||
let args = Win64Args { rcx: input, rdx: 0, r8: 0, r9: 0, rsp: 0x8000 };
|
||||
let mut cpu = CpuState::new(0x1000, 0x8000);
|
||||
let mut memory = GuestMemory::new();
|
||||
assert_eq!((service.handler)(&args, &mut cpu, &mut memory), expected);
|
||||
}
|
||||
"#,
|
||||
);
|
||||
|
||||
for (index, entry) in unique_entries(manifest).enumerate() {
|
||||
let (input, status, expected) = match &entry.classification {
|
||||
Classification::CrtNative { .. } if crt_dispatch_expr(&entry.symbol).is_some() => {
|
||||
let Some((input, expected)) = canonical_integer_case(&entry.symbol) else {
|
||||
continue;
|
||||
};
|
||||
(input, "Partial", format!("Ok({expected})"))
|
||||
}
|
||||
Classification::CrtNative { .. }
|
||||
| Classification::CrtWrapper { .. }
|
||||
| Classification::RuntimeHelper { .. }
|
||||
| Classification::Win32Stub { .. } => (
|
||||
0,
|
||||
"Stub",
|
||||
"Err(ExitReason::IllegalInstruction(0xFE))".to_owned(),
|
||||
),
|
||||
_ => continue,
|
||||
};
|
||||
out.push_str(&format!(
|
||||
r#"
|
||||
#[test]
|
||||
fn generated_test_{name}_{index}() {{
|
||||
check({module:?}, {symbol:?}, {input}, ServiceStatus::{status}, {expected});
|
||||
}}
|
||||
"#,
|
||||
name = symbol_to_ident_lower(&entry.symbol),
|
||||
module = entry.module,
|
||||
symbol = entry.symbol,
|
||||
));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
fn file_header(filename: &str) -> String {
|
||||
format!(
|
||||
"// SPDX-License-Identifier: GPL-3.0-or-later\n\
|
||||
// AUTO-GENERATED by xenora-import-gen — DO NOT EDIT MANUALLY.\n\
|
||||
// Source: public Win32/CRT documentation and ISO C standard.\n\
|
||||
// Regenerate: `xenora imports generate --pe <executable>`\n\
|
||||
// File: {filename}\n\n"
|
||||
)
|
||||
}
|
||||
|
||||
/// Convert a C symbol name to a valid Rust identifier (snake_case, no special chars).
|
||||
fn symbol_to_ident(sym: &str) -> String {
|
||||
sym.chars()
|
||||
.map(|c| {
|
||||
if c.is_alphanumeric() || c == '_' {
|
||||
c
|
||||
} else {
|
||||
'_'
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn symbol_to_ident_lower(sym: &str) -> String {
|
||||
symbol_to_ident(sym).to_ascii_lowercase()
|
||||
}
|
||||
|
||||
/// Returns a dispatch body for CRT calls with a compatible guest ABI adapter.
|
||||
pub(crate) fn crt_dispatch_expr(symbol: &str) -> Option<String> {
|
||||
Some(match symbol {
|
||||
// abs(int) -> int
|
||||
"abs" | "labs" => r#"let x = args.rcx as i32;
|
||||
Ok(x.abs() as u64)"#
|
||||
.to_string(),
|
||||
"llabs" => r#"let x = args.rcx as i64;
|
||||
Ok(x.unsigned_abs())"#
|
||||
.to_string(),
|
||||
// ISO C classification functions: char in RCX
|
||||
"isalnum" | "isalpha" | "isdigit" | "islower" | "isupper" | "isspace" | "isprint"
|
||||
| "iscntrl" | "ispunct" | "isxdigit" => {
|
||||
let test = match symbol {
|
||||
"isalnum" => "(c.is_ascii_alphanumeric())",
|
||||
"isalpha" => "(c.is_ascii_alphabetic())",
|
||||
"isdigit" => "(c.is_ascii_digit())",
|
||||
"islower" => "(c.is_ascii_lowercase())",
|
||||
"isupper" => "(c.is_ascii_uppercase())",
|
||||
"isspace" => "(c.is_ascii_whitespace())",
|
||||
"isprint" => "(!c.is_ascii_control())",
|
||||
"iscntrl" => "(c.is_ascii_control())",
|
||||
"ispunct" => "(c.is_ascii_punctuation())",
|
||||
"isxdigit" => "(c.is_ascii_hexdigit())",
|
||||
_ => "(false)",
|
||||
};
|
||||
format!(
|
||||
r#"let c = (args.rcx & 0xFF) as u8 as char;
|
||||
Ok(if {test} {{ 1 }} else {{ 0 }})"#,
|
||||
test = test,
|
||||
)
|
||||
}
|
||||
"tolower" => r#"let c = (args.rcx & 0xFF) as u8;
|
||||
Ok(c.to_ascii_lowercase() as u64)"#
|
||||
.to_string(),
|
||||
"toupper" => r#"let c = (args.rcx & 0xFF) as u8;
|
||||
Ok(c.to_ascii_uppercase() as u64)"#
|
||||
.to_string(),
|
||||
// Floating-point CRT calls also land here until XMM state is available.
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Independent canonical inputs and expected integer return bits.
|
||||
fn canonical_integer_case(symbol: &str) -> Option<(u64, u64)> {
|
||||
Some(match symbol {
|
||||
"abs" | "labs" | "llabs" => ((-42i64) as u64, 42),
|
||||
"tolower" => (65, 97),
|
||||
"toupper" => (122, 90),
|
||||
"isalnum" | "isalpha" | "isupper" | "isxdigit" => (65, 1),
|
||||
"isdigit" => (53, 1),
|
||||
"islower" => (122, 1),
|
||||
"isspace" => (32, 1),
|
||||
"isprint" => (65, 1),
|
||||
"iscntrl" => (127, 1),
|
||||
"ispunct" => (33, 1),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -1,529 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Decoding of Microsoft Visual C++ decorated names, for diagnostics.
|
||||
//!
|
||||
//! Written from the publicly described decoration scheme: a leading `?`,
|
||||
//! `@`-terminated name fragments listed innermost first, single-digit name and
|
||||
//! type back-references, an access and storage code, a calling convention,
|
||||
//! the return type and the parameter list. Output follows the style of
|
||||
//! Microsoft's `undname` tool. Anything outside the supported subset returns
|
||||
//! `None` instead of a guess, so callers fall back to the decorated name.
|
||||
|
||||
const MAX_DEPTH: usize = 16;
|
||||
|
||||
/// The undecorated form of `symbol`, or `None` when it is not a decorated
|
||||
/// C++ name or uses an unsupported construct.
|
||||
pub fn demangle(symbol: &str) -> Option<String> {
|
||||
let mut parser = Parser {
|
||||
input: symbol.as_bytes(),
|
||||
position: 0,
|
||||
names: Vec::new(),
|
||||
types: Vec::new(),
|
||||
depth: 0,
|
||||
};
|
||||
let result = parser.symbol()?;
|
||||
(parser.position == parser.input.len()).then_some(result)
|
||||
}
|
||||
|
||||
/// A special name introduced by `?` and a code inside the qualified name.
|
||||
enum Special {
|
||||
Constructor,
|
||||
Destructor,
|
||||
Operator(&'static str),
|
||||
Vftable,
|
||||
}
|
||||
|
||||
struct Parser<'a> {
|
||||
input: &'a [u8],
|
||||
position: usize,
|
||||
names: Vec<String>,
|
||||
types: Vec<String>,
|
||||
depth: usize,
|
||||
}
|
||||
|
||||
impl Parser<'_> {
|
||||
fn peek(&self) -> Option<u8> {
|
||||
self.input.get(self.position).copied()
|
||||
}
|
||||
|
||||
fn next(&mut self) -> Option<u8> {
|
||||
let byte = self.peek()?;
|
||||
self.position += 1;
|
||||
Some(byte)
|
||||
}
|
||||
|
||||
fn eat(&mut self, byte: u8) -> bool {
|
||||
let found = self.peek() == Some(byte);
|
||||
if found {
|
||||
self.position += 1;
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
fn eat_str(&mut self, text: &str) -> bool {
|
||||
let found = self.input[self.position..].starts_with(text.as_bytes());
|
||||
if found {
|
||||
self.position += text.len();
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
fn symbol(&mut self) -> Option<String> {
|
||||
if !self.eat(b'?') {
|
||||
return None;
|
||||
}
|
||||
let (name, special) = self.qualified_name(true)?;
|
||||
match self.peek()? {
|
||||
b'0'..=b'4' => self.variable(&name),
|
||||
b'6' => {
|
||||
self.next();
|
||||
let qualifier = cv(self.next()?)?;
|
||||
self.eat(b'@');
|
||||
if !matches!(special, Some(Special::Vftable)) {
|
||||
return None;
|
||||
}
|
||||
Some(format!("{} {name}", qualifier.trim()))
|
||||
}
|
||||
_ => self.function(&name, special.as_ref()),
|
||||
}
|
||||
}
|
||||
|
||||
fn variable(&mut self, name: &str) -> Option<String> {
|
||||
let access = match self.next()? {
|
||||
b'0' => "private: static ",
|
||||
b'1' => "protected: static ",
|
||||
b'2' => "public: static ",
|
||||
_ => "",
|
||||
};
|
||||
let kind = self.data_type()?;
|
||||
self.eat(b'E');
|
||||
let qualifier = cv(self.next()?)?;
|
||||
Some(format!("{access}{kind}{qualifier} {name}"))
|
||||
}
|
||||
|
||||
fn function(&mut self, name: &str, special: Option<&Special>) -> Option<String> {
|
||||
let (access, member) = match self.next()? {
|
||||
b'A' | b'B' => ("private: ", true),
|
||||
b'C' | b'D' => ("private: static ", false),
|
||||
b'E' | b'F' => ("private: virtual ", true),
|
||||
b'I' | b'J' => ("protected: ", true),
|
||||
b'K' | b'L' => ("protected: static ", false),
|
||||
b'M' | b'N' => ("protected: virtual ", true),
|
||||
b'Q' | b'R' => ("public: ", true),
|
||||
b'S' | b'T' => ("public: static ", false),
|
||||
b'U' | b'V' => ("public: virtual ", true),
|
||||
b'Y' | b'Z' => ("", false),
|
||||
_ => return None,
|
||||
};
|
||||
let mut this = String::new();
|
||||
if member {
|
||||
let pointer64 = self.eat(b'E');
|
||||
this.push_str(cv(self.next()?)?.trim_start());
|
||||
if pointer64 {
|
||||
this.push_str(" __ptr64");
|
||||
}
|
||||
}
|
||||
let convention = match self.next()? {
|
||||
b'A' | b'B' => "__cdecl",
|
||||
b'C' | b'D' => "__pascal",
|
||||
b'E' | b'F' => "__thiscall",
|
||||
b'G' | b'H' => "__stdcall",
|
||||
b'I' | b'J' => "__fastcall",
|
||||
b'Q' => "__vectorcall",
|
||||
_ => return None,
|
||||
};
|
||||
let returns = if self.eat(b'@') {
|
||||
if !matches!(special, Some(Special::Constructor | Special::Destructor)) {
|
||||
return None;
|
||||
}
|
||||
String::new()
|
||||
} else {
|
||||
if self.eat(b'?') {
|
||||
cv(self.next()?)?;
|
||||
}
|
||||
format!("{} ", self.data_type()?)
|
||||
};
|
||||
let parameters = self.parameters()?;
|
||||
if !self.eat(b'Z') {
|
||||
return None;
|
||||
}
|
||||
Some(format!(
|
||||
"{access}{returns}{convention} {name}({parameters}){this}"
|
||||
))
|
||||
}
|
||||
|
||||
fn parameters(&mut self) -> Option<String> {
|
||||
if self.eat(b'X') {
|
||||
return Some("void".to_owned());
|
||||
}
|
||||
let mut parameters = Vec::new();
|
||||
loop {
|
||||
match self.peek()? {
|
||||
b'@' => {
|
||||
self.next();
|
||||
break;
|
||||
}
|
||||
b'Z' => {
|
||||
self.next();
|
||||
parameters.push("...".to_owned());
|
||||
break;
|
||||
}
|
||||
_ => {
|
||||
let start = self.position;
|
||||
let kind = self.data_type()?;
|
||||
if self.position - start > 1 && self.types.len() < 10 {
|
||||
self.types.push(kind.clone());
|
||||
}
|
||||
parameters.push(kind);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(parameters.join(","))
|
||||
}
|
||||
|
||||
/// Fragments up to `@`, joined outermost first.
|
||||
fn qualified_name(&mut self, allow_special: bool) -> Option<(String, Option<Special>)> {
|
||||
let mut special = None;
|
||||
let mut fragments = Vec::new();
|
||||
if allow_special
|
||||
&& self.peek() == Some(b'?')
|
||||
&& self.input.get(self.position + 1) != Some(&b'$')
|
||||
{
|
||||
self.next();
|
||||
special = Some(self.special()?);
|
||||
} else {
|
||||
fragments.push(self.fragment()?);
|
||||
}
|
||||
while !self.eat(b'@') {
|
||||
fragments.push(self.fragment()?);
|
||||
}
|
||||
fragments.reverse();
|
||||
let scope = fragments.join("::");
|
||||
let name = match &special {
|
||||
None => scope,
|
||||
Some(special) => {
|
||||
let class = || Some(fragments.last()?.split('<').next()?.to_owned());
|
||||
let leaf = match special {
|
||||
Special::Constructor => class()?,
|
||||
Special::Destructor => format!("~{}", class()?),
|
||||
Special::Operator(name) => name.to_string(),
|
||||
Special::Vftable => "`vftable'".to_owned(),
|
||||
};
|
||||
if scope.is_empty() {
|
||||
leaf
|
||||
} else {
|
||||
format!("{scope}::{leaf}")
|
||||
}
|
||||
}
|
||||
};
|
||||
Some((name, special))
|
||||
}
|
||||
|
||||
fn special(&mut self) -> Option<Special> {
|
||||
Some(match self.next()? {
|
||||
b'0' => Special::Constructor,
|
||||
b'1' => Special::Destructor,
|
||||
b'2' => Special::Operator("operator new"),
|
||||
b'3' => Special::Operator("operator delete"),
|
||||
b'4' => Special::Operator("operator="),
|
||||
b'8' => Special::Operator("operator=="),
|
||||
b'9' => Special::Operator("operator!="),
|
||||
b'A' => Special::Operator("operator[]"),
|
||||
b'R' => Special::Operator("operator()"),
|
||||
b'_' => match self.next()? {
|
||||
b'7' => Special::Vftable,
|
||||
b'U' => Special::Operator("operator new[]"),
|
||||
b'V' => Special::Operator("operator delete[]"),
|
||||
_ => return None,
|
||||
},
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
fn fragment(&mut self) -> Option<String> {
|
||||
if let Some(digit @ b'0'..=b'9') = self.peek() {
|
||||
self.next();
|
||||
return self.names.get(usize::from(digit - b'0')).cloned();
|
||||
}
|
||||
let fragment = if self.eat_str("?$") {
|
||||
self.template()?
|
||||
} else {
|
||||
self.identifier()?
|
||||
};
|
||||
if self.names.len() < 10 && !self.names.contains(&fragment) {
|
||||
self.names.push(fragment.clone());
|
||||
}
|
||||
Some(fragment)
|
||||
}
|
||||
|
||||
fn identifier(&mut self) -> Option<String> {
|
||||
let start = self.position;
|
||||
while self.peek()? != b'@' {
|
||||
let byte = self.next()?;
|
||||
if !(byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'$') {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let text = std::str::from_utf8(&self.input[start..self.position]).ok()?;
|
||||
self.next();
|
||||
(!text.is_empty()).then(|| text.to_owned())
|
||||
}
|
||||
|
||||
/// `name@arguments@`, with back-references local to the argument list.
|
||||
fn template(&mut self) -> Option<String> {
|
||||
self.depth += 1;
|
||||
if self.depth > MAX_DEPTH {
|
||||
return None;
|
||||
}
|
||||
let outer_names = std::mem::take(&mut self.names);
|
||||
let outer_types = std::mem::take(&mut self.types);
|
||||
let name = self.identifier();
|
||||
if let Some(name) = &name {
|
||||
self.names.push(name.clone());
|
||||
}
|
||||
let mut arguments = Vec::new();
|
||||
let result = (|| {
|
||||
let name = name?;
|
||||
while !self.eat(b'@') {
|
||||
let start = self.position;
|
||||
let argument = if self.eat(b'$') {
|
||||
if !self.eat(b'0') {
|
||||
return None;
|
||||
}
|
||||
self.number()?.to_string()
|
||||
} else {
|
||||
self.data_type()?
|
||||
};
|
||||
if self.position - start > 1 && self.types.len() < 10 {
|
||||
self.types.push(argument.clone());
|
||||
}
|
||||
arguments.push(argument);
|
||||
}
|
||||
let joined = arguments.join(",");
|
||||
let close = if joined.ends_with('>') { " >" } else { ">" };
|
||||
Some(format!("{name}<{joined}{close}"))
|
||||
})();
|
||||
self.names = outer_names;
|
||||
self.types = outer_types;
|
||||
self.depth -= 1;
|
||||
result
|
||||
}
|
||||
|
||||
/// `0`–`9` encode 1–10; otherwise hexadecimal digits `A`–`P` end with `@`.
|
||||
fn number(&mut self) -> Option<i64> {
|
||||
let negative = self.eat(b'?');
|
||||
let value = match self.next()? {
|
||||
digit @ b'0'..=b'9' => i64::from(digit - b'0') + 1,
|
||||
b'@' => 0,
|
||||
mut digit => {
|
||||
let mut value: i64 = 0;
|
||||
loop {
|
||||
if !(b'A'..=b'P').contains(&digit) {
|
||||
return None;
|
||||
}
|
||||
value = value
|
||||
.checked_mul(16)?
|
||||
.checked_add(i64::from(digit - b'A'))?;
|
||||
digit = self.next()?;
|
||||
if digit == b'@' {
|
||||
break value;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
Some(if negative { -value } else { value })
|
||||
}
|
||||
|
||||
fn data_type(&mut self) -> Option<String> {
|
||||
self.depth += 1;
|
||||
if self.depth > MAX_DEPTH {
|
||||
return None;
|
||||
}
|
||||
let result = self.data_type_inner();
|
||||
self.depth -= 1;
|
||||
result
|
||||
}
|
||||
|
||||
fn data_type_inner(&mut self) -> Option<String> {
|
||||
let code = self.next()?;
|
||||
let primitive = match code {
|
||||
b'X' => "void",
|
||||
b'C' => "signed char",
|
||||
b'D' => "char",
|
||||
b'E' => "unsigned char",
|
||||
b'F' => "short",
|
||||
b'G' => "unsigned short",
|
||||
b'H' => "int",
|
||||
b'I' => "unsigned int",
|
||||
b'J' => "long",
|
||||
b'K' => "unsigned long",
|
||||
b'M' => "float",
|
||||
b'N' => "double",
|
||||
b'O' => "long double",
|
||||
b'0'..=b'9' => return self.types.get(usize::from(code - b'0')).cloned(),
|
||||
b'_' => match self.next()? {
|
||||
b'J' => "__int64",
|
||||
b'K' => "unsigned __int64",
|
||||
b'N' => "bool",
|
||||
b'W' => "wchar_t",
|
||||
b'S' => "char16_t",
|
||||
b'U' => "char32_t",
|
||||
b'Q' => "char8_t",
|
||||
_ => return None,
|
||||
},
|
||||
b'V' => return Some(format!("class {}", self.qualified_name(false)?.0)),
|
||||
b'U' => return Some(format!("struct {}", self.qualified_name(false)?.0)),
|
||||
b'T' => return Some(format!("union {}", self.qualified_name(false)?.0)),
|
||||
b'W' => {
|
||||
if !self.eat(b'4') {
|
||||
return None;
|
||||
}
|
||||
return Some(format!("enum {}", self.qualified_name(false)?.0));
|
||||
}
|
||||
b'P' | b'Q' | b'R' | b'S' => return self.indirection("*", pointer_cv(code)),
|
||||
b'A' => return self.indirection("&", ""),
|
||||
b'B' => return self.indirection("&", " volatile"),
|
||||
b'$' => {
|
||||
if self.eat_str("$Q") {
|
||||
return self.indirection("&&", "");
|
||||
}
|
||||
if self.eat_str("$T") {
|
||||
return Some("std::nullptr_t".to_owned());
|
||||
}
|
||||
return None;
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
Some(primitive.to_owned())
|
||||
}
|
||||
|
||||
/// A pointer or reference: an optional `E` for `__ptr64`, the pointee's
|
||||
/// qualifiers, then the pointee.
|
||||
fn indirection(&mut self, symbol: &str, own: &str) -> Option<String> {
|
||||
let pointer64 = self.eat(b'E');
|
||||
let pointee_cv = cv(self.next()?)?;
|
||||
let pointee = self.data_type()?;
|
||||
let width = if pointer64 { " __ptr64" } else { "" };
|
||||
Some(format!("{pointee}{pointee_cv} {symbol}{own}{width}"))
|
||||
}
|
||||
}
|
||||
|
||||
fn cv(code: u8) -> Option<&'static str> {
|
||||
Some(match code {
|
||||
b'A' => "",
|
||||
b'B' => " const",
|
||||
b'C' => " volatile",
|
||||
b'D' => " const volatile",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
fn pointer_cv(code: u8) -> &'static str {
|
||||
match code {
|
||||
b'Q' => " const",
|
||||
b'R' => " volatile",
|
||||
b'S' => " const volatile",
|
||||
_ => "",
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::demangle;
|
||||
|
||||
#[test]
|
||||
fn decodes_global_functions_and_operators() {
|
||||
for (decorated, expected) in [
|
||||
("?foo@@YAXXZ", "void __cdecl foo(void)"),
|
||||
("?foo@@YAHH@Z", "int __cdecl foo(int)"),
|
||||
("?f@@YAXPEBD@Z", "void __cdecl f(char const * __ptr64)"),
|
||||
("?f@@YAXHZZ", "void __cdecl f(int,...)"),
|
||||
(
|
||||
"??2@YAPEAX_K@Z",
|
||||
"void * __ptr64 __cdecl operator new(unsigned __int64)",
|
||||
),
|
||||
(
|
||||
"??3@YAXPEAX@Z",
|
||||
"void __cdecl operator delete(void * __ptr64)",
|
||||
),
|
||||
(
|
||||
"??_U@YAPEAX_K@Z",
|
||||
"void * __ptr64 __cdecl operator new[](unsigned __int64)",
|
||||
),
|
||||
(
|
||||
"?_Xlength_error@std@@YAXPEBD@Z",
|
||||
"void __cdecl std::_Xlength_error(char const * __ptr64)",
|
||||
),
|
||||
("?g@@YA_N_J0@Z", "bool __cdecl g(__int64,__int64)"),
|
||||
] {
|
||||
assert_eq!(
|
||||
demangle(decorated).as_deref(),
|
||||
Some(expected),
|
||||
"{decorated}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_members_constructors_and_data() {
|
||||
for (decorated, expected) in [
|
||||
(
|
||||
"?bar@Foo@@QEAAXH@Z",
|
||||
"public: void __cdecl Foo::bar(int) __ptr64",
|
||||
),
|
||||
(
|
||||
"?get@Foo@@QEBAHXZ",
|
||||
"public: int __cdecl Foo::get(void)const __ptr64",
|
||||
),
|
||||
("??0Foo@@QEAA@XZ", "public: __cdecl Foo::Foo(void) __ptr64"),
|
||||
(
|
||||
"??1Foo@@UEAA@XZ",
|
||||
"public: virtual __cdecl Foo::~Foo(void) __ptr64",
|
||||
),
|
||||
(
|
||||
"?make@Foo@@SAPEAV1@XZ",
|
||||
"public: static class Foo * __ptr64 __cdecl Foo::make(void)",
|
||||
),
|
||||
("?x@ns@@3HA", "int ns::x"),
|
||||
("?count@Foo@@2HB", "public: static int const Foo::count"),
|
||||
("??_7type_info@@6B@", "const type_info::`vftable'"),
|
||||
] {
|
||||
assert_eq!(
|
||||
demangle(decorated).as_deref(),
|
||||
Some(expected),
|
||||
"{decorated}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_templates_and_back_references() {
|
||||
assert_eq!(
|
||||
demangle("?g@@YAXAEAV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z")
|
||||
.as_deref(),
|
||||
Some(
|
||||
"void __cdecl g(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > & __ptr64)"
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
demangle("?h@@YAXV?$array@H$0BA@@std@@@Z").as_deref(),
|
||||
Some("void __cdecl h(class std::array<int,16>)")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_undecorated_and_unsupported_names() {
|
||||
for symbol in [
|
||||
"malloc",
|
||||
"",
|
||||
"?",
|
||||
"?foo@@",
|
||||
"?foo@@YAXXZtrailing",
|
||||
"??_R0?AVtype_info@@@8",
|
||||
"?f@@YAXP6AXXZ@Z",
|
||||
&format!("?f@@YAX{}@Z", "PEA".repeat(40) + "H"),
|
||||
] {
|
||||
assert_eq!(demangle(symbol), None, "{symbol}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,217 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Automated C / POSIX header parser for metadata ingestion.
|
||||
//!
|
||||
//! Ingests standard system headers (e.g. `/usr/include/math.h`, `_string.h`)
|
||||
//! and extracts function signatures into typed `FunctionSignature` definitions.
|
||||
//!
|
||||
//! Preserves clean-room provenance and licensing attribution.
|
||||
|
||||
use crate::metadata::{AbiType, CallingConvention, FunctionSignature, MetadataCatalog, ParamDesc};
|
||||
use std::path::Path;
|
||||
|
||||
/// Ingest C header files from disk into `catalog`.
|
||||
pub fn ingest_header_file(
|
||||
catalog: &mut MetadataCatalog,
|
||||
module: &str,
|
||||
header_path: &Path,
|
||||
) -> Result<usize, String> {
|
||||
let content = std::fs::read_to_string(header_path)
|
||||
.map_err(|e| format!("cannot read {}: {e}", header_path.display()))?;
|
||||
|
||||
let filename = header_path
|
||||
.file_name()
|
||||
.and_then(|n| n.to_str())
|
||||
.unwrap_or("header.h");
|
||||
|
||||
let count = parse_c_declarations(catalog, module, filename, &content);
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
/// Ingest standard macOS SDK math and string headers if available.
|
||||
pub fn ingest_standard_system_headers(catalog: &mut MetadataCatalog) -> usize {
|
||||
let candidates = [
|
||||
(
|
||||
"ucrtbase.dll",
|
||||
"/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/math.h",
|
||||
),
|
||||
(
|
||||
"ucrtbase.dll",
|
||||
"/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/_string.h",
|
||||
),
|
||||
];
|
||||
|
||||
let mut total = 0;
|
||||
for (mod_name, path_str) in candidates {
|
||||
let p = Path::new(path_str);
|
||||
if p.exists()
|
||||
&& let Ok(n) = ingest_header_file(catalog, mod_name, p)
|
||||
{
|
||||
total += n;
|
||||
}
|
||||
}
|
||||
total
|
||||
}
|
||||
|
||||
/// Parse C function prototypes from `content`.
|
||||
fn parse_c_declarations(
|
||||
catalog: &mut MetadataCatalog,
|
||||
module: &str,
|
||||
header_name: &str,
|
||||
content: &str,
|
||||
) -> usize {
|
||||
let mut added = 0;
|
||||
|
||||
for line in content.lines() {
|
||||
let line = line.trim();
|
||||
// Look for lines containing function prototypes, e.g. "extern double acos(double);" or "int strcmp(...);"
|
||||
if !line.contains('(')
|
||||
|| !line.contains(')')
|
||||
|| line.starts_with('#')
|
||||
|| line.starts_with("/*")
|
||||
|| line.starts_with('*')
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// Clean up __attribute__, extern, etc.
|
||||
let cleaned = line
|
||||
.replace("extern ", "")
|
||||
.replace("__DARWIN_ALIAS(", "/* alias */ ")
|
||||
.replace("__DARWIN_ALIAS_C(", "/* alias */ ")
|
||||
.replace("_LIBC_CSTR", "char *")
|
||||
.replace("_LIBC_UNSAFE_INDEXABLE", "");
|
||||
|
||||
let Some(open_paren) = cleaned.find('(') else {
|
||||
continue;
|
||||
};
|
||||
let Some(close_paren) = cleaned[open_paren..].find(')') else {
|
||||
continue;
|
||||
};
|
||||
let close_paren = open_paren + close_paren;
|
||||
|
||||
let decl_left = cleaned[..open_paren].trim();
|
||||
let args_str = cleaned[open_paren + 1..close_paren].trim();
|
||||
|
||||
// Split return type and function name
|
||||
let parts: Vec<&str> = decl_left.split_whitespace().collect();
|
||||
if parts.len() < 2 {
|
||||
continue;
|
||||
}
|
||||
let ret_str = parts[..parts.len() - 1].join(" ");
|
||||
let name_str = parts[parts.len() - 1].trim_start_matches('*');
|
||||
|
||||
if !is_valid_c_ident(name_str) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let ret_type = match parse_c_type(&ret_str) {
|
||||
Some(t) => t,
|
||||
None => continue,
|
||||
};
|
||||
|
||||
let mut params = Vec::new();
|
||||
if !args_str.is_empty() && args_str != "void" {
|
||||
for (idx, arg) in args_str.split(',').enumerate() {
|
||||
let arg_clean = arg.trim();
|
||||
let arg_parts: Vec<&str> = arg_clean.split_whitespace().collect();
|
||||
let (param_name, type_str) = if arg_parts.is_empty() {
|
||||
(format!("arg{idx}"), "void".to_string())
|
||||
} else if arg_parts.len() == 1 {
|
||||
(format!("arg{idx}"), arg_parts[0].to_string())
|
||||
} else {
|
||||
let last = arg_parts[arg_parts.len() - 1].trim_start_matches('*');
|
||||
if is_valid_c_ident(last) {
|
||||
(last.to_string(), arg_parts[..arg_parts.len() - 1].join(" "))
|
||||
} else {
|
||||
(format!("arg{idx}"), arg_clean.to_string())
|
||||
}
|
||||
};
|
||||
|
||||
let param_type = parse_c_type(&type_str).unwrap_or(AbiType::U64);
|
||||
params.push(ParamDesc {
|
||||
name: param_name,
|
||||
abi_type: param_type,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let sig = FunctionSignature {
|
||||
name: name_str.to_string(),
|
||||
return_type: ret_type,
|
||||
params,
|
||||
convention: CallingConvention::Win64,
|
||||
header_source: format!("<{header_name}>"),
|
||||
doc: format!("Ingested from {header_name}"),
|
||||
};
|
||||
|
||||
catalog
|
||||
.entries
|
||||
.insert((module.to_ascii_lowercase(), name_str.to_string()), sig);
|
||||
added += 1;
|
||||
}
|
||||
|
||||
added
|
||||
}
|
||||
|
||||
fn is_valid_c_ident(s: &str) -> bool {
|
||||
if s.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let bytes = s.as_bytes();
|
||||
if !bytes[0].is_ascii_alphabetic() && bytes[0] != b'_' {
|
||||
return false;
|
||||
}
|
||||
bytes
|
||||
.iter()
|
||||
.all(|&b| b.is_ascii_alphanumeric() || b == b'_')
|
||||
}
|
||||
|
||||
fn parse_c_type(s: &str) -> Option<AbiType> {
|
||||
let s = s.trim();
|
||||
if s == "void" {
|
||||
Some(AbiType::Void)
|
||||
} else if s == "int" || s == "int32_t" {
|
||||
Some(AbiType::I32)
|
||||
} else if s == "unsigned int" || s == "uint32_t" || s == "unsigned" {
|
||||
Some(AbiType::U32)
|
||||
} else if s == "long long" || s == "int64_t" {
|
||||
Some(AbiType::I64)
|
||||
} else if s == "size_t" || s == "unsigned long" || s == "unsigned long long" || s == "uint64_t"
|
||||
{
|
||||
Some(AbiType::U64)
|
||||
} else if s == "float" {
|
||||
Some(AbiType::F32)
|
||||
} else if s == "double" {
|
||||
Some(AbiType::F64)
|
||||
} else if s.contains("const char") || s.contains("char *") {
|
||||
Some(AbiType::StringAnsi)
|
||||
} else if s.contains('*') {
|
||||
Some(AbiType::Pointer {
|
||||
is_const: s.contains("const"),
|
||||
pointee: "void".into(),
|
||||
})
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_parse_declarations_from_string() {
|
||||
let mut cat = MetadataCatalog::new();
|
||||
let c_code = r#"
|
||||
extern double cos(double x);
|
||||
extern double atan2(double y, double x);
|
||||
int strcmp(const char *s1, const char *s2);
|
||||
"#;
|
||||
let count = parse_c_declarations(&mut cat, "ucrtbase.dll", "test.h", c_code);
|
||||
assert_eq!(count, 3);
|
||||
assert!(cat.lookup("ucrtbase.dll", "cos").is_some());
|
||||
assert!(cat.lookup("ucrtbase.dll", "atan2").is_some());
|
||||
assert!(cat.lookup("ucrtbase.dll", "strcmp").is_some());
|
||||
}
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Deterministic Win32/CRT import binding generator for Xenora.
|
||||
//!
|
||||
//! Reads an import list (PE file or CSV produced by `xenora probe`), classifies each
|
||||
//! symbol against a built-in public-API database derived from documented Win32/CRT
|
||||
//! specifications and MinGW-w64 / POSIX equivalents, then generates:
|
||||
//!
|
||||
//! - `generated_crt.rs` — CRT functions mapped to native libc via `extern "C"` FFI
|
||||
//! - `generated_stubs.rs` — Logged stubs for functions that cannot be automatically mapped
|
||||
//! - `generated_tests.rs` — Conformance tests for every generated binding
|
||||
//! - `generated_manifest.csv`— Machine-readable coverage report
|
||||
//!
|
||||
//! The generator is completely offline. It consumes no AI tokens and has no network
|
||||
//! dependencies. Output is deterministic and idempotent given the same inputs.
|
||||
//!
|
||||
//! # Classification tiers
|
||||
//!
|
||||
//! | Tier | Meaning |
|
||||
//! |------|---------|
|
||||
//! | `CrtNative` | Directly maps to a libc symbol with identical semantics |
|
||||
//! | `CrtWrapper` | Maps to libc with argument/return marshalling |
|
||||
//! | `Win32Stub` | Windows-specific; generated as a logged stub |
|
||||
//! | `Unsupported`| Proprietary/unavailable; noted in manifest, no code emitted |
|
||||
//! | `Manual` | Requires hand-written implementation; flagged in report |
|
||||
|
||||
pub mod apiset;
|
||||
pub mod classify;
|
||||
pub mod codegen;
|
||||
pub mod demangle;
|
||||
pub mod ingest;
|
||||
pub mod manifest;
|
||||
pub mod metadata;
|
||||
pub mod parse;
|
||||
pub mod typed;
|
||||
pub mod verify;
|
||||
|
||||
pub use apiset::{get_api_sets_for_canonical, resolve_api_set_canonical};
|
||||
pub use classify::{Classification, SymbolDb};
|
||||
pub use codegen::{GeneratedFiles, generate};
|
||||
pub use demangle::demangle;
|
||||
pub use ingest::{ingest_header_file, ingest_standard_system_headers};
|
||||
pub use manifest::Manifest;
|
||||
pub use metadata::{AbiType, CallingConvention, FunctionSignature, MetadataCatalog};
|
||||
pub use parse::{ImportRecord, parse_csv};
|
||||
pub use verify::{VerificationResult, run_verification};
|
||||
|
||||
/// Top-level entry point. Reads `csv_path`, classifies every symbol, generates
|
||||
/// Rust source into `out_dir`, and writes `generated_manifest.csv`.
|
||||
pub fn run(csv_path: &str, out_dir: &str) -> Result<Manifest, String> {
|
||||
let records = parse_csv(csv_path)?;
|
||||
let db = SymbolDb::builtin();
|
||||
let manifest = Manifest::build(&records, &db);
|
||||
let files = generate(&manifest, &db);
|
||||
files.write_all(out_dir)?;
|
||||
manifest.write_csv(&format!("{out_dir}/generated_manifest.csv"))?;
|
||||
Ok(manifest)
|
||||
}
|
||||
@@ -1,180 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Coverage manifest: collects classified records and renders reports.
|
||||
|
||||
use crate::classify::{Classification, SymbolDb};
|
||||
use crate::parse::ImportRecord;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
/// One classified import entry.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ManifestEntry {
|
||||
pub module: String,
|
||||
pub symbol: String,
|
||||
pub ordinal: Option<u16>,
|
||||
pub iat_rva: u64,
|
||||
pub classification: Classification,
|
||||
}
|
||||
|
||||
impl ManifestEntry {
|
||||
pub(crate) fn key(&self) -> (String, Option<u16>, &str) {
|
||||
(
|
||||
self.module.to_ascii_lowercase(),
|
||||
self.ordinal,
|
||||
if self.ordinal.is_none() {
|
||||
&self.symbol
|
||||
} else {
|
||||
""
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
pub fn tier(&self) -> &'static str {
|
||||
self.classification.tier_name()
|
||||
}
|
||||
/// Runtime disposition of the generated output for this import.
|
||||
pub fn emission(&self) -> &'static str {
|
||||
match &self.classification {
|
||||
Classification::StandardService => "runtime-service",
|
||||
Classification::CrtNative { .. }
|
||||
if crate::codegen::crt_dispatch_expr(&self.symbol).is_some() =>
|
||||
{
|
||||
"generated-adapter"
|
||||
}
|
||||
Classification::CrtNative { .. }
|
||||
| Classification::CrtWrapper { .. }
|
||||
| Classification::RuntimeHelper { .. }
|
||||
| Classification::Win32Stub { .. } => "generated-stub",
|
||||
Classification::Manual { .. } | Classification::Unsupported { .. } => "no-binding",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Full coverage manifest for a set of import records.
|
||||
pub struct Manifest {
|
||||
pub entries: Vec<ManifestEntry>,
|
||||
}
|
||||
|
||||
impl Manifest {
|
||||
/// Classify every record using the symbol database.
|
||||
pub fn build(records: &[ImportRecord], db: &SymbolDb) -> Self {
|
||||
let mut entries = Vec::with_capacity(records.len());
|
||||
for rec in records {
|
||||
// Check for exact symbol match, then wildcard module match
|
||||
let classification = if rec.ordinal.is_some() {
|
||||
Classification::Manual {
|
||||
reason: "ordinal requires a documented export mapping in the typed runtime registry",
|
||||
}
|
||||
} else if let Some(c) = db.get(&rec.module, &rec.symbol) {
|
||||
c.clone()
|
||||
} else if let Some(c) = db.get(&rec.module, "__wildcard__") {
|
||||
c.clone()
|
||||
} else {
|
||||
// Unknown — treat as Manual
|
||||
Classification::Manual {
|
||||
reason: "no entry in built-in database — engineer required",
|
||||
}
|
||||
};
|
||||
entries.push(ManifestEntry {
|
||||
module: rec.module.clone(),
|
||||
symbol: rec.symbol.clone(),
|
||||
ordinal: rec.ordinal,
|
||||
iat_rva: rec.iat_rva,
|
||||
classification,
|
||||
});
|
||||
}
|
||||
Self { entries }
|
||||
}
|
||||
|
||||
/// Count entries by tier.
|
||||
pub fn summary(&self) -> BTreeMap<&'static str, usize> {
|
||||
let mut m: BTreeMap<&'static str, usize> = BTreeMap::new();
|
||||
for e in &self.entries {
|
||||
*m.entry(e.tier()).or_default() += 1;
|
||||
}
|
||||
m
|
||||
}
|
||||
|
||||
/// Count distinct module and symbol keys by emitted disposition.
|
||||
pub fn emission_summary(&self) -> BTreeMap<&'static str, usize> {
|
||||
let mut seen = BTreeSet::new();
|
||||
let mut counts = BTreeMap::new();
|
||||
for entry in &self.entries {
|
||||
if seen.insert(entry.key()) {
|
||||
*counts.entry(entry.emission()).or_default() += 1;
|
||||
}
|
||||
}
|
||||
counts
|
||||
}
|
||||
|
||||
/// Entries that the generator can produce code for.
|
||||
pub fn generatable(&self) -> impl Iterator<Item = &ManifestEntry> {
|
||||
self.entries
|
||||
.iter()
|
||||
.filter(|e| e.classification.is_generatable())
|
||||
}
|
||||
|
||||
/// Write the manifest as CSV for `xenora imports sync` integration.
|
||||
pub fn write_csv(&self, path: &str) -> Result<(), String> {
|
||||
let mut out = String::from("module,symbol,iat_rva,tier,emission,import_kind\n");
|
||||
for e in &self.entries {
|
||||
let kind = if e.ordinal.is_some() {
|
||||
"ordinal"
|
||||
} else {
|
||||
"name"
|
||||
};
|
||||
out.push_str(&format!(
|
||||
"\"{}\",\"{}\",0x{:08x},{},{},{kind}\n",
|
||||
e.module,
|
||||
e.symbol,
|
||||
e.iat_rva,
|
||||
e.tier(),
|
||||
e.emission()
|
||||
));
|
||||
}
|
||||
std::fs::write(path, out).map_err(|e| format!("write manifest CSV {path}: {e}"))
|
||||
}
|
||||
|
||||
/// Human-readable Markdown summary.
|
||||
pub fn render_markdown(&self) -> String {
|
||||
let summary = self.summary();
|
||||
let total = self.entries.len();
|
||||
let mut md = String::new();
|
||||
md.push_str("# Xenora import generator manifest\n\n");
|
||||
md.push_str("Generated by `xenora imports generate`. Do not edit manually.\n\n");
|
||||
md.push_str("## Catalog classification by import slot\n\n");
|
||||
md.push_str("| Tier | Count | % |\n| --- | ---: | ---: |\n");
|
||||
let total_pct = if total == 0 { 0 } else { 100 };
|
||||
md.push_str(&format!("| **Total** | {total} | {total_pct}% |\n"));
|
||||
for (tier, count) in &summary {
|
||||
let pct = (*count as f64 / total as f64 * 100.0) as u32;
|
||||
md.push_str(&format!("| `{tier}` | {count} | {pct}% |\n"));
|
||||
}
|
||||
md.push_str("\n## Emitted disposition by distinct import\n\n");
|
||||
md.push_str("| Disposition | Count |\n| --- | ---: |\n");
|
||||
let emissions = self.emission_summary();
|
||||
md.push_str(&format!(
|
||||
"| **Total** | {} |\n",
|
||||
emissions.values().sum::<usize>()
|
||||
));
|
||||
for (disposition, count) in emissions {
|
||||
md.push_str(&format!("| `{disposition}` | {count} |\n"));
|
||||
}
|
||||
md.push_str("\nAdapters are emitted as partial handlers. Runtime services use existing registrations.\n");
|
||||
md.push_str("\n## Functions requiring manual engineering\n\n");
|
||||
for e in &self.entries {
|
||||
if let Classification::Manual { reason } | Classification::Unsupported { reason } =
|
||||
&e.classification
|
||||
{
|
||||
match crate::demangle(&e.symbol) {
|
||||
Some(name) => md.push_str(&format!(
|
||||
"- `{}!{}` (`{name}`) — {reason}\n",
|
||||
e.module, e.symbol
|
||||
)),
|
||||
None => md.push_str(&format!("- `{}!{}` — {reason}\n", e.module, e.symbol)),
|
||||
}
|
||||
}
|
||||
}
|
||||
md
|
||||
}
|
||||
}
|
||||
@@ -1,467 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Versioned, offline API metadata definitions.
|
||||
//!
|
||||
//! Stores typed function signatures, parameter descriptions, calling conventions,
|
||||
//! and header sources derived from public Win32 and MinGW-w64 metadata.
|
||||
//!
|
||||
//! Strictly clean-room: derived from public documentation, MIT/BSD-licensed headers,
|
||||
//! or ISO C/POSIX standards.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// Calling convention used by the foreign function.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum CallingConvention {
|
||||
/// Standard Microsoft x64 (RCX, RDX, R8, R9, Stack)
|
||||
Win64,
|
||||
/// Standard CDECL / System V AMD64
|
||||
Cdecl,
|
||||
}
|
||||
|
||||
/// Primitive argument and return types supported by the ABI translator.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum AbiType {
|
||||
Void,
|
||||
Bool,
|
||||
I32,
|
||||
U32,
|
||||
I64,
|
||||
U64,
|
||||
F32,
|
||||
F64,
|
||||
/// Opaque Win64 object handle.
|
||||
Handle,
|
||||
/// Raw guest pointer (virtual address).
|
||||
Pointer {
|
||||
is_const: bool,
|
||||
pointee: String,
|
||||
},
|
||||
/// Null-terminated UTF-8 / ANSI string in guest memory.
|
||||
StringAnsi,
|
||||
/// Null-terminated UTF-16 wide string in guest memory.
|
||||
StringWide,
|
||||
/// Complex composite struct passed by pointer.
|
||||
Struct(String),
|
||||
}
|
||||
|
||||
/// Complete parameter specification.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ParamDesc {
|
||||
pub name: String,
|
||||
pub abi_type: AbiType,
|
||||
}
|
||||
|
||||
/// Complete function signature in the metadata database.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct FunctionSignature {
|
||||
pub name: String,
|
||||
pub return_type: AbiType,
|
||||
pub params: Vec<ParamDesc>,
|
||||
pub convention: CallingConvention,
|
||||
pub header_source: String,
|
||||
pub doc: String,
|
||||
}
|
||||
|
||||
/// Versioned metadata catalog for a subsystem or DLL.
|
||||
pub struct MetadataCatalog {
|
||||
pub version: u32,
|
||||
pub entries: BTreeMap<(String, String), FunctionSignature>, // (canonical_module, symbol) -> sig
|
||||
}
|
||||
|
||||
impl Default for MetadataCatalog {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl MetadataCatalog {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
version: 1,
|
||||
entries: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Load the built-in clean-room metadata catalog and ingest system headers.
|
||||
pub fn builtin() -> Self {
|
||||
let mut cat = Self::new();
|
||||
cat.populate_crt();
|
||||
cat.populate_win32_core();
|
||||
// Genuine automated ingestion of available public system C/POSIX headers
|
||||
crate::ingest::ingest_standard_system_headers(&mut cat);
|
||||
cat
|
||||
}
|
||||
|
||||
pub fn lookup(&self, canonical_module: &str, symbol: &str) -> Option<&FunctionSignature> {
|
||||
let key = (canonical_module.to_ascii_lowercase(), symbol.to_string());
|
||||
self.entries.get(&key)
|
||||
}
|
||||
|
||||
fn add(
|
||||
&mut self,
|
||||
module: &str,
|
||||
name: &str,
|
||||
ret: AbiType,
|
||||
params: Vec<(&str, AbiType)>,
|
||||
header: &str,
|
||||
doc: &str,
|
||||
) {
|
||||
let sig = FunctionSignature {
|
||||
name: name.to_string(),
|
||||
return_type: ret,
|
||||
params: params
|
||||
.into_iter()
|
||||
.map(|(pname, ptype)| ParamDesc {
|
||||
name: pname.to_string(),
|
||||
abi_type: ptype,
|
||||
})
|
||||
.collect(),
|
||||
convention: CallingConvention::Win64,
|
||||
header_source: header.to_string(),
|
||||
doc: doc.to_string(),
|
||||
};
|
||||
self.entries
|
||||
.insert((module.to_ascii_lowercase(), name.to_string()), sig);
|
||||
}
|
||||
|
||||
fn populate_crt(&mut self) {
|
||||
// math.h
|
||||
for name in &[
|
||||
"cos", "sin", "tan", "acos", "asin", "atan", "exp", "log", "sqrt", "fabs",
|
||||
] {
|
||||
self.add(
|
||||
"ucrtbase.dll",
|
||||
name,
|
||||
AbiType::F64,
|
||||
vec![("x", AbiType::F64)],
|
||||
"<math.h>",
|
||||
"ISO C standard math single-argument double",
|
||||
);
|
||||
}
|
||||
for name in &[
|
||||
"cosf", "sinf", "tanf", "acosf", "asinf", "atanf", "expf", "logf", "sqrtf", "fabsf",
|
||||
] {
|
||||
self.add(
|
||||
"ucrtbase.dll",
|
||||
name,
|
||||
AbiType::F32,
|
||||
vec![("x", AbiType::F32)],
|
||||
"<math.h>",
|
||||
"ISO C standard math single-argument float",
|
||||
);
|
||||
}
|
||||
self.add(
|
||||
"ucrtbase.dll",
|
||||
"atan2",
|
||||
AbiType::F64,
|
||||
vec![("y", AbiType::F64), ("x", AbiType::F64)],
|
||||
"<math.h>",
|
||||
"ISO C arc tangent of two variables",
|
||||
);
|
||||
self.add(
|
||||
"ucrtbase.dll",
|
||||
"atan2f",
|
||||
AbiType::F32,
|
||||
vec![("y", AbiType::F32), ("x", AbiType::F32)],
|
||||
"<math.h>",
|
||||
"ISO C arc tangent of two variables (float)",
|
||||
);
|
||||
self.add(
|
||||
"ucrtbase.dll",
|
||||
"pow",
|
||||
AbiType::F64,
|
||||
vec![("base", AbiType::F64), ("exp", AbiType::F64)],
|
||||
"<math.h>",
|
||||
"ISO C power function",
|
||||
);
|
||||
self.add(
|
||||
"ucrtbase.dll",
|
||||
"powf",
|
||||
AbiType::F32,
|
||||
vec![("base", AbiType::F32), ("exp", AbiType::F32)],
|
||||
"<math.h>",
|
||||
"ISO C power function (float)",
|
||||
);
|
||||
|
||||
// string.h
|
||||
self.add(
|
||||
"ucrtbase.dll",
|
||||
"strlen",
|
||||
AbiType::U64,
|
||||
vec![("str", AbiType::StringAnsi)],
|
||||
"<string.h>",
|
||||
"Calculates the length of a string in guest memory",
|
||||
);
|
||||
self.add(
|
||||
"ucrtbase.dll",
|
||||
"strnlen",
|
||||
AbiType::U64,
|
||||
vec![("str", AbiType::StringAnsi), ("count", AbiType::U64)],
|
||||
"<string.h>",
|
||||
"Calculates a byte string length up to the supplied bound",
|
||||
);
|
||||
self.add(
|
||||
"ucrtbase.dll",
|
||||
"strcmp",
|
||||
AbiType::I32,
|
||||
vec![("str1", AbiType::StringAnsi), ("str2", AbiType::StringAnsi)],
|
||||
"<string.h>",
|
||||
"Compares two strings lexicographically",
|
||||
);
|
||||
self.add(
|
||||
"ucrtbase.dll",
|
||||
"strncmp",
|
||||
AbiType::I32,
|
||||
vec![
|
||||
("str1", AbiType::StringAnsi),
|
||||
("str2", AbiType::StringAnsi),
|
||||
("count", AbiType::U64),
|
||||
],
|
||||
"<string.h>",
|
||||
"Compares up to count characters of two strings",
|
||||
);
|
||||
self.add(
|
||||
"ucrtbase.dll",
|
||||
"wcslen",
|
||||
AbiType::U64,
|
||||
vec![("str", AbiType::StringWide)],
|
||||
"<wchar.h>",
|
||||
"Counts 16-bit Windows code units before the terminator",
|
||||
);
|
||||
self.add(
|
||||
"ucrtbase.dll",
|
||||
"wcsnlen",
|
||||
AbiType::U64,
|
||||
vec![("str", AbiType::StringWide), ("count", AbiType::U64)],
|
||||
"<wchar.h>",
|
||||
"Counts 16-bit Windows code units up to the supplied bound",
|
||||
);
|
||||
self.add(
|
||||
"ucrtbase.dll",
|
||||
"wcscmp",
|
||||
AbiType::I32,
|
||||
vec![("str1", AbiType::StringWide), ("str2", AbiType::StringWide)],
|
||||
"<wchar.h>",
|
||||
"Compares two strings of 16-bit Windows code units",
|
||||
);
|
||||
self.add(
|
||||
"ucrtbase.dll",
|
||||
"wcsncmp",
|
||||
AbiType::I32,
|
||||
vec![
|
||||
("str1", AbiType::StringWide),
|
||||
("str2", AbiType::StringWide),
|
||||
("count", AbiType::U64),
|
||||
],
|
||||
"<wchar.h>",
|
||||
"Compares up to count 16-bit Windows code units of two strings",
|
||||
);
|
||||
self.add(
|
||||
"ucrtbase.dll",
|
||||
"memset",
|
||||
AbiType::Pointer {
|
||||
is_const: false,
|
||||
pointee: "void".into(),
|
||||
},
|
||||
vec![
|
||||
(
|
||||
"dest",
|
||||
AbiType::Pointer {
|
||||
is_const: false,
|
||||
pointee: "void".into(),
|
||||
},
|
||||
),
|
||||
("c", AbiType::I32),
|
||||
("count", AbiType::U64),
|
||||
],
|
||||
"<string.h>",
|
||||
"Fills memory with a constant byte",
|
||||
);
|
||||
self.add(
|
||||
"ucrtbase.dll",
|
||||
"memcpy",
|
||||
AbiType::Pointer {
|
||||
is_const: false,
|
||||
pointee: "void".into(),
|
||||
},
|
||||
vec![
|
||||
(
|
||||
"dest",
|
||||
AbiType::Pointer {
|
||||
is_const: false,
|
||||
pointee: "void".into(),
|
||||
},
|
||||
),
|
||||
(
|
||||
"src",
|
||||
AbiType::Pointer {
|
||||
is_const: true,
|
||||
pointee: "void".into(),
|
||||
},
|
||||
),
|
||||
("count", AbiType::U64),
|
||||
],
|
||||
"<string.h>",
|
||||
"Copies memory between non-overlapping guest regions",
|
||||
);
|
||||
self.add(
|
||||
"ucrtbase.dll",
|
||||
"memmove",
|
||||
AbiType::Pointer {
|
||||
is_const: false,
|
||||
pointee: "void".into(),
|
||||
},
|
||||
vec![
|
||||
(
|
||||
"dest",
|
||||
AbiType::Pointer {
|
||||
is_const: false,
|
||||
pointee: "void".into(),
|
||||
},
|
||||
),
|
||||
(
|
||||
"src",
|
||||
AbiType::Pointer {
|
||||
is_const: true,
|
||||
pointee: "void".into(),
|
||||
},
|
||||
),
|
||||
("count", AbiType::U64),
|
||||
],
|
||||
"<string.h>",
|
||||
"Copies memory between guest ranges that may overlap",
|
||||
);
|
||||
self.add(
|
||||
"ucrtbase.dll",
|
||||
"memcmp",
|
||||
AbiType::I32,
|
||||
vec![
|
||||
(
|
||||
"buf1",
|
||||
AbiType::Pointer {
|
||||
is_const: true,
|
||||
pointee: "void".into(),
|
||||
},
|
||||
),
|
||||
(
|
||||
"buf2",
|
||||
AbiType::Pointer {
|
||||
is_const: true,
|
||||
pointee: "void".into(),
|
||||
},
|
||||
),
|
||||
("count", AbiType::U64),
|
||||
],
|
||||
"<string.h>",
|
||||
"Compares bytes in two memory buffers",
|
||||
);
|
||||
}
|
||||
|
||||
fn populate_win32_core(&mut self) {
|
||||
// kernel32 processthreads / synch
|
||||
self.add(
|
||||
"kernel32.dll",
|
||||
"GetCurrentProcessId",
|
||||
AbiType::U32,
|
||||
vec![],
|
||||
"<processthreadsapi.h>",
|
||||
"Retrieves the process identifier of the calling process",
|
||||
);
|
||||
self.add(
|
||||
"kernel32.dll",
|
||||
"GetCurrentThreadId",
|
||||
AbiType::U32,
|
||||
vec![],
|
||||
"<processthreadsapi.h>",
|
||||
"Retrieves the thread identifier of the calling thread",
|
||||
);
|
||||
self.add(
|
||||
"kernel32.dll",
|
||||
"GetLastError",
|
||||
AbiType::U32,
|
||||
vec![],
|
||||
"<errhandlingapi.h>",
|
||||
"Retrieves the calling thread's last-error code value",
|
||||
);
|
||||
self.add(
|
||||
"kernel32.dll",
|
||||
"SetLastError",
|
||||
AbiType::Void,
|
||||
vec![("dwErrCode", AbiType::U32)],
|
||||
"<errhandlingapi.h>",
|
||||
"Sets the last-error code for the calling thread",
|
||||
);
|
||||
self.add(
|
||||
"kernel32.dll",
|
||||
"GetThreadId",
|
||||
AbiType::U32,
|
||||
vec![("Thread", AbiType::Handle)],
|
||||
"<processthreadsapi.h>",
|
||||
"Retrieves the identifier of the specified thread",
|
||||
);
|
||||
self.add(
|
||||
"kernel32.dll",
|
||||
"DuplicateHandle",
|
||||
AbiType::Bool,
|
||||
vec![
|
||||
("hSourceProcessHandle", AbiType::Handle),
|
||||
("hSourceHandle", AbiType::Handle),
|
||||
("hTargetProcessHandle", AbiType::Handle),
|
||||
(
|
||||
"lpTargetHandle",
|
||||
AbiType::Pointer {
|
||||
is_const: false,
|
||||
pointee: "HANDLE".into(),
|
||||
},
|
||||
),
|
||||
("dwDesiredAccess", AbiType::U32),
|
||||
("bInheritHandle", AbiType::Bool),
|
||||
("dwOptions", AbiType::U32),
|
||||
],
|
||||
"<handleapi.h>",
|
||||
"Creates another handle to the same object",
|
||||
);
|
||||
for (name, return_type) in [
|
||||
("GetTickCount", AbiType::U32),
|
||||
("GetTickCount64", AbiType::U64),
|
||||
] {
|
||||
self.add(
|
||||
"kernel32.dll",
|
||||
name,
|
||||
return_type,
|
||||
vec![],
|
||||
"<sysinfoapi.h>",
|
||||
"Returns elapsed system uptime in milliseconds",
|
||||
);
|
||||
}
|
||||
self.add(
|
||||
"kernel32.dll",
|
||||
"QueryPerformanceCounter",
|
||||
AbiType::Bool,
|
||||
vec![(
|
||||
"lpPerformanceCount",
|
||||
AbiType::Pointer {
|
||||
is_const: false,
|
||||
pointee: "LARGE_INTEGER".into(),
|
||||
},
|
||||
)],
|
||||
"<profileapi.h>",
|
||||
"Retrieves the current value of the performance counter",
|
||||
);
|
||||
self.add(
|
||||
"kernel32.dll",
|
||||
"QueryPerformanceFrequency",
|
||||
AbiType::Bool,
|
||||
vec![(
|
||||
"lpFrequency",
|
||||
AbiType::Pointer {
|
||||
is_const: false,
|
||||
pointee: "LARGE_INTEGER".into(),
|
||||
},
|
||||
)],
|
||||
"<profileapi.h>",
|
||||
"Retrieves the frequency of the performance counter",
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,135 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! CSV parser for the `missing_imports.csv` produced by `xenora probe`.
|
||||
//!
|
||||
//! Format: `"module","symbol_or_ordinal","iat_rva"`
|
||||
//! An optional `import_kind` column distinguishes numeric ordinals from names.
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub struct ImportRecord {
|
||||
/// DLL name in original casing, e.g. `"api-ms-win-crt-math-l1-1-0.dll"`
|
||||
pub module: String,
|
||||
/// Symbol name or `Ordinal#N`
|
||||
pub symbol: String,
|
||||
pub ordinal: Option<u16>,
|
||||
/// IAT RVA (informational only, not used for generation)
|
||||
pub iat_rva: u64,
|
||||
}
|
||||
|
||||
/// Parse a CSV produced by `xenora probe`.
|
||||
/// Returns records sorted by (module_lc, symbol).
|
||||
pub fn parse_csv(path: &str) -> Result<Vec<ImportRecord>, String> {
|
||||
let content = std::fs::read_to_string(path).map_err(|e| format!("cannot read {path}: {e}"))?;
|
||||
let mut records = Vec::new();
|
||||
let mut kind_column = None;
|
||||
for (line_no, line) in content.lines().enumerate() {
|
||||
// Skip header (with or without quotes)
|
||||
let trimmed = line.trim();
|
||||
if line_no == 0 && (trimmed.starts_with("module") || trimmed.starts_with("\"module\"")) {
|
||||
kind_column = split_csv_line(trimmed)
|
||||
.iter()
|
||||
.position(|column| unquote(column) == "import_kind");
|
||||
continue;
|
||||
}
|
||||
let line = line.trim();
|
||||
if line.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let cols: Vec<&str> = split_csv_line(line);
|
||||
if cols.len() < 2 {
|
||||
continue;
|
||||
}
|
||||
let module = unquote(cols[0]).to_string();
|
||||
let symbol = unquote(cols[1]).to_string();
|
||||
let ordinal = match kind_column {
|
||||
None => None,
|
||||
Some(index) => match cols.get(index).map(|field| unquote(field)) {
|
||||
Some("name") => None,
|
||||
Some("ordinal") => Some(
|
||||
symbol
|
||||
.strip_prefix("Ordinal#")
|
||||
.and_then(|value| value.parse().ok())
|
||||
.ok_or_else(|| format!("{path}:{}: invalid ordinal", line_no + 1))?,
|
||||
),
|
||||
_ => return Err(format!("{path}:{}: invalid import_kind", line_no + 1)),
|
||||
},
|
||||
};
|
||||
let iat_rva = if cols.len() >= 3 {
|
||||
u64::from_str_radix(unquote(cols[2]).trim_start_matches("0x"), 16).unwrap_or(0)
|
||||
} else {
|
||||
0
|
||||
};
|
||||
if !module.is_empty() && !symbol.is_empty() {
|
||||
records.push(ImportRecord {
|
||||
module,
|
||||
symbol,
|
||||
ordinal,
|
||||
iat_rva,
|
||||
});
|
||||
}
|
||||
}
|
||||
records.sort();
|
||||
records.dedup();
|
||||
Ok(records)
|
||||
}
|
||||
|
||||
fn unquote(s: &str) -> &str {
|
||||
let s = s.trim();
|
||||
if s.starts_with('"') && s.ends_with('"') && s.len() >= 2 {
|
||||
&s[1..s.len() - 1]
|
||||
} else {
|
||||
s
|
||||
}
|
||||
}
|
||||
|
||||
/// Minimal CSV line splitter that handles quoted fields containing commas.
|
||||
fn split_csv_line(line: &str) -> Vec<&str> {
|
||||
let mut fields = Vec::new();
|
||||
let bytes = line.as_bytes();
|
||||
let mut i = 0;
|
||||
while i < bytes.len() {
|
||||
if bytes[i] == b'"' {
|
||||
// Find closing quote
|
||||
let start = i;
|
||||
i += 1;
|
||||
while i < bytes.len() && bytes[i] != b'"' {
|
||||
i += 1;
|
||||
}
|
||||
if i < bytes.len() {
|
||||
i += 1; // skip closing quote
|
||||
}
|
||||
fields.push(&line[start..i]);
|
||||
// skip comma
|
||||
if i < bytes.len() && bytes[i] == b',' {
|
||||
i += 1;
|
||||
}
|
||||
} else {
|
||||
let start = i;
|
||||
while i < bytes.len() && bytes[i] != b',' {
|
||||
i += 1;
|
||||
}
|
||||
fields.push(&line[start..i]);
|
||||
if i < bytes.len() {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
fields
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn split_basic() {
|
||||
let cols = split_csv_line(r#""foo.dll","bar",0x1234"#);
|
||||
assert_eq!(cols, vec![r#""foo.dll""#, r#""bar""#, "0x1234"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unquote_strips() {
|
||||
assert_eq!(unquote(r#""hello""#), "hello");
|
||||
assert_eq!(unquote("world"), "world");
|
||||
}
|
||||
}
|
||||
@@ -1,506 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Typed runtime services: parse and validate the declarative registry, and
|
||||
//! generate Win64 adapters, static metadata and a coverage report.
|
||||
|
||||
use crate::apiset::get_api_sets_for_canonical;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::fmt::Write as _;
|
||||
|
||||
/// Most arguments one service may declare.
|
||||
const MAX_PARAMETERS: usize = 16;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Parameter {
|
||||
pub name: String,
|
||||
pub kind: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Service {
|
||||
pub library: String,
|
||||
pub symbol: String,
|
||||
pub ordinal: Option<(u16, String)>,
|
||||
pub parameters: Vec<Parameter>,
|
||||
pub result: String,
|
||||
pub handler: String,
|
||||
pub status: String,
|
||||
pub aliases: Vec<String>,
|
||||
pub failure: String,
|
||||
pub reference: String,
|
||||
pub tests: Vec<String>,
|
||||
}
|
||||
|
||||
fn is_identifier(text: &str) -> bool {
|
||||
!text.is_empty()
|
||||
&& !text.as_bytes()[0].is_ascii_digit()
|
||||
&& text.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_')
|
||||
}
|
||||
|
||||
/// Adapter expression reading parameter `index`, or `None` for an unknown type.
|
||||
fn reader(kind: &str, index: usize) -> Option<String> {
|
||||
Some(match kind {
|
||||
"u32" | "i32" | "u64" | "bool32" | "f32" | "f64" => format!("call.{kind}({index})?"),
|
||||
"handle" | "ptr" => format!("call.u64({index})?"),
|
||||
_ => {
|
||||
let size: u32 = kind.strip_prefix("out<")?.strip_suffix('>')?.parse().ok()?;
|
||||
if !(1..=4096).contains(&size) {
|
||||
return None;
|
||||
}
|
||||
format!("call.out::<{size}>({index})?")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Rust type of a result other than void.
|
||||
fn result_type(kind: &str) -> &'static str {
|
||||
match kind {
|
||||
"u32" => "u32",
|
||||
"i32" => "i32",
|
||||
"bool32" => "bool",
|
||||
"f32" => "crate::runtime::Float32",
|
||||
"f64" => "crate::runtime::Float64",
|
||||
_ => "u64",
|
||||
}
|
||||
}
|
||||
|
||||
const RESULTS: [&str; 9] = [
|
||||
"void", "u32", "i32", "u64", "bool32", "handle", "ptr", "f32", "f64",
|
||||
];
|
||||
|
||||
/// Parse and validate the registry. `test_source` is the text of the test file
|
||||
/// that must define every named test.
|
||||
pub fn parse(text: &str, test_source: &str) -> Result<Vec<Service>, String> {
|
||||
let mut services: Vec<Service> = Vec::new();
|
||||
let mut seen_fields = BTreeSet::new();
|
||||
for (number, raw) in text.lines().enumerate() {
|
||||
let at = |message: &str| format!("line {}: {message}", number + 1);
|
||||
let line = raw.trim();
|
||||
if line.is_empty() || line.starts_with('#') {
|
||||
continue;
|
||||
}
|
||||
let (keyword, rest) = line.split_once(' ').ok_or_else(|| at("missing value"))?;
|
||||
let rest = rest.trim();
|
||||
if keyword == "service" {
|
||||
services.push(parse_signature(rest).map_err(|message| at(&message))?);
|
||||
seen_fields.clear();
|
||||
continue;
|
||||
}
|
||||
let service = services
|
||||
.last_mut()
|
||||
.ok_or_else(|| at("field outside a service"))?;
|
||||
let repeatable = matches!(keyword, "alias" | "test");
|
||||
if !repeatable && !seen_fields.insert(keyword.to_owned()) {
|
||||
return Err(at(&format!("repeated field {keyword}")));
|
||||
}
|
||||
match keyword {
|
||||
"handler" => service.handler = rest.to_owned(),
|
||||
"status" => service.status = rest.to_owned(),
|
||||
"alias" => service.aliases.push(rest.to_owned()),
|
||||
"ordinal" => {
|
||||
let (value, source) = rest
|
||||
.split_once(' ')
|
||||
.ok_or_else(|| at("ordinal needs a number and a source"))?;
|
||||
let value = value
|
||||
.parse::<u16>()
|
||||
.ok()
|
||||
.filter(|value| *value != 0)
|
||||
.ok_or_else(|| at("ordinal must be in 1..=65535"))?;
|
||||
service.ordinal = Some((value, source.trim().to_owned()));
|
||||
}
|
||||
"fails" => service.failure = rest.to_owned(),
|
||||
"ref" => service.reference = rest.to_owned(),
|
||||
"test" => service.tests.push(rest.to_owned()),
|
||||
other => return Err(at(&format!("unknown field {other}"))),
|
||||
}
|
||||
}
|
||||
validate(&services, test_source)?;
|
||||
Ok(services)
|
||||
}
|
||||
|
||||
fn parse_signature(text: &str) -> Result<Service, String> {
|
||||
let (library, rest) = text.split_once(' ').ok_or("missing symbol")?;
|
||||
let (symbol, rest) = rest.split_once('(').ok_or("missing parameter list")?;
|
||||
let (list, result) = rest.rsplit_once(") -> ").ok_or("missing result type")?;
|
||||
let mut parameters = Vec::new();
|
||||
if !list.trim().is_empty() {
|
||||
for parameter in list.split(',') {
|
||||
let (name, kind) = parameter.split_once(':').ok_or("parameter needs a type")?;
|
||||
parameters.push(Parameter {
|
||||
name: name.trim().to_owned(),
|
||||
kind: kind.trim().to_owned(),
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(Service {
|
||||
library: library.to_owned(),
|
||||
symbol: symbol.trim().to_owned(),
|
||||
ordinal: None,
|
||||
parameters,
|
||||
result: result.trim().to_owned(),
|
||||
handler: String::new(),
|
||||
status: String::new(),
|
||||
aliases: Vec::new(),
|
||||
failure: String::new(),
|
||||
reference: String::new(),
|
||||
tests: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
fn validate(services: &[Service], test_source: &str) -> Result<(), String> {
|
||||
// Every key a guest could import, with the service it resolves to.
|
||||
let mut keys: BTreeMap<(String, &str), usize> = BTreeMap::new();
|
||||
let mut ordinals = BTreeSet::new();
|
||||
for (index, service) in services.iter().enumerate() {
|
||||
let name = format!("{}!{}", service.library, service.symbol);
|
||||
let fail = |message: String| Err(format!("{name}: {message}"));
|
||||
if service.library != service.library.to_ascii_lowercase()
|
||||
|| !service.library.ends_with(".dll")
|
||||
|| service.library.starts_with("api-ms-")
|
||||
{
|
||||
return fail("library must be a lower-case canonical module".into());
|
||||
}
|
||||
if !is_identifier(&service.symbol) {
|
||||
return fail("symbol is not an identifier".into());
|
||||
}
|
||||
if let Some((ordinal, source)) = &service.ordinal {
|
||||
if source.is_empty() {
|
||||
return fail("ordinal needs a source".into());
|
||||
}
|
||||
if !ordinals.insert((&service.library, ordinal)) {
|
||||
return fail(format!("ordinal {ordinal} already resolves in this module"));
|
||||
}
|
||||
}
|
||||
if !is_identifier(&service.handler) {
|
||||
return fail("missing or invalid handler".into());
|
||||
}
|
||||
if service.parameters.len() > MAX_PARAMETERS {
|
||||
return fail("too many parameters".into());
|
||||
}
|
||||
let mut names = BTreeSet::new();
|
||||
for (position, parameter) in service.parameters.iter().enumerate() {
|
||||
if !is_identifier(¶meter.name) || !names.insert(¶meter.name) {
|
||||
return fail(format!("invalid parameter name {:?}", parameter.name));
|
||||
}
|
||||
if reader(¶meter.kind, position).is_none() {
|
||||
return fail(format!("unsupported parameter type {:?}", parameter.kind));
|
||||
}
|
||||
}
|
||||
if !RESULTS.contains(&service.result.as_str()) {
|
||||
return fail(format!("unsupported result type {:?}", service.result));
|
||||
}
|
||||
if !matches!(service.status.as_str(), "implemented" | "partial" | "stub") {
|
||||
return fail("status must be implemented, partial or stub".into());
|
||||
}
|
||||
if service.failure.is_empty() || service.reference.is_empty() {
|
||||
return fail("needs a failure contract and a reference".into());
|
||||
}
|
||||
if service.tests.is_empty() && service.status != "stub" {
|
||||
return fail("needs a test before it may claim behaviour".into());
|
||||
}
|
||||
for test in &service.tests {
|
||||
if !is_identifier(test) || !test_source.contains(&format!("fn {test}()")) {
|
||||
return fail(format!("test {test} does not exist"));
|
||||
}
|
||||
}
|
||||
let documented = get_api_sets_for_canonical(&service.library);
|
||||
let modules = std::iter::once(&service.library).chain(&service.aliases);
|
||||
for module in modules {
|
||||
if module != &service.library && !documented.contains(&module.as_str()) {
|
||||
return fail(format!("{module} is not a listed API set of its library"));
|
||||
}
|
||||
if keys
|
||||
.insert((module.clone(), &service.symbol), index)
|
||||
.is_some()
|
||||
{
|
||||
return fail(format!("{module} already resolves this symbol"));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn status_variant(status: &str) -> &'static str {
|
||||
match status {
|
||||
"implemented" => "Implemented",
|
||||
"partial" => "Partial",
|
||||
_ => "Stub",
|
||||
}
|
||||
}
|
||||
|
||||
fn string_list(items: &[String]) -> String {
|
||||
let quoted: Vec<String> = items.iter().map(|item| format!("{item:?}")).collect();
|
||||
format!("&[{}]", quoted.join(", "))
|
||||
}
|
||||
|
||||
/// Rust source of the adapters and metadata.
|
||||
pub fn generate_rust(services: &[Service]) -> String {
|
||||
let mut out = String::from(
|
||||
"// SPDX-License-Identifier: GPL-3.0-or-later\n\n\
|
||||
// Generated by xenora-runtime-gen from crates/loader/runtime/services.txt.\n\
|
||||
// Do not edit.\n\n\
|
||||
use crate::imports::{ImportRegistry, ServiceStatus};\n\
|
||||
use crate::runtime::{Call, Parameter, Return, ServiceContext, ServiceMetadata};\n\
|
||||
use crate::services::{ServicesState, handlers};\n\
|
||||
use std::sync::Arc;\n\n",
|
||||
);
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"pub static SERVICES: [ServiceMetadata; {}] = [",
|
||||
services.len()
|
||||
);
|
||||
for service in services {
|
||||
let parameters: Vec<String> = service
|
||||
.parameters
|
||||
.iter()
|
||||
.map(|p| format!("Parameter {{ name: {:?}, kind: {:?} }}", p.name, p.kind))
|
||||
.collect();
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" ServiceMetadata {{\n library: {:?},\n symbol: {:?},\n \
|
||||
parameters: &[{}],\n result: {:?},\n status: ServiceStatus::{},\n \
|
||||
aliases: {},\n failure: {:?},\n reference: {:?},\n tests: {},\n }},",
|
||||
service.library,
|
||||
service.symbol,
|
||||
parameters.join(", "),
|
||||
service.result,
|
||||
status_variant(&service.status),
|
||||
string_list(&service.aliases),
|
||||
service.failure,
|
||||
service.reference,
|
||||
string_list(&service.tests),
|
||||
);
|
||||
}
|
||||
out.push_str(
|
||||
"];\n\n/// Register every generated service and its API-set aliases.\n\
|
||||
pub fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {\n",
|
||||
);
|
||||
for service in services {
|
||||
let count = service.parameters.len();
|
||||
let names: String = (0..count).map(|index| format!(", a{index}")).collect();
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" let s = state.clone();\n registry.register_with_status({:?}, {:?}, ServiceStatus::{}, move |args, cpu, memory| {{",
|
||||
service.library,
|
||||
service.symbol,
|
||||
status_variant(&service.status),
|
||||
);
|
||||
if count == 0 {
|
||||
out.push_str(" let _ = (args, &Call::new);\n");
|
||||
} else {
|
||||
out.push_str(" let call = Call::new(args, cpu, memory);\n");
|
||||
}
|
||||
for (index, parameter) in service.parameters.iter().enumerate() {
|
||||
let read = reader(¶meter.kind, index).unwrap_or_default();
|
||||
let _ = writeln!(out, " let a{index} = {read};");
|
||||
}
|
||||
// The declared type is stated so that a handler returning another one
|
||||
// does not compile.
|
||||
let binding = match service.result.as_str() {
|
||||
"void" => "let ()".to_owned(),
|
||||
result => format!("let result: {}", result_type(result)),
|
||||
};
|
||||
let place = if service.result == "void" {
|
||||
"Ok(0)"
|
||||
} else {
|
||||
"Ok(result.place(cpu))"
|
||||
};
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" let mut context = ServiceContext {{ state: &s, memory, teb: cpu.gs_base }};\n {binding} = handlers::{}(&mut context{names})?;\n {place}\n }});",
|
||||
service.handler
|
||||
);
|
||||
if let Some((ordinal, _)) = &service.ordinal {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" registry.try_ordinal_alias({:?}, {:?}, {ordinal}).expect(\"validated export ordinal\");",
|
||||
service.library, service.symbol
|
||||
);
|
||||
}
|
||||
}
|
||||
out.push_str(" for service in &SERVICES {\n for alias in service.aliases {\n if let Err(error) = registry.try_alias(alias, service.library, service.symbol) {\n panic!(\"{error}\");\n }\n }\n }\n}\n");
|
||||
out.replace(
|
||||
" let _ = (args, &Call::new);\n",
|
||||
" let _ = args;\n",
|
||||
)
|
||||
}
|
||||
|
||||
/// Coverage report. Each count is distinct; aliases are never services.
|
||||
pub fn generate_report(services: &[Service]) -> String {
|
||||
let count = |status: &str| services.iter().filter(|s| s.status == status).count();
|
||||
let handlers: BTreeSet<&str> = services.iter().map(|s| s.handler.as_str()).collect();
|
||||
let aliases: usize = services.iter().map(|s| s.aliases.len()).sum();
|
||||
let tested = services.iter().filter(|s| !s.tests.is_empty()).count();
|
||||
let mut out = String::from(
|
||||
"# Typed runtime services\n\nGenerated by `xenora-runtime-gen` from `crates/loader/runtime/services.txt`. Do not edit.\n\n\
|
||||
A declared service is not a claim of compatibility. `implemented` and `partial` describe behaviour against the documented contract for the synthetic guest. No service has been independently accepted.\n\n\
|
||||
| Measure | Count |\n| --- | ---: |\n",
|
||||
);
|
||||
for (label, value) in [
|
||||
("Services with a declared ABI", services.len()),
|
||||
("Generated adapters", services.len()),
|
||||
("Unique handler implementations", handlers.len()),
|
||||
("Implemented", count("implemented")),
|
||||
("Partial", count("partial")),
|
||||
("Stub", count("stub")),
|
||||
("Conformance-tested through guest dispatch", tested),
|
||||
("API-set aliases (not services)", aliases),
|
||||
("Independently accepted", 0),
|
||||
] {
|
||||
let _ = writeln!(out, "| {label} | {value} |");
|
||||
}
|
||||
out.push_str("\n| Service | Signature | Status | Failure |\n| --- | --- | --- | --- |\n");
|
||||
for service in services {
|
||||
let parameters: Vec<String> = service
|
||||
.parameters
|
||||
.iter()
|
||||
.map(|p| format!("{}: {}", p.name, p.kind))
|
||||
.collect();
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"| `{}!{}` | `({}) -> {}` | {} | {} |",
|
||||
service.library,
|
||||
service.symbol,
|
||||
parameters.join(", "),
|
||||
service.result,
|
||||
service.status,
|
||||
service.failure
|
||||
);
|
||||
}
|
||||
for service in services {
|
||||
if let Some((ordinal, source)) = &service.ordinal {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"\nOrdinal {ordinal} for `{}!{}` is documented by {source}.",
|
||||
service.library, service.symbol
|
||||
);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const TESTS: &str = "fn works() {}";
|
||||
|
||||
fn entry(signature: &str, extra: &str) -> String {
|
||||
format!(
|
||||
"service {signature}\nhandler h\nstatus partial\nfails never\nref x.h\ntest works\n{extra}\n"
|
||||
)
|
||||
}
|
||||
|
||||
fn rejects(text: &str, message: &str) {
|
||||
let error = parse(text, TESTS).unwrap_err();
|
||||
assert!(error.contains(message), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn valid_entries_parse_and_generate_deterministically() {
|
||||
let text = entry(
|
||||
"kernel32.dll F(a: u32, b: f64, c: out<8>) -> handle",
|
||||
"alias api-ms-win-core-memory-l1-1-0.dll",
|
||||
);
|
||||
let services = parse(&text, TESTS).unwrap();
|
||||
assert_eq!(services[0].parameters[2].kind, "out<8>");
|
||||
let rust = generate_rust(&services);
|
||||
assert_eq!(rust, generate_rust(&services));
|
||||
for expected in ["call.u32(0)?", "call.f64(1)?", "call.out::<8>(2)?"] {
|
||||
assert!(rust.contains(expected), "{expected}");
|
||||
}
|
||||
assert!(generate_report(&services).contains("| Unique handler implementations | 1 |"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ordinal_requires_a_source_and_unique_module_key() {
|
||||
let first = entry("kernel32.dll F() -> void", "ordinal 42 test catalog");
|
||||
let services = parse(&first, TESTS).unwrap();
|
||||
assert!(
|
||||
generate_rust(&services).contains("try_ordinal_alias(\"kernel32.dll\", \"F\", 42)")
|
||||
);
|
||||
assert!(generate_report(&services).contains("documented by test catalog"));
|
||||
let second = entry("kernel32.dll G() -> void", "ordinal 42 test catalog");
|
||||
rejects(&(first + &second), "ordinal 42 already resolves");
|
||||
rejects(
|
||||
&entry("kernel32.dll F() -> void", "ordinal 42"),
|
||||
"needs a number and a source",
|
||||
);
|
||||
rejects(
|
||||
&entry("kernel32.dll F() -> void", "ordinal 65536 test catalog"),
|
||||
"1..=65535",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conflicting_keys_are_rejected() {
|
||||
let one = entry("kernel32.dll F() -> void", "");
|
||||
rejects(&(one.clone() + &one), "already resolves");
|
||||
let aliased = entry(
|
||||
"kernel32.dll F() -> void",
|
||||
"alias api-ms-win-core-memory-l1-1-0.dll",
|
||||
);
|
||||
let twice = entry(
|
||||
"kernel32.dll G() -> void",
|
||||
"alias api-ms-win-core-memory-l1-1-0.dll\nalias api-ms-win-core-memory-l1-1-0.dll",
|
||||
);
|
||||
assert!(parse(&aliased, TESTS).is_ok());
|
||||
rejects(&twice, "already resolves");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_declarations_are_rejected() {
|
||||
rejects(
|
||||
&entry("kernel32.dll F(a: struct) -> void", ""),
|
||||
"parameter type",
|
||||
);
|
||||
rejects(
|
||||
&entry("kernel32.dll F(a: out<0>) -> void", ""),
|
||||
"parameter type",
|
||||
);
|
||||
rejects(
|
||||
&entry("kernel32.dll F(a: void) -> void", ""),
|
||||
"parameter type",
|
||||
);
|
||||
rejects(&entry("kernel32.dll F() -> out<4>", ""), "result type");
|
||||
rejects(
|
||||
&entry("kernel32.dll F(a: u32, a: u32) -> void", ""),
|
||||
"parameter name",
|
||||
);
|
||||
rejects(&entry("Kernel32.dll F() -> void", ""), "canonical module");
|
||||
rejects(
|
||||
&entry("api-ms-win-core-memory-l1-1-0.dll F() -> void", ""),
|
||||
"canonical module",
|
||||
);
|
||||
rejects(
|
||||
&entry(
|
||||
"kernel32.dll F() -> void",
|
||||
"alias api-ms-win-core-made-up-l1-1-0.dll",
|
||||
),
|
||||
"not a listed API set",
|
||||
);
|
||||
rejects(
|
||||
&entry("kernel32.dll F() -> void", "colour blue"),
|
||||
"unknown field",
|
||||
);
|
||||
rejects(
|
||||
&entry("kernel32.dll F() -> void", "status stub"),
|
||||
"repeated field",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn behaviour_needs_evidence() {
|
||||
let untested =
|
||||
"service kernel32.dll F() -> void\nhandler h\nstatus partial\nfails never\nref x.h\n";
|
||||
rejects(untested, "needs a test");
|
||||
rejects(&(untested.to_owned() + "test missing\n"), "does not exist");
|
||||
let stub = untested.replace("partial", "stub");
|
||||
assert!(parse(&stub, TESTS).is_ok());
|
||||
rejects(
|
||||
&untested.replace("ref x.h\n", "test works\n"),
|
||||
"needs a failure contract",
|
||||
);
|
||||
rejects("handler h\n", "outside a service");
|
||||
}
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Verification and conformance test runner for import bindings.
|
||||
//!
|
||||
//! Runs deterministic synthetic checks against all generated bindings
|
||||
//! to ensure they adhere to Windows x64 ABI standards and guest memory safety.
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
/// Result of running the verification suite.
|
||||
#[derive(Debug)]
|
||||
pub struct VerificationResult {
|
||||
pub passed: usize,
|
||||
pub failed: usize,
|
||||
pub total: usize,
|
||||
pub details: Vec<String>,
|
||||
}
|
||||
|
||||
/// Run automated behavioral and conformance tests for generated bindings.
|
||||
pub fn run_verification() -> Result<VerificationResult, String> {
|
||||
let output = Command::new("cargo")
|
||||
.args([
|
||||
"test",
|
||||
"-p",
|
||||
"xenora-loader",
|
||||
"--test",
|
||||
"generated_conformance",
|
||||
])
|
||||
.output()
|
||||
.map_err(|e| format!("failed to execute cargo test: {e}"))?;
|
||||
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
|
||||
let mut passed = 0;
|
||||
let mut failed = 0;
|
||||
let mut details = Vec::new();
|
||||
|
||||
for line in stdout.lines() {
|
||||
if line.starts_with("test generated_test_") || line.starts_with("test generated_stubs_") {
|
||||
details.push(line.to_string());
|
||||
if line.ends_with("... ok") {
|
||||
passed += 1;
|
||||
} else if line.ends_with("... FAILED") {
|
||||
failed += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !output.status.success() && failed == 0 {
|
||||
return Err(format!("cargo test execution failed:\n{stderr}\n{stdout}"));
|
||||
}
|
||||
|
||||
Ok(VerificationResult {
|
||||
passed,
|
||||
failed,
|
||||
total: passed + failed,
|
||||
details,
|
||||
})
|
||||
}
|
||||
@@ -1,109 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Decorated names produced by an independent mangler: Apple clang 21 with
|
||||
//! `-target x86_64-pc-windows-msvc -S` on the declarations quoted beside each
|
||||
//! case. Expected strings restate those declarations in `undname` style; they
|
||||
//! are not taken from the decoder.
|
||||
|
||||
use xenora_import_gen::demangle;
|
||||
|
||||
#[test]
|
||||
fn clang_msvc_manglings_decode_to_their_declarations() {
|
||||
for (decorated, expected) in [
|
||||
// void foo();
|
||||
("?foo@@YAXXZ", "void __cdecl foo(void)"),
|
||||
// int foo2(int);
|
||||
("?foo2@@YAHH@Z", "int __cdecl foo2(int)"),
|
||||
// void f(const char*);
|
||||
("?f@@YAXPEBD@Z", "void __cdecl f(char const * __ptr64)"),
|
||||
// void fv(int, ...);
|
||||
("?fv@@YAXHZZ", "void __cdecl fv(int,...)"),
|
||||
// bool g(long long, long long);
|
||||
("?g@@YA_N_J0@Z", "bool __cdecl g(__int64,__int64)"),
|
||||
// namespace std { void _Xlength_error(const char*); }
|
||||
(
|
||||
"?_Xlength_error@std@@YAXPEBD@Z",
|
||||
"void __cdecl std::_Xlength_error(char const * __ptr64)",
|
||||
),
|
||||
// struct Foo { void bar(int); };
|
||||
(
|
||||
"?bar@Foo@@QEAAXH@Z",
|
||||
"public: void __cdecl Foo::bar(int) __ptr64",
|
||||
),
|
||||
// struct Foo { int get() const; };
|
||||
(
|
||||
"?get@Foo@@QEBAHXZ",
|
||||
"public: int __cdecl Foo::get(void)const __ptr64",
|
||||
),
|
||||
// struct Foo { Foo(); };
|
||||
("??0Foo@@QEAA@XZ", "public: __cdecl Foo::Foo(void) __ptr64"),
|
||||
// struct Foo { static Foo* make(); };
|
||||
(
|
||||
"?make@Foo@@SAPEAU1@XZ",
|
||||
"public: static struct Foo * __ptr64 __cdecl Foo::make(void)",
|
||||
),
|
||||
// void use(Foo&);
|
||||
(
|
||||
"?use@@YAXAEAUFoo@@@Z",
|
||||
"void __cdecl use(struct Foo & __ptr64)",
|
||||
),
|
||||
// namespace ns { int x; }
|
||||
("?x@ns@@3HA", "int ns::x"),
|
||||
// Global operator new(size_t) and sized operator delete(void*, size_t).
|
||||
(
|
||||
"??2@YAPEAX_K@Z",
|
||||
"void * __ptr64 __cdecl operator new(unsigned __int64)",
|
||||
),
|
||||
(
|
||||
"??3@YAXPEAX_K@Z",
|
||||
"void __cdecl operator delete(void * __ptr64,unsigned __int64)",
|
||||
),
|
||||
// void gs(std::basic_string<char, std::char_traits<char>, std::allocator<char>>&);
|
||||
(
|
||||
"?gs@@YAXAEAV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z",
|
||||
"void __cdecl gs(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > & __ptr64)",
|
||||
),
|
||||
// void h(std::array<int, 16>);
|
||||
(
|
||||
"?h@@YAXV?$array@H$0BA@@std@@@Z",
|
||||
"void __cdecl h(class std::array<int,16>)",
|
||||
),
|
||||
] {
|
||||
assert_eq!(
|
||||
demangle(decorated).as_deref(),
|
||||
Some(expected),
|
||||
"{decorated}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_clang_manglings_are_reported_rather_than_guessed() {
|
||||
// void (*keep[])(): function pointer types are outside the supported subset.
|
||||
assert_eq!(demangle("?keep@@3PAP6AXXZA"), None);
|
||||
// A compiler-generated cleanup funclet nested in another function's scope.
|
||||
assert_eq!(demangle("?dtor$2@?0??use@@YAXAEAUFoo@@@Z@4HA"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn manifests_show_undecorated_names_for_unclassified_cxx_imports() {
|
||||
use xenora_import_gen::{ImportRecord, Manifest, SymbolDb};
|
||||
let record = |symbol: &str| ImportRecord {
|
||||
module: "msvcp140.dll".to_owned(),
|
||||
symbol: symbol.to_owned(),
|
||||
ordinal: None,
|
||||
iat_rva: 0x2000,
|
||||
};
|
||||
let manifest = Manifest::build(
|
||||
&[
|
||||
record("?_Xlength_error@std@@YAXPEBD@Z"),
|
||||
record("?keep@@3PAP6AXXZA"),
|
||||
],
|
||||
&SymbolDb::builtin(),
|
||||
);
|
||||
let markdown = manifest.render_markdown();
|
||||
assert!(markdown.contains(
|
||||
"- `msvcp140.dll!?_Xlength_error@std@@YAXPEBD@Z` (`void __cdecl std::_Xlength_error(char const * __ptr64)`) —"
|
||||
));
|
||||
assert!(markdown.contains("- `msvcp140.dll!?keep@@3PAP6AXXZA` —"));
|
||||
}
|
||||
@@ -1,175 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
use xenora_import_gen::{Classification, Manifest, SymbolDb, generate, parse_csv};
|
||||
|
||||
#[test]
|
||||
fn test_builtin_db_classifies_crt_math() {
|
||||
let db = SymbolDb::builtin();
|
||||
let acos_cls = db.get("api-ms-win-crt-math-l1-1-0.dll", "acos");
|
||||
assert!(matches!(acos_cls, Some(Classification::CrtNative { .. })));
|
||||
|
||||
let sqrtf_cls = db.get("api-ms-win-crt-math-l1-1-0.dll", "sqrtf");
|
||||
assert!(matches!(sqrtf_cls, Some(Classification::StandardService)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_builtin_db_classifies_crt_string() {
|
||||
let db = SymbolDb::builtin();
|
||||
let strlen_cls = db.get("api-ms-win-crt-string-l1-1-0.dll", "strlen");
|
||||
assert!(matches!(strlen_cls, Some(Classification::StandardService)));
|
||||
|
||||
let strcat_s_cls = db.get("api-ms-win-crt-string-l1-1-0.dll", "strcat_s");
|
||||
assert!(matches!(
|
||||
strcat_s_cls,
|
||||
Some(Classification::CrtWrapper { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_builtin_db_case_insensitive() {
|
||||
let db = SymbolDb::builtin();
|
||||
let sym1 = db.get("API-MS-WIN-CRT-MATH-L1-1-0.DLL", "acos");
|
||||
let sym2 = db.get("api-ms-win-crt-math-l1-1-0.dll", "acos");
|
||||
assert_eq!(sym1, sym2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_csv_preserves_ordinals_and_identically_spelled_names() {
|
||||
let dir = std::env::temp_dir().join(format!("xenora-typed-imports-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let input = dir.join("imports.csv");
|
||||
std::fs::write(
|
||||
&input,
|
||||
"module,symbol_or_ordinal,iat_rva,import_kind\n\
|
||||
\"demo.dll\",\"Ordinal#42\",0x1000,ordinal\n\
|
||||
\"DEMO.dll\",\"Ordinal#42\",0x1004,ordinal\n\
|
||||
\"demo.dll\",\"Ordinal#42\",0x1008,name\n",
|
||||
)
|
||||
.unwrap();
|
||||
let records = parse_csv(input.to_str().unwrap()).unwrap();
|
||||
let db = SymbolDb::builtin();
|
||||
let manifest = Manifest::build(&records, &db);
|
||||
assert_eq!(manifest.emission_summary().get("no-binding"), Some(&2));
|
||||
assert_eq!(manifest.generatable().count(), 0);
|
||||
let output = dir.join("manifest.csv");
|
||||
manifest.write_csv(output.to_str().unwrap()).unwrap();
|
||||
let csv = std::fs::read_to_string(output).unwrap();
|
||||
assert!(csv.contains("0x00001000,manual,no-binding,ordinal"));
|
||||
assert!(csv.contains("0x00001008,manual,no-binding,name"));
|
||||
let files = generate(&manifest, &db);
|
||||
assert!(!files.crt_rs.contains("Ordinal#42"));
|
||||
assert!(!files.stubs_rs.contains("Ordinal#42"));
|
||||
assert!(
|
||||
files
|
||||
.manifest_md
|
||||
.contains("requires a documented export mapping")
|
||||
);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_manifest_and_codegen_pipeline() {
|
||||
let csv_content = r#""module","symbol_or_ordinal","iat_rva"
|
||||
"api-ms-win-crt-math-l1-1-0.dll","acos",0x1000
|
||||
"api-ms-win-crt-string-l1-1-0.dll","tolower",0x1008
|
||||
"API-MS-WIN-CRT-STRING-L1-1-0.DLL","tolower",0x1048
|
||||
"api-ms-win-core-processthreads-l1-1-0.dll","CreateThread",0x1010
|
||||
"custom.dll","UnknownCustomFunc",0x1018
|
||||
"kernel32.dll","QueryPerformanceCounter",0x1020
|
||||
"api-ms-win-core-profile-l1-1-0.dll","QueryPerformanceFrequency",0x1028
|
||||
"api-ms-win-core-processthreads-l1-1-0.dll","GetThreadId",0x1030
|
||||
"api-ms-win-core-handle-l1-1-0.dll","DuplicateHandle",0x1038
|
||||
"api-ms-win-core-sysinfo-l1-1-0.dll","GetTickCount64",0x1040
|
||||
"#;
|
||||
|
||||
let tmp_dir = std::env::temp_dir().join("xenora_test_pipeline");
|
||||
std::fs::create_dir_all(&tmp_dir).unwrap();
|
||||
let csv_file = tmp_dir.join("test_imports.csv");
|
||||
std::fs::write(&csv_file, csv_content).unwrap();
|
||||
|
||||
let records = parse_csv(csv_file.to_str().unwrap()).unwrap();
|
||||
assert_eq!(records.len(), 10);
|
||||
|
||||
let db = SymbolDb::builtin();
|
||||
let manifest = Manifest::build(&records, &db);
|
||||
let summary = manifest.summary();
|
||||
|
||||
assert_eq!(*summary.get("crt-native").unwrap_or(&0), 3);
|
||||
assert_eq!(*summary.get("win32-stub").unwrap_or(&0), 1);
|
||||
assert_eq!(*summary.get("manual").unwrap_or(&0), 1);
|
||||
|
||||
assert_eq!(summary.get("standard-service"), Some(&5));
|
||||
assert_eq!(manifest.generatable().count(), 4);
|
||||
|
||||
let emissions = manifest.emission_summary();
|
||||
assert_eq!(emissions.get("generated-adapter"), Some(&1));
|
||||
assert_eq!(emissions.get("generated-stub"), Some(&2));
|
||||
assert_eq!(emissions.get("runtime-service"), Some(&5));
|
||||
assert_eq!(emissions.get("no-binding"), Some(&1));
|
||||
let csv = tmp_dir.join("manifest.csv");
|
||||
manifest.write_csv(csv.to_str().unwrap()).unwrap();
|
||||
let csv = std::fs::read_to_string(csv).unwrap();
|
||||
assert!(csv.contains("\"acos\",0x00001000,crt-native,generated-stub"));
|
||||
|
||||
let files = generate(&manifest, &db);
|
||||
assert!(files.crt_rs.contains("register_generated_crt_services"));
|
||||
assert_eq!(files.crt_rs.matches("\"tolower\"").count(), 1);
|
||||
let acos = files.crt_rs.split_once("\"acos\"").unwrap().1;
|
||||
let acos = acos.split("registry.register_with_status").next().unwrap();
|
||||
assert!(acos.contains("ServiceStatus::Stub"));
|
||||
assert!(acos.contains("Err(ExitReason::IllegalInstruction(0xFE))"));
|
||||
assert!(files.tests_rs.contains("generated_test_acos"));
|
||||
assert!(
|
||||
files
|
||||
.tests_rs
|
||||
.contains("generated_crt::register_generated_crt_services")
|
||||
);
|
||||
assert!(files.tests_rs.contains("(service.handler)"));
|
||||
assert!(files.tests_rs.contains("generated_test_createthread"));
|
||||
assert!(files.stubs_rs.contains("CreateThread"));
|
||||
assert!(!files.stubs_rs.contains("QueryPerformance"));
|
||||
assert!(!files.stubs_rs.contains("GetThreadId"));
|
||||
assert!(!files.stubs_rs.contains("DuplicateHandle"));
|
||||
assert!(!files.stubs_rs.contains("GetTickCount64"));
|
||||
assert!(files.tests_rs.contains("generated_test_tolower"));
|
||||
|
||||
let out_dir = tmp_dir.join("out");
|
||||
files.write_all(out_dir.to_str().unwrap()).unwrap();
|
||||
assert!(out_dir.join("generated_crt.rs").exists());
|
||||
assert!(out_dir.join("generated_stubs.rs").exists());
|
||||
assert!(out_dir.join("generated_tests.rs").exists());
|
||||
assert!(out_dir.join("generated_manifest.md").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_catalog_describes_windows_wide_string_signatures() {
|
||||
use xenora_import_gen::{AbiType, MetadataCatalog};
|
||||
|
||||
let catalog = MetadataCatalog::builtin();
|
||||
let wide = AbiType::StringWide;
|
||||
for (symbol, return_type, parameters) in [
|
||||
("wcslen", AbiType::U64, vec![wide.clone()]),
|
||||
("wcsnlen", AbiType::U64, vec![wide.clone(), AbiType::U64]),
|
||||
("wcscmp", AbiType::I32, vec![wide.clone(), wide.clone()]),
|
||||
(
|
||||
"wcsncmp",
|
||||
AbiType::I32,
|
||||
vec![wide.clone(), wide, AbiType::U64],
|
||||
),
|
||||
] {
|
||||
let signature = catalog.lookup("ucrtbase.dll", symbol).unwrap();
|
||||
assert_eq!(signature.return_type, return_type);
|
||||
assert_eq!(
|
||||
signature
|
||||
.params
|
||||
.iter()
|
||||
.map(|p| p.abi_type.clone())
|
||||
.collect::<Vec<_>>(),
|
||||
parameters
|
||||
);
|
||||
}
|
||||
let copy = catalog.lookup("ucrtbase.dll", "memcpy").unwrap();
|
||||
let move_ = catalog.lookup("ucrtbase.dll", "memmove").unwrap();
|
||||
assert_eq!(move_.params, copy.params);
|
||||
assert_eq!(move_.return_type, copy.return_type);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -17,6 +17,7 @@ VARIANTS = (
|
||||
("V_ADD_NC_U32", "ENC_VOP3"),
|
||||
("S_ENDPGM", "ENC_SOPP"),
|
||||
("S_MOV_B32", "ENC_SOP1"),
|
||||
("S_CMP_EQ_U32", "ENC_SOPC"),
|
||||
("S_CBRANCH_SCC0", "ENC_SOPP"),
|
||||
("S_CBRANCH_EXECZ", "ENC_SOPP"),
|
||||
("S_CBRANCH_VCCZ", "ENC_SOPP"),
|
||||
@@ -29,18 +30,6 @@ VARIANTS = (
|
||||
("V_XOR_B32", "ENC_VOP2"),
|
||||
("V_ADD_F32", "ENC_VOP2"),
|
||||
("V_MUL_F32", "ENC_VOP2"),
|
||||
("V_CMP_LT_I32", "ENC_VOPC"),
|
||||
("V_CMP_EQ_I32", "ENC_VOPC"),
|
||||
("V_CMP_LE_I32", "ENC_VOPC"),
|
||||
("V_CMP_GT_I32", "ENC_VOPC"),
|
||||
("V_CMP_NE_I32", "ENC_VOPC"),
|
||||
("V_CMP_GE_I32", "ENC_VOPC"),
|
||||
("V_CMP_LT_U32", "ENC_VOPC"),
|
||||
("V_CMP_EQ_U32", "ENC_VOPC"),
|
||||
("V_CMP_LE_U32", "ENC_VOPC"),
|
||||
("V_CMP_GT_U32", "ENC_VOPC"),
|
||||
("V_CMP_NE_U32", "ENC_VOPC"),
|
||||
("V_CMP_GE_U32", "ENC_VOPC"),
|
||||
("EXP", "ENC_EXP"),
|
||||
("V_INTERP_P1_F32", "ENC_VINTRP"),
|
||||
("V_INTERP_P2_F32", "ENC_VINTRP"),
|
||||
|
||||
@@ -1,437 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate the complete gfx1030 instruction metadata table.
|
||||
|
||||
Two stages keep regeneration offline and checkable without the 11 MB AMD XML:
|
||||
|
||||
snapshot AMD RDNA 2 XML -> crates/isa/data/rdna2.jsonl (normalised, sorted)
|
||||
rust crates/isa/data/rdna2.jsonl -> crates/isa/src/rdna2_meta.rs
|
||||
|
||||
`--check` regenerates in memory and fails when a committed file differs.
|
||||
Only the Python standard library is used. See docs/research/rdna2.md.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from xml.etree import ElementTree
|
||||
|
||||
SOURCE_SHA256 = "d671ecbc36543674ab59e9b2feffd56718fd2137e7ad913c314f2e2508b9f4f7"
|
||||
ARCHITECTURE = "AMD RDNA 2"
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
SNAPSHOT = ROOT / "crates/isa/data/rdna2.jsonl"
|
||||
RUST = ROOT / "crates/isa/src/rdna2_meta.rs"
|
||||
SCHEMA = 1
|
||||
|
||||
# Encodings whose default condition defines an instruction's base form. The
|
||||
# remaining XML encodings are literal, SDWA, DPP or NSA extensions of these.
|
||||
BASE_ENCODINGS = {
|
||||
"ENC_SOP1": "Sop1",
|
||||
"ENC_SOP2": "Sop2",
|
||||
"ENC_SOPC": "Sopc",
|
||||
"ENC_SOPK": "Sopk",
|
||||
"ENC_SOPP": "Sopp",
|
||||
"ENC_SMEM": "Smem",
|
||||
"ENC_VOP1": "Vop1",
|
||||
"ENC_VOP2": "Vop2",
|
||||
"ENC_VOPC": "Vopc",
|
||||
"ENC_VOP3": "Vop3",
|
||||
"VOP3_SDST_ENC": "Vop3Sdst",
|
||||
"ENC_VOP3P": "Vop3p",
|
||||
"ENC_VINTRP": "Vintrp",
|
||||
"ENC_DS": "Ds",
|
||||
"ENC_MUBUF": "Mubuf",
|
||||
"ENC_MTBUF": "Mtbuf",
|
||||
"ENC_MIMG": "Mimg",
|
||||
"ENC_EXP": "Exp",
|
||||
"ENC_FLAT": "Flat",
|
||||
"ENC_FLAT_GLBL": "Global",
|
||||
"ENC_FLAT_SCRATCH": "Scratch",
|
||||
}
|
||||
|
||||
# Extension encoding -> (base encoding, extension kind). The XML names the
|
||||
# variant and its operands but gives no expression for when it applies; the
|
||||
# decoder implements those rules by hand (docs/research/rdna2.md).
|
||||
EXTENSIONS = {
|
||||
"SOP1_INST_LITERAL": ("ENC_SOP1", "literal"),
|
||||
"SOP2_INST_LITERAL": ("ENC_SOP2", "literal"),
|
||||
"SOPC_INST_LITERAL": ("ENC_SOPC", "literal"),
|
||||
"SOPK_INST_LITERAL": ("ENC_SOPK", "literal"),
|
||||
"VOP1_INST_LITERAL": ("ENC_VOP1", "literal"),
|
||||
"VOP2_INST_LITERAL": ("ENC_VOP2", "literal"),
|
||||
"VOPC_INST_LITERAL": ("ENC_VOPC", "literal"),
|
||||
"VOP3_INST_LITERAL": ("ENC_VOP3", "literal"),
|
||||
"VOP3_SDST_ENC_INST_LITERAL": ("VOP3_SDST_ENC", "literal"),
|
||||
"VOP3P_INST_LITERAL": ("ENC_VOP3P", "literal"),
|
||||
"VOP1_VOP_SDWA": ("ENC_VOP1", "sdwa"),
|
||||
"VOP2_VOP_SDWA": ("ENC_VOP2", "sdwa"),
|
||||
"VOP2_VOP_SDWA_SDST_ENC": ("ENC_VOP2", "sdwa"),
|
||||
"VOPC_VOP_SDWA_SDST_ENC": ("ENC_VOPC", "sdwa"),
|
||||
"VOP1_VOP_DPP8": ("ENC_VOP1", "dpp8"),
|
||||
"VOP2_VOP_DPP8": ("ENC_VOP2", "dpp8"),
|
||||
"VOP1_VOP_DPP16": ("ENC_VOP1", "dpp16"),
|
||||
"VOP2_VOP_DPP16": ("ENC_VOP2", "dpp16"),
|
||||
"MIMG_NSA1": ("ENC_MIMG", "nsa"),
|
||||
"MIMG_NSA2": ("ENC_MIMG", "nsa"),
|
||||
"MIMG_NSA3": ("ENC_MIMG", "nsa"),
|
||||
}
|
||||
|
||||
FLAGS = ("IsBranch", "IsConditionalBranch", "IsIndirectBranch", "IsProgramTerminator", "IsImmediatelyExecuted")
|
||||
|
||||
|
||||
def fail(message):
|
||||
raise SystemExit(f"generate_rdna2_meta: {message}")
|
||||
|
||||
|
||||
def text(element, path):
|
||||
value = element.findtext(path)
|
||||
if value is None:
|
||||
fail(f"missing <{path}>")
|
||||
return value.strip()
|
||||
|
||||
|
||||
def boolean(value):
|
||||
if value not in ("TRUE", "FALSE", "true", "false"):
|
||||
fail(f"unexpected boolean {value!r}")
|
||||
return value.lower() == "true"
|
||||
|
||||
|
||||
def snapshot_from_xml(data):
|
||||
if hashlib.sha256(data).hexdigest() != SOURCE_SHA256:
|
||||
fail("RDNA 2 XML does not match the approved input SHA-256")
|
||||
root = ElementTree.fromstring(data)
|
||||
document = root.find("Document")
|
||||
isa = root.find("ISA")
|
||||
if text(isa, "Architecture/ArchitectureName") != ARCHITECTURE:
|
||||
fail("XML is not the RDNA 2 architecture")
|
||||
records = [{
|
||||
"kind": "source",
|
||||
"schema": SCHEMA,
|
||||
"architecture": ARCHITECTURE,
|
||||
"sha256": SOURCE_SHA256,
|
||||
"release": text(document, "ReleaseDate"),
|
||||
"xml_schema": text(document, "SchemaVersion"),
|
||||
"license": text(document, "License"),
|
||||
"copyright": text(document, "Copyright"),
|
||||
}]
|
||||
|
||||
known = set(BASE_ENCODINGS) | set(EXTENSIONS)
|
||||
encodings = {}
|
||||
for encoding in isa.findall("Encodings/Encoding"):
|
||||
name = text(encoding, "EncodingName")
|
||||
if name not in known:
|
||||
fail(f"unclassified encoding {name}; add it to BASE_ENCODINGS or EXTENSIONS")
|
||||
bits = int(text(encoding, "BitCount"))
|
||||
mask = int(text(encoding, "EncodingIdentifierMask"), 2)
|
||||
identifiers = sorted(int(item.text, 2) for item in encoding.findall("EncodingIdentifiers/EncodingIdentifier"))
|
||||
if mask >> 32 or any(identifier >> 32 for identifier in identifiers):
|
||||
fail(f"{name} identifies instructions beyond the first dword")
|
||||
fields = []
|
||||
for field in encoding.findall("MicrocodeFormat/BitMap/Field"):
|
||||
ranges = sorted(field.findall("BitLayout/Range"), key=lambda item: int(item.attrib.get("Order", 0)))
|
||||
fields.append([
|
||||
text(field, "FieldName"),
|
||||
[[int(text(item, "BitOffset")), int(text(item, "BitCount"))] for item in ranges],
|
||||
])
|
||||
fields.sort(key=lambda item: (item[1][0][0], item[0]))
|
||||
encodings[name] = {"mask": mask, "identifiers": set(identifiers)}
|
||||
records.append({
|
||||
"kind": "encoding",
|
||||
"name": name,
|
||||
"bits": bits,
|
||||
"identifier_mask": mask,
|
||||
"identifiers": identifiers,
|
||||
"conditions": sorted(text(item, "ConditionName") for item in encoding.findall("EncodingConditions/EncodingCondition")),
|
||||
"fields": fields,
|
||||
})
|
||||
missing = known - set(encodings)
|
||||
if missing:
|
||||
fail(f"encodings absent from the XML: {sorted(missing)}")
|
||||
|
||||
for operand_type in isa.findall("OperandTypes/OperandType"):
|
||||
values = sorted(
|
||||
[text(value, "Name"), int(text(value, "Value"))]
|
||||
for value in operand_type.findall("OperandPredefinedValues/PredefinedValue")
|
||||
)
|
||||
records.append({
|
||||
"kind": "operand_type",
|
||||
"name": text(operand_type, "OperandTypeName"),
|
||||
"partitioned": boolean(operand_type.attrib.get("IsPartitioned", "false")),
|
||||
"values": values,
|
||||
})
|
||||
|
||||
for data_format in isa.findall("DataFormats/DataFormat"):
|
||||
records.append({
|
||||
"kind": "data_format",
|
||||
"name": text(data_format, "DataFormatName"),
|
||||
"data_type": text(data_format, "DataType"),
|
||||
"bits": int(text(data_format, "BitCount")),
|
||||
"components": int(text(data_format, "ComponentCount")),
|
||||
})
|
||||
|
||||
seen = set()
|
||||
for instruction in isa.findall("Instructions/Instruction"):
|
||||
name = text(instruction, "InstructionName")
|
||||
flags = {flag: boolean(text(instruction, f"InstructionFlags/{flag}")) for flag in FLAGS}
|
||||
group = instruction.find("FunctionalGroup")
|
||||
for variant in instruction.findall("InstructionEncodings/InstructionEncoding"):
|
||||
encoding_name = text(variant, "EncodingName")
|
||||
condition = text(variant, "EncodingCondition")
|
||||
opcode = int(text(variant, "Opcode"))
|
||||
key = (name, encoding_name, condition)
|
||||
if key in seen:
|
||||
fail(f"duplicate variant {key}")
|
||||
seen.add(key)
|
||||
operands = []
|
||||
for operand in sorted(variant.findall("Operands/Operand"), key=lambda item: int(item.attrib["Order"])):
|
||||
operands.append([
|
||||
operand.findtext("FieldName") or "",
|
||||
operand.findtext("DataFormatName") or "",
|
||||
operand.findtext("OperandType") or "",
|
||||
int(operand.findtext("OperandSize") or 0),
|
||||
boolean(operand.attrib["Input"]),
|
||||
boolean(operand.attrib["Output"]),
|
||||
boolean(operand.attrib["IsImplicit"]),
|
||||
boolean(operand.attrib.get("IsBinaryMicrocodeRequired", "true")),
|
||||
])
|
||||
record = {
|
||||
"kind": "variant",
|
||||
"instruction": name,
|
||||
"encoding": encoding_name,
|
||||
"condition": condition,
|
||||
"opcode": opcode,
|
||||
}
|
||||
# Extension variants keep only what classifies them; their
|
||||
# operands repeat the base form with a literal, SDWA, DPP or NSA word.
|
||||
if encoding_name in BASE_ENCODINGS or condition == "default":
|
||||
record.update({
|
||||
"flags": sorted(flag for flag, value in flags.items() if value),
|
||||
"group": text(group, "Name"),
|
||||
"subgroups": sorted(item.text.strip() for item in group.findall("FunctionalSubgroups/Subgroup")),
|
||||
"operands": operands,
|
||||
})
|
||||
records.append(record)
|
||||
|
||||
order = {"source": 0, "encoding": 1, "operand_type": 2, "data_format": 3, "variant": 4}
|
||||
records.sort(key=lambda record: (
|
||||
order[record["kind"]],
|
||||
record.get("name", ""),
|
||||
record.get("encoding", ""),
|
||||
record.get("instruction", ""),
|
||||
record.get("condition", ""),
|
||||
))
|
||||
return "".join(json.dumps(record, sort_keys=True, separators=(",", ":")) + "\n" for record in records)
|
||||
|
||||
|
||||
def place(value, ranges):
|
||||
"""Places `value` into a field layout; returns (mask, bits) within the first two dwords."""
|
||||
mask = bits = 0
|
||||
for offset, count in ranges:
|
||||
if offset + count > 64:
|
||||
fail("opcode field extends beyond the second dword")
|
||||
low = (1 << count) - 1
|
||||
bits |= (value & low) << offset
|
||||
mask |= low << offset
|
||||
value >>= count
|
||||
if value:
|
||||
fail("opcode does not fit its field")
|
||||
return mask, bits
|
||||
|
||||
|
||||
def forms_from_snapshot(snapshot):
|
||||
records = [json.loads(line) for line in snapshot.splitlines()]
|
||||
source = records[0]
|
||||
if source.get("kind") != "source" or source.get("schema") != SCHEMA or source.get("sha256") != SOURCE_SHA256:
|
||||
fail("snapshot header does not match this generator")
|
||||
encodings = {record["name"]: record for record in records if record["kind"] == "encoding"}
|
||||
variants = [record for record in records if record["kind"] == "variant"]
|
||||
|
||||
extensions = {}
|
||||
for variant in variants:
|
||||
if variant["encoding"] in EXTENSIONS:
|
||||
base, kind = EXTENSIONS[variant["encoding"]]
|
||||
entry = extensions.setdefault((variant["instruction"], base), set())
|
||||
if kind == "literal" and variant["condition"] == "default":
|
||||
entry.add("always_literal")
|
||||
entry.add(kind)
|
||||
|
||||
based = {(variant["instruction"], variant["encoding"]) for variant in variants if variant["encoding"] in BASE_ENCODINGS}
|
||||
forms = []
|
||||
for variant in variants:
|
||||
encoding_name = variant["encoding"]
|
||||
identity = encoding_name
|
||||
if encoding_name in EXTENSIONS:
|
||||
# A few instructions exist only with a literal (S_SETREG_IMM32_B32,
|
||||
# V_FMAMK_F32, ...): the XML lists them under the literal encoding's
|
||||
# default condition and gives them no base variant.
|
||||
base, kind = EXTENSIONS[encoding_name]
|
||||
if kind != "literal" or variant["condition"] != "default" or (variant["instruction"], base) in based:
|
||||
continue
|
||||
encoding_name = base
|
||||
elif encoding_name not in BASE_ENCODINGS:
|
||||
continue
|
||||
# Three VOP1/VOP3 relative moves name the excluded extensions instead of "default".
|
||||
if variant["condition"] != "default" and not variant["condition"].startswith("Nothas_"):
|
||||
fail(f"{variant['instruction']} has non-default base condition {variant['condition']}")
|
||||
encoding = encodings[encoding_name]
|
||||
id_encoding = encodings[identity]
|
||||
fields = dict((name, ranges) for name, ranges in encoding["fields"])
|
||||
prefix_mask, _ = place(0, fields["ENCODING"])
|
||||
prefixes = {identifier & prefix_mask for identifier in id_encoding["identifiers"]}
|
||||
if len(prefixes) != 1:
|
||||
fail(f"{encoding_name} has an ambiguous encoding prefix")
|
||||
prefix = prefixes.pop()
|
||||
id_mask = id_encoding["identifier_mask"] & 0xFFFFFFFF
|
||||
opcode = variant["opcode"]
|
||||
if "OP" in fields:
|
||||
op_mask, op_bits = place(opcode, fields["OP"])
|
||||
elif opcode == 0:
|
||||
op_mask = op_bits = 0
|
||||
else:
|
||||
fail(f"{encoding_name} has no OP field for opcode {opcode}")
|
||||
# The identifier mask can add selector bits beyond ENCODING and OP,
|
||||
# such as the FLAT segment field. Take them from the listed identifier.
|
||||
# MTBUF keeps one opcode bit in the second dword, which the
|
||||
# first-dword identifiers cannot express; carry it separately.
|
||||
low = 0xFFFFFFFF
|
||||
candidates = sorted({
|
||||
identifier & 0xFFFFFFFF for identifier in id_encoding["identifiers"]
|
||||
if identifier & (prefix_mask | op_mask) & low == (prefix | op_bits) & low
|
||||
})
|
||||
if len(candidates) != 1:
|
||||
fail(f"{variant['instruction']} matches {len(candidates)} {encoding_name} identifiers")
|
||||
forms.append({
|
||||
"name": variant["instruction"],
|
||||
"encoding": BASE_ENCODINGS[encoding_name],
|
||||
"opcode": opcode,
|
||||
# Opcode bits outside the identifier mask (MIMG bit 0, MTBUF bit 53)
|
||||
# still select the instruction.
|
||||
"mask": id_mask | op_mask,
|
||||
"bits": (candidates[0] & id_mask) | op_bits,
|
||||
"bytes": encoding["bits"] // 8,
|
||||
"flags": variant["flags"],
|
||||
"group": variant["group"],
|
||||
"extensions": sorted(extensions.get((variant["instruction"], encoding_name), ())),
|
||||
"operands": variant["operands"],
|
||||
})
|
||||
|
||||
by_pattern = {}
|
||||
for form in forms:
|
||||
if form["bits"] & ~form["mask"]:
|
||||
fail(f"{form['name']} has identifying bits outside its mask")
|
||||
key = (form["mask"], form["bits"])
|
||||
if key in by_pattern:
|
||||
fail(f"{form['name']} and {by_pattern[key]['name']} share an encoding")
|
||||
by_pattern[key] = form
|
||||
for left in forms:
|
||||
for right in forms:
|
||||
if left is right or left["mask"] == right["mask"]:
|
||||
continue
|
||||
common = left["mask"] & right["mask"]
|
||||
if (left["bits"] ^ right["bits"]) & common == 0:
|
||||
fail(f"{left['name']} ({left['encoding']}) overlaps {right['name']} ({right['encoding']})")
|
||||
forms.sort(key=lambda form: (form["encoding"], form["opcode"]))
|
||||
return source, encodings, forms
|
||||
|
||||
|
||||
def rust_from_snapshot(snapshot):
|
||||
source, encodings, forms = forms_from_snapshot(snapshot)
|
||||
out = []
|
||||
emit = out.append
|
||||
emit("// Generated by crates/isa/generate_rdna2_meta.py from crates/isa/data/rdna2.jsonl. Do not edit.")
|
||||
emit(f"// Source: AMD RDNA 2 XML, {source['release']}, schema {source['xml_schema']}, SHA-256 {source['sha256']}.")
|
||||
emit(f"// {source['copyright']}")
|
||||
emit("// SPDX-License-Identifier: MIT")
|
||||
emit("")
|
||||
emit("use super::meta::{EncodingFamily, Extensions, FieldLayout, Form, FormFlags, OperandInfo};")
|
||||
emit("")
|
||||
emit(f'/// SHA-256 of the AMD XML the table was generated from.\npub const SOURCE_SHA256: &str = "{source["sha256"]}";')
|
||||
emit("")
|
||||
|
||||
operand_sets = {}
|
||||
for form in forms:
|
||||
operand_sets.setdefault(json.dumps(form["operands"]), len(operand_sets))
|
||||
emit("static OPERANDS: [&[OperandInfo]; %d] = [" % len(operand_sets))
|
||||
for operands_json in operand_sets:
|
||||
operands = json.loads(operands_json)
|
||||
items = ", ".join(
|
||||
"OperandInfo { field: %s, format: %s, kind: %s, bits: %d, input: %s, output: %s, implicit: %s, encoded: %s }"
|
||||
% (json.dumps(field), json.dumps(data_format), json.dumps(kind), size,
|
||||
str(i).lower(), str(o).lower(), str(implicit).lower(), str(encoded).lower())
|
||||
for field, data_format, kind, size, i, o, implicit, encoded in operands
|
||||
)
|
||||
emit(f" &[{items}],")
|
||||
emit("];")
|
||||
emit("")
|
||||
|
||||
families = sorted({form["encoding"] for form in forms})
|
||||
emit("/// Field layouts of each base encoding, as (bit offset, bit count) pieces from least significant.")
|
||||
emit("pub static FIELDS: [(EncodingFamily, &[FieldLayout]); %d] = [" % len(families))
|
||||
reverse = {value: key for key, value in BASE_ENCODINGS.items()}
|
||||
for family in families:
|
||||
fields = encodings[reverse[family]]["fields"]
|
||||
items = ", ".join(
|
||||
"FieldLayout { name: %s, pieces: &[%s] }" % (json.dumps(name), ", ".join(f"({o}, {c})" for o, c in ranges))
|
||||
for name, ranges in fields
|
||||
)
|
||||
emit(f" (EncodingFamily::{family}, &[{items}]),")
|
||||
emit("];")
|
||||
emit("")
|
||||
|
||||
flag_bits = {
|
||||
"IsBranch": 1,
|
||||
"IsConditionalBranch": 2,
|
||||
"IsIndirectBranch": 4,
|
||||
"IsProgramTerminator": 8,
|
||||
"IsImmediatelyExecuted": 16,
|
||||
}
|
||||
extension_bits = {"literal": 1, "always_literal": 2, "sdwa": 4, "dpp8": 8, "dpp16": 16, "nsa": 32}
|
||||
emit("/// Every gfx1030 base instruction form in the AMD XML, sorted by encoding family and opcode.")
|
||||
emit("pub static FORMS: [Form; %d] = [" % len(forms))
|
||||
for form in forms:
|
||||
flags = sum(flag_bits[flag] for flag in form["flags"])
|
||||
extensions = sum(extension_bits[item] for item in form["extensions"])
|
||||
emit(
|
||||
" Form { name: %s, family: EncodingFamily::%s, opcode: %d, mask: 0x%016x, bits: 0x%016x, bytes: %d, "
|
||||
"flags: FormFlags(0x%02x), extensions: Extensions(0x%02x), group: %s, operands: OPERANDS[%d] },"
|
||||
% (json.dumps(form["name"]), form["encoding"], form["opcode"], form["mask"], form["bits"], form["bytes"],
|
||||
flags, extensions, json.dumps(form["group"]), operand_sets[json.dumps(form["operands"])])
|
||||
)
|
||||
emit("];")
|
||||
return "\n".join(out) + "\n"
|
||||
|
||||
|
||||
def compare(path, expected):
|
||||
actual = path.read_text() if path.exists() else ""
|
||||
if actual != expected:
|
||||
print(f"{path.relative_to(ROOT)} is out of date; rerun crates/isa/generate_rdna2_meta.py", file=sys.stderr)
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument("--xml", type=Path, help="approved amdgpu_isa_rdna2.xml; regenerates the snapshot too")
|
||||
parser.add_argument("--check", action="store_true", help="fail when committed outputs differ")
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.xml:
|
||||
snapshot = snapshot_from_xml(args.xml.read_bytes())
|
||||
elif SNAPSHOT.exists():
|
||||
snapshot = SNAPSHOT.read_text()
|
||||
else:
|
||||
fail("no snapshot; pass --xml")
|
||||
rust = rust_from_snapshot(snapshot)
|
||||
if args.check:
|
||||
ok = compare(RUST, rust)
|
||||
if args.xml:
|
||||
ok = compare(SNAPSHOT, snapshot) and ok
|
||||
raise SystemExit(0 if ok else 1)
|
||||
SNAPSHOT.parent.mkdir(parents=True, exist_ok=True)
|
||||
SNAPSHOT.write_text(snapshot)
|
||||
RUST.write_text(rust)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,56 +0,0 @@
|
||||
# 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 these files.
|
||||
|
||||
schema = 1
|
||||
architecture = "gfx1030"
|
||||
# Must equal the "sha256" of the source line in crates/isa/data/rdna2.jsonl.
|
||||
source_sha256 = "d671ecbc36543674ab59e9b2feffd56718fd2137e7ad913c314f2e2508b9f4f7"
|
||||
# Family files, in this order (forms keep the order they are listed in; each
|
||||
# file holds the operand rules and forms of one encoding family, named after it).
|
||||
include = [
|
||||
"rdna2/sop2.toml",
|
||||
"rdna2/sopc.toml",
|
||||
"rdna2/sopk.toml",
|
||||
"rdna2/sop1.toml",
|
||||
"rdna2/vop1.toml",
|
||||
"rdna2/vop2.toml",
|
||||
"rdna2/vopc.toml",
|
||||
"rdna2/vop3.toml",
|
||||
"rdna2/sopp.toml",
|
||||
]
|
||||
|
||||
# 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"
|
||||
|
||||
# Form field meanings (every family file):
|
||||
# name XML instruction name (stable identity)
|
||||
# family encoding family; must match the XML base encoding
|
||||
# opcode XML opcode; must match
|
||||
# variant Rust enum variant of the typed op
|
||||
# operation primitive (closed vocabulary in generate_semantics.py OPERATIONS)
|
||||
# signedness unsigned | signed | bitwise (bitwise iff a logical operation)
|
||||
# carry_in none | scc | vcc (implicit scalar or per-lane condition or carry)
|
||||
# width operand and result width in bits
|
||||
# scc unchanged | carry_out | borrow | signed_overflow | nonzero | relation | selected_src0
|
||||
# vcc, exec unchanged (stated, not implied) | lane_mask (Wave32 VOPC compare or VOP2 carry output)
|
||||
# VOP3A compare variant rows derive sdst_lane_mask from their operand rule.
|
||||
# wave any | wave32 (wave32 for VOPC compares, VOP1 integer forms and VCC-reading VOP2 forms)
|
||||
# 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
|
||||
@@ -1,270 +0,0 @@
|
||||
# SOP1 forms of the gfx1030 semantic registry; included by ../rdna2.toml.
|
||||
# Data only; see the root file for the field meanings.
|
||||
|
||||
# ---- SOP1 32-bit unary integer forms (#215) ----
|
||||
# NOT, BCNT0, BCNT1 and ABS set SCC = (D != 0); the others leave SCC unchanged.
|
||||
# Searches that find nothing return -1 (guide 12.3).
|
||||
|
||||
[operand_rules.sop1_sgpr]
|
||||
family = "SOP1"
|
||||
dst = { field = "SDST", class = "sgpr", min = 0, max = 105 }
|
||||
src = [{ field = "SSRC0", class = "scalar_source" }]
|
||||
max_literals = 1
|
||||
unsupported = [
|
||||
"dst_vcc", "dst_exec", "dst_ttmp", "dst_m0", "dst_null",
|
||||
"src_vcc", "src_exec", "src_m0", "src_ttmp", "src_float_inline", "src_special",
|
||||
]
|
||||
|
||||
# Guide sections 5.3 and 12.3. VCC and EXEC halves can be explicit
|
||||
# destinations; the move has no implicit mask or SCC effects.
|
||||
[operand_rules.sop1_move]
|
||||
family = "SOP1"
|
||||
dst = { field = "SDST", class = "sgpr_or_vcc_exec" }
|
||||
src = [{ field = "SSRC0", class = "scalar_source" }]
|
||||
max_literals = 1
|
||||
unsupported = [
|
||||
"dst_ttmp", "dst_m0", "dst_null",
|
||||
"src_vcc", "src_exec", "src_m0", "src_ttmp", "src_float_inline", "src_special",
|
||||
]
|
||||
|
||||
[[form]]
|
||||
name = "S_MOV_B32"
|
||||
family = "SOP1"
|
||||
opcode = 3
|
||||
variant = "MovB32"
|
||||
operation = "mov"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop1_move"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.3", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_NOT_B32"
|
||||
family = "SOP1"
|
||||
opcode = 7
|
||||
variant = "NotB32"
|
||||
operation = "not"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop1_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.3", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_BREV_B32"
|
||||
family = "SOP1"
|
||||
opcode = 11
|
||||
variant = "BrevB32"
|
||||
operation = "brev"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop1_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.3", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_BCNT0_I32_B32"
|
||||
family = "SOP1"
|
||||
opcode = 13
|
||||
variant = "Bcnt0I32B32"
|
||||
operation = "bcnt0"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop1_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.3", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_BCNT1_I32_B32"
|
||||
family = "SOP1"
|
||||
opcode = 15
|
||||
variant = "Bcnt1I32B32"
|
||||
operation = "bcnt1"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop1_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.3", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_FF0_I32_B32"
|
||||
family = "SOP1"
|
||||
opcode = 17
|
||||
variant = "Ff0I32B32"
|
||||
operation = "ff0"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop1_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.3", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_FF1_I32_B32"
|
||||
family = "SOP1"
|
||||
opcode = 19
|
||||
variant = "Ff1I32B32"
|
||||
operation = "ff1"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop1_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.3", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_FLBIT_I32_B32"
|
||||
family = "SOP1"
|
||||
opcode = 21
|
||||
variant = "FlbitI32B32"
|
||||
operation = "flbit"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop1_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.3", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_FLBIT_I32"
|
||||
family = "SOP1"
|
||||
opcode = 23
|
||||
variant = "FlbitI32"
|
||||
operation = "flbit"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop1_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.3", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_SEXT_I32_I8"
|
||||
family = "SOP1"
|
||||
opcode = 25
|
||||
variant = "SextI32I8"
|
||||
operation = "sext"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
source_bits = 8
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop1_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.3", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_SEXT_I32_I16"
|
||||
family = "SOP1"
|
||||
opcode = 26
|
||||
variant = "SextI32I16"
|
||||
operation = "sext"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
source_bits = 16
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop1_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.3", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_ABS_I32"
|
||||
family = "SOP1"
|
||||
opcode = 52
|
||||
variant = "AbsI32"
|
||||
operation = "abs"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop1_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.3", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
@@ -1,647 +0,0 @@
|
||||
# SOP2 forms of the gfx1030 semantic registry; included by ../rdna2.toml.
|
||||
# Data only; see the root file for the field meanings.
|
||||
|
||||
# ---- SOP2 32-bit integer and logical forms (migrated from #229/#230) ----
|
||||
|
||||
# Operand rules shared by a family. A rule names its destination and source
|
||||
# classes; the decoder implements each rule once (rules are not per opcode).
|
||||
[operand_rules.sop2_sgpr]
|
||||
family = "SOP2"
|
||||
dst = { field = "SDST", class = "sgpr", min = 0, max = 105 }
|
||||
src = [
|
||||
{ field = "SSRC0", class = "scalar_source" },
|
||||
{ field = "SSRC1", class = "scalar_source" },
|
||||
]
|
||||
# scalar_source = normal SGPR s0-s105, inline integer -16..64, or a literal word.
|
||||
max_literals = 1
|
||||
# Encodings this rule rejects, so they stay unsupported rather than guessed.
|
||||
unsupported = [
|
||||
"dst_vcc", "dst_exec", "dst_ttmp", "dst_m0", "dst_null",
|
||||
"src_vcc", "src_exec", "src_m0", "src_ttmp", "src_float_inline",
|
||||
"src_special", "two_literals",
|
||||
]
|
||||
|
||||
|
||||
[[form]]
|
||||
name = "S_ADD_U32"
|
||||
family = "SOP2"
|
||||
opcode = 0
|
||||
variant = "AddU32"
|
||||
operation = "add"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "carry_out"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 101 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_SUB_U32"
|
||||
family = "SOP2"
|
||||
opcode = 1
|
||||
variant = "SubU32"
|
||||
operation = "sub"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "borrow"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 101 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_ADD_I32"
|
||||
family = "SOP2"
|
||||
opcode = 2
|
||||
variant = "AddI32"
|
||||
operation = "add"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "signed_overflow"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 101 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_SUB_I32"
|
||||
family = "SOP2"
|
||||
opcode = 3
|
||||
variant = "SubI32"
|
||||
operation = "sub"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "signed_overflow"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 101 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_ADDC_U32"
|
||||
family = "SOP2"
|
||||
opcode = 4
|
||||
variant = "AddcU32"
|
||||
operation = "add"
|
||||
signedness = "unsigned"
|
||||
carry_in = "scc"
|
||||
width = 32
|
||||
scc = "carry_out"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 102 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_SUBB_U32"
|
||||
family = "SOP2"
|
||||
opcode = 5
|
||||
variant = "SubbU32"
|
||||
operation = "sub"
|
||||
signedness = "unsigned"
|
||||
carry_in = "scc"
|
||||
width = 32
|
||||
scc = "borrow"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 102 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_AND_B32"
|
||||
family = "SOP2"
|
||||
opcode = 14
|
||||
variant = "AndB32"
|
||||
operation = "and"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [{ document = "guide", section = "12.1", page = 102 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_OR_B32"
|
||||
family = "SOP2"
|
||||
opcode = 16
|
||||
variant = "OrB32"
|
||||
operation = "or"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [{ document = "guide", section = "12.1", page = 102 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_XOR_B32"
|
||||
family = "SOP2"
|
||||
opcode = 18
|
||||
variant = "XorB32"
|
||||
operation = "xor"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [{ document = "guide", section = "12.1", page = 102 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
# ---- Stage C: further SOP2 logical and shift forms (#215) ----
|
||||
# Shifts use the low shift_count_bits of S1 as the count (guide 12.1 pseudocode).
|
||||
|
||||
[[form]]
|
||||
name = "S_ANDN2_B32"
|
||||
family = "SOP2"
|
||||
opcode = 20
|
||||
variant = "Andn2B32"
|
||||
operation = "andn2"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [{ document = "guide", section = "12.1", page = 103 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_ORN2_B32"
|
||||
family = "SOP2"
|
||||
opcode = 22
|
||||
variant = "Orn2B32"
|
||||
operation = "orn2"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [{ document = "guide", section = "12.1", page = 103 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_NAND_B32"
|
||||
family = "SOP2"
|
||||
opcode = 24
|
||||
variant = "NandB32"
|
||||
operation = "nand"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [{ document = "guide", section = "12.1", page = 104 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_NOR_B32"
|
||||
family = "SOP2"
|
||||
opcode = 26
|
||||
variant = "NorB32"
|
||||
operation = "nor"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [{ document = "guide", section = "12.1", page = 104 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_XNOR_B32"
|
||||
family = "SOP2"
|
||||
opcode = 28
|
||||
variant = "XnorB32"
|
||||
operation = "xnor"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [{ document = "guide", section = "12.1", page = 104 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_LSHL_B32"
|
||||
family = "SOP2"
|
||||
opcode = 30
|
||||
variant = "LshlB32"
|
||||
operation = "lshl"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
shift_count_bits = 5
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [{ document = "guide", section = "12.1", page = 104 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_LSHR_B32"
|
||||
family = "SOP2"
|
||||
opcode = 32
|
||||
variant = "LshrB32"
|
||||
operation = "lshr"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
shift_count_bits = 5
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [{ document = "guide", section = "12.1", page = 104 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_ASHR_I32"
|
||||
family = "SOP2"
|
||||
opcode = 34
|
||||
variant = "AshrI32"
|
||||
operation = "ashr"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
shift_count_bits = 5
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [{ document = "guide", section = "12.1", page = 104 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
# ---- SOP2 32-bit integer arithmetic, select and bit-field forms (#215) ----
|
||||
# min/max: SCC = S0 chosen by the strict compare (a tie gives S1, SCC 0). cselect
|
||||
# reads SCC and writes none. bfm, mul, mul_hi write no SCC (Tables 11, 12, 14).
|
||||
# bfe: offset S1[4:0], width S1[22:16]. lshl_add: SCC = carry of (S0 << N) + S1.
|
||||
|
||||
[[form]]
|
||||
name = "S_MIN_I32"
|
||||
family = "SOP2"
|
||||
opcode = 6
|
||||
variant = "MinI32"
|
||||
operation = "min"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "selected_src0"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 102 },
|
||||
{ document = "guide", section = "5.4", page = 34 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_MIN_U32"
|
||||
family = "SOP2"
|
||||
opcode = 7
|
||||
variant = "MinU32"
|
||||
operation = "min"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "selected_src0"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 102 },
|
||||
{ document = "guide", section = "5.4", page = 34 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_MAX_I32"
|
||||
family = "SOP2"
|
||||
opcode = 8
|
||||
variant = "MaxI32"
|
||||
operation = "max"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "selected_src0"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 102 },
|
||||
{ document = "guide", section = "5.4", page = 34 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_MAX_U32"
|
||||
family = "SOP2"
|
||||
opcode = 9
|
||||
variant = "MaxU32"
|
||||
operation = "max"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "selected_src0"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 103 },
|
||||
{ document = "guide", section = "5.4", page = 34 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CSELECT_B32"
|
||||
family = "SOP2"
|
||||
opcode = 10
|
||||
variant = "CselectB32"
|
||||
operation = "cselect"
|
||||
signedness = "bitwise"
|
||||
carry_in = "scc"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 103 },
|
||||
{ document = "guide", section = "5.5", page = 34 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_BFM_B32"
|
||||
family = "SOP2"
|
||||
opcode = 36
|
||||
variant = "BfmB32"
|
||||
operation = "bfm"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 104 },
|
||||
{ document = "guide", section = "5.7", page = 36 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_MUL_I32"
|
||||
family = "SOP2"
|
||||
opcode = 38
|
||||
variant = "MulI32"
|
||||
operation = "mul"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 105 },
|
||||
{ document = "guide", section = "5.4", page = 34 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_BFE_U32"
|
||||
family = "SOP2"
|
||||
opcode = 39
|
||||
variant = "BfeU32"
|
||||
operation = "bfe"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 105 },
|
||||
{ document = "guide", section = "5.7", page = 36 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_BFE_I32"
|
||||
family = "SOP2"
|
||||
opcode = 40
|
||||
variant = "BfeI32"
|
||||
operation = "bfe"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 105 },
|
||||
{ document = "guide", section = "5.7", page = 36 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_ABSDIFF_I32"
|
||||
family = "SOP2"
|
||||
opcode = 44
|
||||
variant = "AbsdiffI32"
|
||||
operation = "absdiff"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 105 },
|
||||
{ document = "guide", section = "5.4", page = 34 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_LSHL1_ADD_U32"
|
||||
family = "SOP2"
|
||||
opcode = 46
|
||||
variant = "Lshl1AddU32"
|
||||
operation = "lshl_add"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
shift_amount = 1
|
||||
scc = "carry_out"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [{ document = "guide", section = "12.1", page = 105 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_LSHL2_ADD_U32"
|
||||
family = "SOP2"
|
||||
opcode = 47
|
||||
variant = "Lshl2AddU32"
|
||||
operation = "lshl_add"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
shift_amount = 2
|
||||
scc = "carry_out"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [{ document = "guide", section = "12.1", page = 105 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_LSHL3_ADD_U32"
|
||||
family = "SOP2"
|
||||
opcode = 48
|
||||
variant = "Lshl3AddU32"
|
||||
operation = "lshl_add"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
shift_amount = 3
|
||||
scc = "carry_out"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [{ document = "guide", section = "12.1", page = 106 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_LSHL4_ADD_U32"
|
||||
family = "SOP2"
|
||||
opcode = 49
|
||||
variant = "Lshl4AddU32"
|
||||
operation = "lshl_add"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
shift_amount = 4
|
||||
scc = "carry_out"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [{ document = "guide", section = "12.1", page = 106 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_MUL_HI_U32"
|
||||
family = "SOP2"
|
||||
opcode = 53
|
||||
variant = "MulHiU32"
|
||||
operation = "mul_hi"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [{ document = "guide", section = "12.1", page = 106 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_MUL_HI_I32"
|
||||
family = "SOP2"
|
||||
opcode = 54
|
||||
variant = "MulHiI32"
|
||||
operation = "mul_hi"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [{ document = "guide", section = "12.1", page = 106 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
@@ -1,269 +0,0 @@
|
||||
# SOPC forms of the gfx1030 semantic registry; included by ../rdna2.toml.
|
||||
# Data only; see the root file for the field meanings.
|
||||
|
||||
# ---- Stage D: SOPC 32-bit integer compares (#215) ----
|
||||
# Only SCC is written: SCC = relation(S0, S1), S0 = SSRC0 on the left (guide 12.4).
|
||||
|
||||
[operand_rules.sopc_scalar]
|
||||
family = "SOPC"
|
||||
src = [
|
||||
{ field = "SSRC0", class = "scalar_source" },
|
||||
{ field = "SSRC1", class = "scalar_source" },
|
||||
]
|
||||
max_literals = 1
|
||||
unsupported = [
|
||||
"src_vcc", "src_exec", "src_m0", "src_ttmp", "src_float_inline",
|
||||
"src_special", "two_literals",
|
||||
]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMP_EQ_I32"
|
||||
family = "SOPC"
|
||||
opcode = 0
|
||||
variant = "CmpEqI32"
|
||||
operation = "compare"
|
||||
relation = "eq"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopc_scalar"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.4", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMP_LG_I32"
|
||||
family = "SOPC"
|
||||
opcode = 1
|
||||
variant = "CmpLgI32"
|
||||
operation = "compare"
|
||||
relation = "lg"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopc_scalar"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.4", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMP_GT_I32"
|
||||
family = "SOPC"
|
||||
opcode = 2
|
||||
variant = "CmpGtI32"
|
||||
operation = "compare"
|
||||
relation = "gt"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopc_scalar"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.4", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMP_GE_I32"
|
||||
family = "SOPC"
|
||||
opcode = 3
|
||||
variant = "CmpGeI32"
|
||||
operation = "compare"
|
||||
relation = "ge"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopc_scalar"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.4", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMP_LT_I32"
|
||||
family = "SOPC"
|
||||
opcode = 4
|
||||
variant = "CmpLtI32"
|
||||
operation = "compare"
|
||||
relation = "lt"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopc_scalar"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.4", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMP_LE_I32"
|
||||
family = "SOPC"
|
||||
opcode = 5
|
||||
variant = "CmpLeI32"
|
||||
operation = "compare"
|
||||
relation = "le"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopc_scalar"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.4", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMP_EQ_U32"
|
||||
family = "SOPC"
|
||||
opcode = 6
|
||||
variant = "CmpEqU32"
|
||||
operation = "compare"
|
||||
relation = "eq"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopc_scalar"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.4", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMP_LG_U32"
|
||||
family = "SOPC"
|
||||
opcode = 7
|
||||
variant = "CmpLgU32"
|
||||
operation = "compare"
|
||||
relation = "lg"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopc_scalar"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.4", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMP_GT_U32"
|
||||
family = "SOPC"
|
||||
opcode = 8
|
||||
variant = "CmpGtU32"
|
||||
operation = "compare"
|
||||
relation = "gt"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopc_scalar"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.4", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMP_GE_U32"
|
||||
family = "SOPC"
|
||||
opcode = 9
|
||||
variant = "CmpGeU32"
|
||||
operation = "compare"
|
||||
relation = "ge"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopc_scalar"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.4", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMP_LT_U32"
|
||||
family = "SOPC"
|
||||
opcode = 10
|
||||
variant = "CmpLtU32"
|
||||
operation = "compare"
|
||||
relation = "lt"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopc_scalar"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.4", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMP_LE_U32"
|
||||
family = "SOPC"
|
||||
opcode = 11
|
||||
variant = "CmpLeU32"
|
||||
operation = "compare"
|
||||
relation = "le"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopc_scalar"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.4", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
@@ -1,358 +0,0 @@
|
||||
# SOPK forms of the gfx1030 semantic registry; included by ../rdna2.toml.
|
||||
# Data only; see the root file for the field meanings.
|
||||
|
||||
# ---- SOPK 16-bit immediate integer forms (#215) ----
|
||||
# SDST is the destination, and the left operand of the compares; SIMM16 is
|
||||
# sign-extended except by the unsigned compares (guide 12.2). The word never
|
||||
# takes a literal dword. SDST s0-s105 only; s0-s7 hold resource descriptors,
|
||||
# so the decoder accepts them as compare operands and the translator never
|
||||
# writes them.
|
||||
|
||||
[operand_rules.sopk_sgpr]
|
||||
family = "SOPK"
|
||||
dst = { field = "SDST", class = "sgpr", min = 0, max = 105 }
|
||||
src = [{ field = "SIMM16", class = "simm16" }]
|
||||
max_literals = 0
|
||||
unsupported = ["dst_vcc", "dst_exec", "dst_ttmp", "dst_m0", "dst_null"]
|
||||
|
||||
[operand_rules.sopk_compare]
|
||||
family = "SOPK"
|
||||
src = [
|
||||
{ field = "SDST", class = "sgpr", min = 0, max = 105 },
|
||||
{ field = "SIMM16", class = "simm16" },
|
||||
]
|
||||
max_literals = 0
|
||||
unsupported = ["dst_vcc", "dst_exec", "dst_ttmp", "dst_m0", "dst_null"]
|
||||
|
||||
[[form]]
|
||||
name = "S_MOVK_I32"
|
||||
family = "SOPK"
|
||||
opcode = 0
|
||||
variant = "MovkI32"
|
||||
operation = "mov"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMOVK_I32"
|
||||
family = "SOPK"
|
||||
opcode = 2
|
||||
variant = "CmovkI32"
|
||||
operation = "cmov"
|
||||
signedness = "signed"
|
||||
carry_in = "scc"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMPK_EQ_I32"
|
||||
family = "SOPK"
|
||||
opcode = 3
|
||||
variant = "CmpkEqI32"
|
||||
operation = "compare"
|
||||
relation = "eq"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_compare"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMPK_LG_I32"
|
||||
family = "SOPK"
|
||||
opcode = 4
|
||||
variant = "CmpkLgI32"
|
||||
operation = "compare"
|
||||
relation = "lg"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_compare"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMPK_GT_I32"
|
||||
family = "SOPK"
|
||||
opcode = 5
|
||||
variant = "CmpkGtI32"
|
||||
operation = "compare"
|
||||
relation = "gt"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_compare"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMPK_GE_I32"
|
||||
family = "SOPK"
|
||||
opcode = 6
|
||||
variant = "CmpkGeI32"
|
||||
operation = "compare"
|
||||
relation = "ge"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_compare"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMPK_LT_I32"
|
||||
family = "SOPK"
|
||||
opcode = 7
|
||||
variant = "CmpkLtI32"
|
||||
operation = "compare"
|
||||
relation = "lt"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_compare"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMPK_LE_I32"
|
||||
family = "SOPK"
|
||||
opcode = 8
|
||||
variant = "CmpkLeI32"
|
||||
operation = "compare"
|
||||
relation = "le"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_compare"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMPK_EQ_U32"
|
||||
family = "SOPK"
|
||||
opcode = 9
|
||||
variant = "CmpkEqU32"
|
||||
operation = "compare"
|
||||
relation = "eq"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_compare"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMPK_LG_U32"
|
||||
family = "SOPK"
|
||||
opcode = 10
|
||||
variant = "CmpkLgU32"
|
||||
operation = "compare"
|
||||
relation = "lg"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_compare"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMPK_GT_U32"
|
||||
family = "SOPK"
|
||||
opcode = 11
|
||||
variant = "CmpkGtU32"
|
||||
operation = "compare"
|
||||
relation = "gt"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_compare"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMPK_GE_U32"
|
||||
family = "SOPK"
|
||||
opcode = 12
|
||||
variant = "CmpkGeU32"
|
||||
operation = "compare"
|
||||
relation = "ge"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_compare"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMPK_LT_U32"
|
||||
family = "SOPK"
|
||||
opcode = 13
|
||||
variant = "CmpkLtU32"
|
||||
operation = "compare"
|
||||
relation = "lt"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_compare"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMPK_LE_U32"
|
||||
family = "SOPK"
|
||||
opcode = 14
|
||||
variant = "CmpkLeU32"
|
||||
operation = "compare"
|
||||
relation = "le"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_compare"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_ADDK_I32"
|
||||
family = "SOPK"
|
||||
opcode = 15
|
||||
variant = "AddkI32"
|
||||
operation = "add"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "signed_overflow"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_MULK_I32"
|
||||
family = "SOPK"
|
||||
opcode = 16
|
||||
variant = "MulkI32"
|
||||
operation = "mul"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
@@ -1,123 +0,0 @@
|
||||
# Existing gfx1030 compute controls, AMD RDNA 2 ISA guide §12.5.
|
||||
|
||||
[operand_rules.sopp_end]
|
||||
family = "SOPP"
|
||||
src = []
|
||||
max_literals = 0
|
||||
unsupported = []
|
||||
immediate = 0
|
||||
|
||||
[operand_rules.sopp_branch]
|
||||
family = "SOPP"
|
||||
src = [{ field = "SIMM16", class = "label" }]
|
||||
max_literals = 0
|
||||
unsupported = []
|
||||
|
||||
[operand_rules.sopp_wait]
|
||||
family = "SOPP"
|
||||
src = [{ field = "SIMM16", class = "waitcnt" }]
|
||||
max_literals = 0
|
||||
unsupported = []
|
||||
immediate = 0x3f70
|
||||
|
||||
[[form]]
|
||||
name = "S_ENDPGM"
|
||||
family = "SOPP"
|
||||
opcode = 1
|
||||
variant = "EndProgram"
|
||||
operation = "end_program"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "sopp_end"
|
||||
spec = [{ document = "guide", section = "12.5", page = 124 }, { document = "guide", section = "13.1.5", page = 245 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_BRANCH"
|
||||
family = "SOPP"
|
||||
opcode = 2
|
||||
variant = "Branch"
|
||||
operation = "branch"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "sopp_branch"
|
||||
spec = [{ document = "guide", section = "12.5", page = 124 }, { document = "guide", section = "13.1.5", page = 245 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CBRANCH_SCC0"
|
||||
family = "SOPP"
|
||||
opcode = 4
|
||||
variant = "BranchSccZero"
|
||||
operation = "branch_scc_zero"
|
||||
signedness = "signed"
|
||||
carry_in = "scc"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "sopp_branch"
|
||||
spec = [{ document = "guide", section = "12.5", page = 124 }, { document = "guide", section = "13.1.5", page = 245 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CBRANCH_VCCZ"
|
||||
family = "SOPP"
|
||||
opcode = 6
|
||||
variant = "BranchVccZero"
|
||||
operation = "branch_vcc_zero"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "sopp_branch"
|
||||
spec = [{ document = "guide", section = "12.5", page = 124 }, { document = "guide", section = "13.1.5", page = 245 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CBRANCH_EXECZ"
|
||||
family = "SOPP"
|
||||
opcode = 8
|
||||
variant = "BranchExecZero"
|
||||
operation = "branch_exec_zero"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "sopp_branch"
|
||||
spec = [{ document = "guide", section = "12.5", page = 125 }, { document = "guide", section = "13.1.5", page = 245 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_WAITCNT"
|
||||
family = "SOPP"
|
||||
opcode = 12
|
||||
variant = "WaitLoad"
|
||||
operation = "wait_load"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "sopp_wait"
|
||||
spec = [{ document = "guide", section = "12.5", page = 125 }, { document = "guide", section = "13.1.5", page = 245 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
@@ -1,123 +0,0 @@
|
||||
# Wave32 VOP1 integer forms, AMD RDNA 2 ISA guide 12.8.
|
||||
|
||||
[operand_rules.vop1_vgpr]
|
||||
family = "VOP1"
|
||||
dst = { field = "VDST", class = "vgpr", min = 0, max = 255 }
|
||||
src = [{ field = "SRC0", class = "vector_source" }]
|
||||
max_literals = 1
|
||||
unsupported = [
|
||||
"src_vcc_hi", "src_exec", "src_m0", "src_ttmp", "src_null", "src_float_inline", "src_special",
|
||||
]
|
||||
|
||||
# Both operands are read and written by swap; SRC0 must select a VGPR.
|
||||
[operand_rules.vop1_swap]
|
||||
family = "VOP1"
|
||||
dst = { field = "VDST", class = "vgpr", min = 0, max = 255 }
|
||||
src = [{ field = "SRC0", class = "vgpr" }]
|
||||
max_literals = 0
|
||||
unsupported = [
|
||||
"src_sgpr", "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_null", "src_inline",
|
||||
"src_float_inline", "src_special", "src_literal",
|
||||
]
|
||||
|
||||
[[form]]
|
||||
name = "V_NOT_B32"
|
||||
family = "VOP1"
|
||||
opcode = 55
|
||||
variant = "NotB32"
|
||||
operation = "not"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vop1_vgpr"
|
||||
spec = [{ document = "guide", section = "12.8", page = 143 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_BFREV_B32"
|
||||
family = "VOP1"
|
||||
opcode = 56
|
||||
variant = "BfrevB32"
|
||||
operation = "brev"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vop1_vgpr"
|
||||
spec = [{ document = "guide", section = "12.8", page = 143 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_FFBH_U32"
|
||||
family = "VOP1"
|
||||
opcode = 57
|
||||
variant = "FfbhU32"
|
||||
operation = "flbit"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vop1_vgpr"
|
||||
spec = [{ document = "guide", section = "12.8", page = 143 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_FFBL_B32"
|
||||
family = "VOP1"
|
||||
opcode = 58
|
||||
variant = "FfblB32"
|
||||
operation = "ff1"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vop1_vgpr"
|
||||
spec = [{ document = "guide", section = "12.8", page = 143 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_FFBH_I32"
|
||||
family = "VOP1"
|
||||
opcode = 59
|
||||
variant = "FfbhI32"
|
||||
operation = "flbit"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vop1_vgpr"
|
||||
spec = [{ document = "guide", section = "12.8", page = 144 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_SWAP_B32"
|
||||
family = "VOP1"
|
||||
opcode = 101
|
||||
variant = "SwapB32"
|
||||
operation = "swap"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vop1_swap"
|
||||
spec = [{ document = "guide", section = "12.8", page = 149 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
@@ -1,432 +0,0 @@
|
||||
# VOP2 forms of the gfx1030 semantic registry; included by ../rdna2.toml.
|
||||
# Data only; see the root file for the field meanings.
|
||||
|
||||
# ---- VOP2 32-bit vector integer forms (#215) ----
|
||||
# Per lane under EXEC; no SCC, VCC or EXEC write (guide 12.7). The 24-bit
|
||||
# multiplies read S0[23:0] and S1[23:0], sign-extended when signed; the high
|
||||
# forms keep bits 63:32 of the product. SUBREV declares its reversed sources.
|
||||
|
||||
[operand_rules.vop2_vgpr]
|
||||
family = "VOP2"
|
||||
dst = { field = "VDST", class = "vgpr", min = 0, max = 255 }
|
||||
src = [
|
||||
{ field = "SRC0", class = "vector_source" },
|
||||
{ field = "VSRC1", class = "vgpr" },
|
||||
]
|
||||
# vector_source = VGPR, normal SGPR s0-s105, vcc_lo, inline integer -16..64, or a literal word.
|
||||
max_literals = 1
|
||||
unsupported = [
|
||||
"src_vcc_hi", "src_exec", "src_m0", "src_ttmp", "src_null", "src_float_inline", "src_special",
|
||||
]
|
||||
|
||||
[[form]]
|
||||
name = "V_MUL_I32_I24"
|
||||
family = "VOP2"
|
||||
opcode = 9
|
||||
variant = "MulI32I24"
|
||||
operation = "mul24"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "vop2_vgpr"
|
||||
spec = [{ document = "guide", section = "12.7", page = 131 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_MUL_HI_I32_I24"
|
||||
family = "VOP2"
|
||||
opcode = 10
|
||||
variant = "MulHiI32I24"
|
||||
operation = "mul_hi24"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "vop2_vgpr"
|
||||
spec = [{ document = "guide", section = "12.7", page = 132 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_MUL_U32_U24"
|
||||
family = "VOP2"
|
||||
opcode = 11
|
||||
variant = "MulU32U24"
|
||||
operation = "mul24"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "vop2_vgpr"
|
||||
spec = [{ document = "guide", section = "12.7", page = 132 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_MUL_HI_U32_U24"
|
||||
family = "VOP2"
|
||||
opcode = 12
|
||||
variant = "MulHiU32U24"
|
||||
operation = "mul_hi24"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "vop2_vgpr"
|
||||
spec = [{ document = "guide", section = "12.7", page = 132 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_MIN_I32"
|
||||
family = "VOP2"
|
||||
opcode = 17
|
||||
variant = "MinI32"
|
||||
operation = "min"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "vop2_vgpr"
|
||||
spec = [{ document = "guide", section = "12.7", page = 133 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_MAX_I32"
|
||||
family = "VOP2"
|
||||
opcode = 18
|
||||
variant = "MaxI32"
|
||||
operation = "max"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "vop2_vgpr"
|
||||
spec = [{ document = "guide", section = "12.7", page = 133 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_MIN_U32"
|
||||
family = "VOP2"
|
||||
opcode = 19
|
||||
variant = "MinU32"
|
||||
operation = "min"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "vop2_vgpr"
|
||||
spec = [{ document = "guide", section = "12.7", page = 133 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_MAX_U32"
|
||||
family = "VOP2"
|
||||
opcode = 20
|
||||
variant = "MaxU32"
|
||||
operation = "max"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "vop2_vgpr"
|
||||
spec = [{ document = "guide", section = "12.7", page = 133 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_XNOR_B32"
|
||||
family = "VOP2"
|
||||
opcode = 30
|
||||
variant = "XnorB32"
|
||||
operation = "xnor"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "vop2_vgpr"
|
||||
spec = [{ document = "guide", section = "12.7", page = 134 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_ADD_NC_U32"
|
||||
family = "VOP2"
|
||||
opcode = 37
|
||||
variant = "AddNcU32"
|
||||
operation = "add"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "vop2_vgpr"
|
||||
spec = [{ document = "guide", section = "12.7", page = 134 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_SUB_NC_U32"
|
||||
family = "VOP2"
|
||||
opcode = 38
|
||||
variant = "SubNcU32"
|
||||
operation = "sub"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "vop2_vgpr"
|
||||
spec = [{ document = "guide", section = "12.7", page = 134 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_SUBREV_NC_U32"
|
||||
family = "VOP2"
|
||||
opcode = 39
|
||||
variant = "SubrevNcU32"
|
||||
operation = "sub"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
source_order = "reversed"
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "vop2_vgpr"
|
||||
spec = [{ document = "guide", section = "12.7", page = 134 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
# ---- VOP2 logical and shift forms migrated from hand-written code (#215 M27) ----
|
||||
# Per lane under EXEC; no SCC, VCC or EXEC write (guide 12.7). The shifts read
|
||||
# their sources reversed: D = S1 shifted by S0[4:0]; ASHRREV fills with S1's sign.
|
||||
# These keep the subset the hand-written decoder accepted: both sources VGPRs.
|
||||
[operand_rules.vop2_vgpr2]
|
||||
family = "VOP2"
|
||||
dst = { field = "VDST", class = "vgpr", min = 0, max = 255 }
|
||||
src = [
|
||||
{ field = "SRC0", class = "vgpr" },
|
||||
{ field = "VSRC1", class = "vgpr" },
|
||||
]
|
||||
max_literals = 0
|
||||
unsupported = [
|
||||
"src_sgpr", "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_null", "src_inline",
|
||||
"src_float_inline", "src_special", "src_literal",
|
||||
]
|
||||
|
||||
[[form]]
|
||||
name = "V_LSHRREV_B32"
|
||||
family = "VOP2"
|
||||
opcode = 22
|
||||
variant = "LshrrevB32"
|
||||
operation = "lshr"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
shift_count_bits = 5
|
||||
source_order = "reversed"
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "vop2_vgpr2"
|
||||
spec = [{ document = "guide", section = "12.7", page = 133 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_ASHRREV_I32"
|
||||
family = "VOP2"
|
||||
opcode = 24
|
||||
variant = "AshrrevI32"
|
||||
operation = "ashr"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
shift_count_bits = 5
|
||||
source_order = "reversed"
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "vop2_vgpr2"
|
||||
spec = [{ document = "guide", section = "12.7", page = 133 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_LSHLREV_B32"
|
||||
family = "VOP2"
|
||||
opcode = 26
|
||||
variant = "LshlrevB32"
|
||||
operation = "lshl"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
shift_count_bits = 5
|
||||
source_order = "reversed"
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "vop2_vgpr2"
|
||||
spec = [{ document = "guide", section = "12.7", page = 133 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_AND_B32"
|
||||
family = "VOP2"
|
||||
opcode = 27
|
||||
variant = "AndB32"
|
||||
operation = "and"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "vop2_vgpr2"
|
||||
spec = [{ document = "guide", section = "12.7", page = 133 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_OR_B32"
|
||||
family = "VOP2"
|
||||
opcode = 28
|
||||
variant = "OrB32"
|
||||
operation = "or"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "vop2_vgpr2"
|
||||
spec = [{ document = "guide", section = "12.7", page = 133 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_XOR_B32"
|
||||
family = "VOP2"
|
||||
opcode = 29
|
||||
variant = "XorB32"
|
||||
operation = "xor"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "vop2_vgpr2"
|
||||
spec = [{ document = "guide", section = "12.7", page = 133 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[operand_rules.vop2_vcc]
|
||||
family = "VOP2"
|
||||
dst = { field = "VDST", class = "vgpr", min = 0, max = 255 }
|
||||
src = [
|
||||
{ field = "SRC0", class = "vector_source" },
|
||||
{ field = "VSRC1", class = "vgpr" },
|
||||
]
|
||||
# vector_source = VGPR, normal SGPR s0-s105, vcc_lo, inline integer -16..64, or a literal word.
|
||||
max_literals = 1
|
||||
unsupported = [
|
||||
"src_vcc_hi", "src_exec", "src_m0", "src_ttmp", "src_null", "src_float_inline", "src_special",
|
||||
]
|
||||
|
||||
[[form]]
|
||||
name = "V_CNDMASK_B32"
|
||||
family = "VOP2"
|
||||
opcode = 1
|
||||
variant = "CndmaskB32"
|
||||
operation = "cselect"
|
||||
signedness = "bitwise"
|
||||
carry_in = "vcc"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vop2_vcc"
|
||||
spec = [{ document = "guide", section = "12.7", page = 131 }, { document = "guide", section = "3.9", page = 20 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_ADD_CO_CI_U32"
|
||||
family = "VOP2"
|
||||
opcode = 40
|
||||
variant = "AddCoCiU32"
|
||||
operation = "add"
|
||||
signedness = "unsigned"
|
||||
carry_in = "vcc"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vop2_vcc"
|
||||
spec = [{ document = "guide", section = "12.7", page = 134 }, { document = "guide", section = "3.9", page = 20 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_SUB_CO_CI_U32"
|
||||
family = "VOP2"
|
||||
opcode = 41
|
||||
variant = "SubCoCiU32"
|
||||
operation = "sub"
|
||||
signedness = "unsigned"
|
||||
carry_in = "vcc"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vop2_vcc"
|
||||
spec = [{ document = "guide", section = "12.7", page = 134 }, { document = "guide", section = "3.9", page = 20 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_SUBREV_CO_CI_U32"
|
||||
family = "VOP2"
|
||||
opcode = 42
|
||||
variant = "SubrevCoCiU32"
|
||||
operation = "sub"
|
||||
signedness = "unsigned"
|
||||
carry_in = "vcc"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vop2_vcc"
|
||||
source_order = "reversed"
|
||||
spec = [{ document = "guide", section = "12.7", page = 134 }, { document = "guide", section = "3.9", page = 20 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
@@ -1,362 +0,0 @@
|
||||
# VOP3 encodings of the gfx1030 semantic registry; included by ../rdna2.toml.
|
||||
# Data only; see the root file for the field meanings.
|
||||
|
||||
# ---- Wave32 VOPC compares in VOP3A (#215) ----
|
||||
|
||||
# VDST encodes the scalar lane-mask destination, including vcc_lo (selector 106).
|
||||
# The two sources are VGPRs. Modifiers are clear and SRC2 is inline zero.
|
||||
[operand_rules.vop3_cmp_vgpr2]
|
||||
family = "VOP3"
|
||||
dst = { field = "VDST", class = "sgpr", min = 0, max = 106 }
|
||||
src = [
|
||||
{ field = "SRC0", class = "vgpr" },
|
||||
{ field = "SRC1", class = "vgpr" },
|
||||
]
|
||||
max_literals = 0
|
||||
variant_only = true
|
||||
unsupported = [
|
||||
"dst_vcc_hi", "dst_exec", "dst_ttmp", "dst_m0", "dst_null",
|
||||
"src_sgpr", "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_null", "src_inline",
|
||||
"src_float_inline", "src_special", "src_literal", "modifiers", "src2",
|
||||
]
|
||||
|
||||
# Opcodes come from the pinned XML's default ENC_VOP3 records.
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_LT_I32"
|
||||
family = "VOP3"
|
||||
opcode = 129
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_EQ_I32"
|
||||
family = "VOP3"
|
||||
opcode = 130
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_LE_I32"
|
||||
family = "VOP3"
|
||||
opcode = 131
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_GT_I32"
|
||||
family = "VOP3"
|
||||
opcode = 132
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_NE_I32"
|
||||
family = "VOP3"
|
||||
opcode = 133
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_GE_I32"
|
||||
family = "VOP3"
|
||||
opcode = 134
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_LT_U32"
|
||||
family = "VOP3"
|
||||
opcode = 193
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_EQ_U32"
|
||||
family = "VOP3"
|
||||
opcode = 194
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_LE_U32"
|
||||
family = "VOP3"
|
||||
opcode = 195
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_GT_U32"
|
||||
family = "VOP3"
|
||||
opcode = 196
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_NE_U32"
|
||||
family = "VOP3"
|
||||
opcode = 197
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_GE_U32"
|
||||
family = "VOP3"
|
||||
opcode = 198
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_F_I32"
|
||||
family = "VOP3"
|
||||
opcode = 128
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_T_I32"
|
||||
family = "VOP3"
|
||||
opcode = 135
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_F_U32"
|
||||
family = "VOP3"
|
||||
opcode = 192
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_T_U32"
|
||||
family = "VOP3"
|
||||
opcode = 199
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
# ---- VOP3 encoding variants of registry forms (#215) ----
|
||||
# An [[encoding_variant]] re-encodes a form declared in another family file: it
|
||||
# names the form (`of`), this family, the XML opcode here and the operand rule
|
||||
# of this encoding, and inherits everything else (operation, signedness,
|
||||
# effects) from the form. The XML must agree with the inherited declaration.
|
||||
|
||||
# Two VGPR sources, VGPR destination, no modifiers (ABS, OP_SEL, CLAMP, OMOD
|
||||
# and NEG clear) and SRC2 the assembler's unused inline zero. This is the
|
||||
# subset the decoder accepted for v_add_nc_u32_e64 before the registry.
|
||||
[operand_rules.vop3_vgpr2]
|
||||
family = "VOP3"
|
||||
dst = { field = "VDST", class = "vgpr", min = 0, max = 255 }
|
||||
src = [
|
||||
{ field = "SRC0", class = "vgpr" },
|
||||
{ field = "SRC1", class = "vgpr" },
|
||||
]
|
||||
max_literals = 0
|
||||
# Only [[encoding_variant]] entries may use this rule; it hosts no new forms.
|
||||
variant_only = true
|
||||
unsupported = [
|
||||
"src_sgpr", "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_null", "src_inline",
|
||||
"src_float_inline", "src_special", "src_literal", "modifiers", "src2",
|
||||
]
|
||||
|
||||
# VOP3 opcode of a VOP2 form = VOP2 opcode + 0x100 (guide 12.7.1), e.g. 37 + 256
|
||||
# = 293; each opcode below is still checked against the pinned XML.
|
||||
[[encoding_variant]]
|
||||
of = "V_ADD_NC_U32"
|
||||
family = "VOP3"
|
||||
opcode = 293
|
||||
operands = "vop3_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.12", page = 167 },
|
||||
{ document = "guide", section = "12.7", page = 134 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
# ABS and NEG apply to floating-point inputs (guide 6.2.1) and OMOD
|
||||
# applies to floating-point results (6.2.2). These integer forms use neither.
|
||||
# OP_SEL selects 16-bit halves (13.3.4). CLAMP saturates integer results
|
||||
# (6.5), which these registry forms do not declare. SGPR, inline and literal
|
||||
# sources remain outside this operand rule.
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_MUL_I32_I24"
|
||||
family = "VOP3"
|
||||
opcode = 265
|
||||
operands = "vop3_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.12", page = 167 },
|
||||
{ document = "guide", section = "12.7", page = 131 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_MUL_HI_I32_I24"
|
||||
family = "VOP3"
|
||||
opcode = 266
|
||||
operands = "vop3_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.12", page = 167 },
|
||||
{ document = "guide", section = "12.7", page = 132 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_MUL_U32_U24"
|
||||
family = "VOP3"
|
||||
opcode = 267
|
||||
operands = "vop3_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.12", page = 167 },
|
||||
{ document = "guide", section = "12.7", page = 132 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_MUL_HI_U32_U24"
|
||||
family = "VOP3"
|
||||
opcode = 268
|
||||
operands = "vop3_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.12", page = 167 },
|
||||
{ document = "guide", section = "12.7", page = 132 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_MIN_I32"
|
||||
family = "VOP3"
|
||||
opcode = 273
|
||||
operands = "vop3_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.12", page = 167 },
|
||||
{ document = "guide", section = "12.7", page = 133 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_MAX_I32"
|
||||
family = "VOP3"
|
||||
opcode = 274
|
||||
operands = "vop3_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.12", page = 167 },
|
||||
{ document = "guide", section = "12.7", page = 133 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_MIN_U32"
|
||||
family = "VOP3"
|
||||
opcode = 275
|
||||
operands = "vop3_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.12", page = 167 },
|
||||
{ document = "guide", section = "12.7", page = 133 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_MAX_U32"
|
||||
family = "VOP3"
|
||||
opcode = 276
|
||||
operands = "vop3_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.12", page = 167 },
|
||||
{ document = "guide", section = "12.7", page = 133 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_XNOR_B32"
|
||||
family = "VOP3"
|
||||
opcode = 286
|
||||
operands = "vop3_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.12", page = 167 },
|
||||
{ document = "guide", section = "12.7", page = 134 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_SUB_NC_U32"
|
||||
family = "VOP3"
|
||||
opcode = 294
|
||||
operands = "vop3_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.12", page = 167 },
|
||||
{ document = "guide", section = "12.7", page = 134 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_SUBREV_NC_U32"
|
||||
family = "VOP3"
|
||||
opcode = 295
|
||||
operands = "vop3_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.12", page = 167 },
|
||||
{ document = "guide", section = "12.7", page = 134 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
@@ -1,974 +0,0 @@
|
||||
# VOPC forms of the gfx1030 semantic registry; included by ../rdna2.toml.
|
||||
# Data only; see the root file for the field meanings.
|
||||
|
||||
# ---- VOPC Wave32 32-bit integer compares (migrated from #239) ----
|
||||
# VCC_LO := lanes where EXEC and the relation (S0 = SRC0 on the left) hold;
|
||||
# the contract is docs/shaders/vector-compare.md. relation "lg" is the guide's
|
||||
# LG/NE offset 5 (Table 59), named V_CMP_NE_* in the XML. v_cmpx (EXEC writes),
|
||||
# the VOP3 encoding and Wave64 stay unsupported.
|
||||
[operand_rules.vopc_vcc]
|
||||
family = "VOPC"
|
||||
src = [
|
||||
{ field = "SRC0", class = "vector_source" },
|
||||
{ field = "VSRC1", class = "vgpr" },
|
||||
]
|
||||
# The destination is implicitly vcc_lo; SRC0 is a vector_source as for VOP2.
|
||||
max_literals = 1
|
||||
unsupported = [
|
||||
"src_vcc_hi", "src_exec", "src_m0", "src_ttmp", "src_null", "src_float_inline", "src_special",
|
||||
]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_LT_I32"
|
||||
family = "VOPC"
|
||||
opcode = 129
|
||||
variant = "CmpLtI32"
|
||||
operation = "compare"
|
||||
relation = "lt"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_EQ_I32"
|
||||
family = "VOPC"
|
||||
opcode = 130
|
||||
variant = "CmpEqI32"
|
||||
operation = "compare"
|
||||
relation = "eq"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_LE_I32"
|
||||
family = "VOPC"
|
||||
opcode = 131
|
||||
variant = "CmpLeI32"
|
||||
operation = "compare"
|
||||
relation = "le"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_GT_I32"
|
||||
family = "VOPC"
|
||||
opcode = 132
|
||||
variant = "CmpGtI32"
|
||||
operation = "compare"
|
||||
relation = "gt"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_NE_I32"
|
||||
family = "VOPC"
|
||||
opcode = 133
|
||||
variant = "CmpNeI32"
|
||||
operation = "compare"
|
||||
relation = "lg"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_GE_I32"
|
||||
family = "VOPC"
|
||||
opcode = 134
|
||||
variant = "CmpGeI32"
|
||||
operation = "compare"
|
||||
relation = "ge"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_LT_U32"
|
||||
family = "VOPC"
|
||||
opcode = 193
|
||||
variant = "CmpLtU32"
|
||||
operation = "compare"
|
||||
relation = "lt"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_EQ_U32"
|
||||
family = "VOPC"
|
||||
opcode = 194
|
||||
variant = "CmpEqU32"
|
||||
operation = "compare"
|
||||
relation = "eq"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_LE_U32"
|
||||
family = "VOPC"
|
||||
opcode = 195
|
||||
variant = "CmpLeU32"
|
||||
operation = "compare"
|
||||
relation = "le"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_GT_U32"
|
||||
family = "VOPC"
|
||||
opcode = 196
|
||||
variant = "CmpGtU32"
|
||||
operation = "compare"
|
||||
relation = "gt"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_NE_U32"
|
||||
family = "VOPC"
|
||||
opcode = 197
|
||||
variant = "CmpNeU32"
|
||||
operation = "compare"
|
||||
relation = "lg"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_GE_U32"
|
||||
family = "VOPC"
|
||||
opcode = 198
|
||||
variant = "CmpGeU32"
|
||||
operation = "compare"
|
||||
relation = "ge"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
# ---- VOPC F and T compares (guide Table 59 offsets 0 and 7) ----
|
||||
# The test is false or true for every lane, so VCC_LO := 0 or the EXEC lanes
|
||||
# that exist. Sources are still decoded and checked as for the other compares
|
||||
# (docs/shaders/vector-compare.md section 5).
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_F_I32"
|
||||
family = "VOPC"
|
||||
opcode = 128
|
||||
variant = "CmpFI32"
|
||||
operation = "compare"
|
||||
relation = "f"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_T_I32"
|
||||
family = "VOPC"
|
||||
opcode = 135
|
||||
variant = "CmpTI32"
|
||||
operation = "compare"
|
||||
relation = "t"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_F_U32"
|
||||
family = "VOPC"
|
||||
opcode = 192
|
||||
variant = "CmpFU32"
|
||||
operation = "compare"
|
||||
relation = "f"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_T_U32"
|
||||
family = "VOPC"
|
||||
opcode = 199
|
||||
variant = "CmpTU32"
|
||||
operation = "compare"
|
||||
relation = "t"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
# Wave32 64-bit integer compares (guide 3.6.3, 6.2 Table 20 and 12.9).
|
||||
[operand_rules.vopc_vcc_pair]
|
||||
family = "VOPC"
|
||||
src = [
|
||||
{ field = "SRC0", class = "vector_pair_or_inline_integer" },
|
||||
{ field = "VSRC1", class = "vgpr_pair" },
|
||||
]
|
||||
max_literals = 0
|
||||
unsupported = [
|
||||
"src_vcc", "src_literal", "src_exec", "src_m0", "src_ttmp", "src_null",
|
||||
"src_float_inline", "src_special",
|
||||
]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_LT_I64"
|
||||
family = "VOPC"
|
||||
opcode = 161
|
||||
variant = "CmpLtI64"
|
||||
operation = "compare"
|
||||
relation = "lt"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 64
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_pair"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_EQ_I64"
|
||||
family = "VOPC"
|
||||
opcode = 162
|
||||
variant = "CmpEqI64"
|
||||
operation = "compare"
|
||||
relation = "eq"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 64
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_pair"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_LE_I64"
|
||||
family = "VOPC"
|
||||
opcode = 163
|
||||
variant = "CmpLeI64"
|
||||
operation = "compare"
|
||||
relation = "le"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 64
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_pair"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_GT_I64"
|
||||
family = "VOPC"
|
||||
opcode = 164
|
||||
variant = "CmpGtI64"
|
||||
operation = "compare"
|
||||
relation = "gt"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 64
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_pair"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_NE_I64"
|
||||
family = "VOPC"
|
||||
opcode = 165
|
||||
variant = "CmpNeI64"
|
||||
operation = "compare"
|
||||
relation = "lg"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 64
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_pair"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_GE_I64"
|
||||
family = "VOPC"
|
||||
opcode = 166
|
||||
variant = "CmpGeI64"
|
||||
operation = "compare"
|
||||
relation = "ge"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 64
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_pair"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_LT_U64"
|
||||
family = "VOPC"
|
||||
opcode = 225
|
||||
variant = "CmpLtU64"
|
||||
operation = "compare"
|
||||
relation = "lt"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 64
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_pair"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_EQ_U64"
|
||||
family = "VOPC"
|
||||
opcode = 226
|
||||
variant = "CmpEqU64"
|
||||
operation = "compare"
|
||||
relation = "eq"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 64
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_pair"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_LE_U64"
|
||||
family = "VOPC"
|
||||
opcode = 227
|
||||
variant = "CmpLeU64"
|
||||
operation = "compare"
|
||||
relation = "le"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 64
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_pair"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_GT_U64"
|
||||
family = "VOPC"
|
||||
opcode = 228
|
||||
variant = "CmpGtU64"
|
||||
operation = "compare"
|
||||
relation = "gt"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 64
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_pair"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_NE_U64"
|
||||
family = "VOPC"
|
||||
opcode = 229
|
||||
variant = "CmpNeU64"
|
||||
operation = "compare"
|
||||
relation = "lg"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 64
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_pair"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_GE_U64"
|
||||
family = "VOPC"
|
||||
opcode = 230
|
||||
variant = "CmpGeU64"
|
||||
operation = "compare"
|
||||
relation = "ge"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 64
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_pair"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_F_I64"
|
||||
family = "VOPC"
|
||||
opcode = 160
|
||||
variant = "CmpFI64"
|
||||
operation = "compare"
|
||||
relation = "f"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 64
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_pair"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_T_I64"
|
||||
family = "VOPC"
|
||||
opcode = 167
|
||||
variant = "CmpTI64"
|
||||
operation = "compare"
|
||||
relation = "t"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 64
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_pair"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_F_U64"
|
||||
family = "VOPC"
|
||||
opcode = 224
|
||||
variant = "CmpFU64"
|
||||
operation = "compare"
|
||||
relation = "f"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 64
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_pair"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_T_U64"
|
||||
family = "VOPC"
|
||||
opcode = 231
|
||||
variant = "CmpTU64"
|
||||
operation = "compare"
|
||||
relation = "t"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 64
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_pair"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal"]
|
||||
|
||||
# Wave32 16-bit integer compares (guide 12.9, Tables 59 and 61).
|
||||
[operand_rules.vopc_vcc_half]
|
||||
family = "VOPC"
|
||||
src = [
|
||||
{ field = "SRC0", class = "vector_source" },
|
||||
{ field = "VSRC1", class = "vgpr" },
|
||||
]
|
||||
# Guide 6.2, 6.2.5 and 6.8: read the low half of each source.
|
||||
max_literals = 0
|
||||
unsupported = [
|
||||
"src_literal", "src_vcc_hi", "src_exec", "src_m0", "src_ttmp", "src_null", "src_float_inline", "src_special",
|
||||
]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_LT_I16"
|
||||
family = "VOPC"
|
||||
opcode = 137
|
||||
variant = "CmpLtI16"
|
||||
operation = "compare"
|
||||
relation = "lt"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 16
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_half"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_EQ_I16"
|
||||
family = "VOPC"
|
||||
opcode = 138
|
||||
variant = "CmpEqI16"
|
||||
operation = "compare"
|
||||
relation = "eq"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 16
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_half"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_LE_I16"
|
||||
family = "VOPC"
|
||||
opcode = 139
|
||||
variant = "CmpLeI16"
|
||||
operation = "compare"
|
||||
relation = "le"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 16
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_half"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_GT_I16"
|
||||
family = "VOPC"
|
||||
opcode = 140
|
||||
variant = "CmpGtI16"
|
||||
operation = "compare"
|
||||
relation = "gt"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 16
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_half"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_NE_I16"
|
||||
family = "VOPC"
|
||||
opcode = 141
|
||||
variant = "CmpNeI16"
|
||||
operation = "compare"
|
||||
relation = "lg"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 16
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_half"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_GE_I16"
|
||||
family = "VOPC"
|
||||
opcode = 142
|
||||
variant = "CmpGeI16"
|
||||
operation = "compare"
|
||||
relation = "ge"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 16
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_half"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_LT_U16"
|
||||
family = "VOPC"
|
||||
opcode = 169
|
||||
variant = "CmpLtU16"
|
||||
operation = "compare"
|
||||
relation = "lt"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 16
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_half"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_EQ_U16"
|
||||
family = "VOPC"
|
||||
opcode = 170
|
||||
variant = "CmpEqU16"
|
||||
operation = "compare"
|
||||
relation = "eq"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 16
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_half"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_LE_U16"
|
||||
family = "VOPC"
|
||||
opcode = 171
|
||||
variant = "CmpLeU16"
|
||||
operation = "compare"
|
||||
relation = "le"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 16
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_half"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_GT_U16"
|
||||
family = "VOPC"
|
||||
opcode = 172
|
||||
variant = "CmpGtU16"
|
||||
operation = "compare"
|
||||
relation = "gt"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 16
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_half"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_NE_U16"
|
||||
family = "VOPC"
|
||||
opcode = 173
|
||||
variant = "CmpNeU16"
|
||||
operation = "compare"
|
||||
relation = "lg"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 16
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_half"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_GE_U16"
|
||||
family = "VOPC"
|
||||
opcode = 174
|
||||
variant = "CmpGeU16"
|
||||
operation = "compare"
|
||||
relation = "ge"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 16
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_half"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
+46
-213
@@ -2,42 +2,13 @@
|
||||
|
||||
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_BRANCH, S_CBRANCH_EXECZ,
|
||||
S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_ENDPGM, S_MOV_B32, S_WAITCNT, S_WAITCNT_VSCNT, V_ADD_F32,
|
||||
V_ADD_NC_U32, V_AND_B32, V_ASHRREV_I32, V_CMP_EQ_I32, V_CMP_EQ_U32, V_CMP_GE_I32, V_CMP_GE_U32,
|
||||
V_CMP_GT_I32, V_CMP_GT_U32, V_CMP_LE_I32, V_CMP_LE_U32, V_CMP_LT_I32, V_CMP_LT_U32,
|
||||
V_CMP_NE_I32, V_CMP_NE_U32, V_INTERP_P1_F32, V_INTERP_P2_F32, V_LSHLREV_B32, V_LSHRREV_B32,
|
||||
V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32,
|
||||
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_INTERP_P1_F32, V_INTERP_P2_F32,
|
||||
V_LSHLREV_B32, V_LSHRREV_B32, V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32,
|
||||
};
|
||||
pub use semantics_gen::{
|
||||
ScalarAluOp, ScalarCompareOp, ScalarImmediateCompareOp, ScalarImmediateOp, ScalarUnaryOp,
|
||||
SoppControlOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp, VectorCompareVop3Op,
|
||||
VectorSwapOp, VectorUnaryOp,
|
||||
};
|
||||
|
||||
impl VectorAluOp {
|
||||
/// Whether this encoding takes a per-lane VCC_LO bit.
|
||||
pub fn reads_vcc(self) -> bool {
|
||||
self.semantics().carry_in == semantics::CarryIn::Vcc
|
||||
}
|
||||
|
||||
/// Whether this encoding replaces the Wave32 VCC_LO mask.
|
||||
pub fn writes_vcc(self) -> bool {
|
||||
self.semantics().vcc == semantics::MaskEffect::LaneMask
|
||||
}
|
||||
}
|
||||
|
||||
/// SGPR index of `vcc_lo`, the Wave32 vector condition code.
|
||||
pub const VCC_LO: u8 = 106;
|
||||
|
||||
/// Selects the instruction encoding independently of the container and execution ABI.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
@@ -71,8 +42,6 @@ impl Opcode {
|
||||
pub enum VectorSource {
|
||||
/// VGPR index.
|
||||
Register(u8),
|
||||
/// Normal SGPR index (s0-s105) or `vcc_lo` (106), read as a wave-uniform value.
|
||||
Scalar(u8),
|
||||
/// Inline integer or literal word, represented by its bits.
|
||||
Immediate(u32),
|
||||
}
|
||||
@@ -81,8 +50,6 @@ impl fmt::Display for VectorSource {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::Register(register) => write!(formatter, "v{register}"),
|
||||
Self::Scalar(VCC_LO) => formatter.write_str("vcc_lo"),
|
||||
Self::Scalar(register) => write!(formatter, "s{register}"),
|
||||
Self::Immediate(value) => write!(formatter, "0x{value:x}"),
|
||||
}
|
||||
}
|
||||
@@ -109,28 +76,6 @@ impl fmt::Display for ScalarSource {
|
||||
}
|
||||
}
|
||||
|
||||
/// Relation tested by a SOPC or VOPC integer compare; S0 (SSRC0 or SRC0) is on
|
||||
/// the left.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum CompareRelation {
|
||||
/// S0 < S1 (opcode offset 1).
|
||||
Less,
|
||||
/// S0 == S1 (offset 2).
|
||||
Equal,
|
||||
/// S0 <= S1 (offset 3).
|
||||
LessOrEqual,
|
||||
/// S0 > S1 (offset 4).
|
||||
Greater,
|
||||
/// S0 != S1 (offset 5).
|
||||
NotEqual,
|
||||
/// S0 >= S1 (offset 6).
|
||||
GreaterOrEqual,
|
||||
/// Never holds (VOPC F, offset 0).
|
||||
False,
|
||||
/// Always holds (VOPC T, offset 7).
|
||||
True,
|
||||
}
|
||||
|
||||
/// Output targeted by a supported uncompressed four-component export.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum ExportTarget {
|
||||
@@ -168,83 +113,15 @@ pub enum Instruction {
|
||||
WaitStore,
|
||||
/// VOP1 unmodified 32-bit vector move.
|
||||
MoveB32 { dst: u8, src: VectorSource },
|
||||
/// VOP1 unary integer operation with a single VGPR result.
|
||||
VectorUnary {
|
||||
op: VectorUnaryOp,
|
||||
dst: u8,
|
||||
src: VectorSource,
|
||||
},
|
||||
/// VOP1 register swap. Both operands are inputs and outputs.
|
||||
VectorSwap { op: VectorSwapOp, dst: u8, src: u8 },
|
||||
/// VOP3 encoding of a registry VOP2 integer operation (operand rule
|
||||
/// `vop3_vgpr2`): two VGPR sources and no input or output modifiers.
|
||||
VectorAluVop3 {
|
||||
op: VectorAluVop3Op,
|
||||
dst: u8,
|
||||
src0: u8,
|
||||
src1: u8,
|
||||
},
|
||||
/// SOP1 32-bit unary integer operation. The move also allows an explicit
|
||||
/// VCC or EXEC half destination. Some unary operations write SCC.
|
||||
ScalarUnary {
|
||||
op: ScalarUnaryOp,
|
||||
dst: u8,
|
||||
src: ScalarSource,
|
||||
},
|
||||
/// SOP2 32-bit integer operation writing a normal SGPR (s0-s105) and, for
|
||||
/// most operations, SCC; `s_cselect_b32` also reads SCC.
|
||||
ScalarAlu {
|
||||
op: ScalarAluOp,
|
||||
dst: u8,
|
||||
/// VOP3 unsigned 32-bit addition with no carry or input/output modifiers.
|
||||
AddNoCarryU32 { dst: u8, src0: u8, src1: u8 },
|
||||
/// SOP1 32-bit move to a normal SGPR or an EXEC/VCC half.
|
||||
ScalarMoveB32 { dst: u8, src: ScalarSource },
|
||||
/// SOPC 32-bit equality comparison writing SCC.
|
||||
ScalarCompareEqU32 {
|
||||
src0: ScalarSource,
|
||||
src1: ScalarSource,
|
||||
},
|
||||
/// SOPC 32-bit integer compare writing only SCC.
|
||||
ScalarCompare {
|
||||
op: ScalarCompareOp,
|
||||
src0: ScalarSource,
|
||||
src1: ScalarSource,
|
||||
},
|
||||
/// SOPK 32-bit integer operation on SDST (s0-s105, never s0-s7) and the
|
||||
/// 16-bit immediate `simm16`; `s_addk_i32` also writes SCC and
|
||||
/// `s_cmovk_i32` reads it.
|
||||
ScalarImmediate {
|
||||
op: ScalarImmediateOp,
|
||||
dst: u8,
|
||||
simm16: u16,
|
||||
},
|
||||
/// SOPK 32-bit integer compare of `src` (s0-s105) with the 16-bit
|
||||
/// immediate, writing only SCC.
|
||||
ScalarImmediateCompare {
|
||||
op: ScalarImmediateCompareOp,
|
||||
src: u8,
|
||||
simm16: u16,
|
||||
},
|
||||
/// VOPC integer compare writing a Wave32 mask to `vcc_lo`.
|
||||
/// For 64-bit forms register operands name pair bases and the immediate
|
||||
/// contains the low word of a sign-extended inline integer.
|
||||
VectorCompare {
|
||||
op: VectorCompareOp,
|
||||
src0: VectorSource,
|
||||
src1: u8,
|
||||
},
|
||||
/// VOP3A 32-bit integer compare writing a Wave32 mask to s0-s105 or `vcc_lo`.
|
||||
/// Both sources are VGPR indices.
|
||||
VectorCompareVop3 {
|
||||
op: VectorCompareVop3Op,
|
||||
sdst: u8,
|
||||
src0: u8,
|
||||
src1: u8,
|
||||
},
|
||||
/// VOP2 32-bit per-lane integer operation from the semantic registry.
|
||||
/// `src0` is a VGPR, `s0-s105`, `vcc_lo`, an inline integer or a literal;
|
||||
/// `src1` is a VGPR. Inactive lanes keep `dst`.
|
||||
VectorAlu {
|
||||
op: VectorAluOp,
|
||||
dst: u8,
|
||||
src0: VectorSource,
|
||||
src1: u8,
|
||||
},
|
||||
/// SOPP jump to a stream byte offset when SCC is clear.
|
||||
BranchSccZero { target: usize },
|
||||
/// SOPP jump when the Wave32 execution mask is empty.
|
||||
@@ -253,6 +130,18 @@ pub enum Instruction {
|
||||
BranchVccZero { target: usize },
|
||||
/// SOPP unconditional jump to a stream byte offset.
|
||||
Branch { target: usize },
|
||||
/// VOP2 logical left shift with the count in src0.
|
||||
VectorLshlrevB32 { dst: u8, src0: u8, src1: u8 },
|
||||
/// VOP2 logical right shift with the count in src0.
|
||||
VectorLshrrevB32 { dst: u8, src0: u8, src1: u8 },
|
||||
/// VOP2 arithmetic right shift with the count in src0.
|
||||
VectorAshrrevI32 { dst: u8, src0: u8, src1: u8 },
|
||||
/// VOP2 bitwise AND.
|
||||
VectorAndB32 { dst: u8, src0: u8, src1: u8 },
|
||||
/// VOP2 bitwise OR.
|
||||
VectorOrB32 { dst: u8, src0: u8, src1: u8 },
|
||||
/// VOP2 bitwise XOR.
|
||||
VectorXorB32 { dst: u8, src0: u8, src1: u8 },
|
||||
/// VOP2 single-precision addition. Execution requires an explicit FP mode.
|
||||
VectorAddF32 { dst: u8, src0: u8, src1: u8 },
|
||||
/// VOP2 single-precision multiplication. Execution requires an explicit FP mode.
|
||||
@@ -285,21 +174,6 @@ pub enum Instruction {
|
||||
EndProgram,
|
||||
}
|
||||
|
||||
/// Formats an SGPR destination with LLVM's names for the EXEC and VCC halves.
|
||||
struct ScalarDestination(u8);
|
||||
|
||||
impl fmt::Display for ScalarDestination {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self.0 {
|
||||
106 => formatter.write_str("vcc_lo"),
|
||||
107 => formatter.write_str("vcc_hi"),
|
||||
126 => formatter.write_str("exec_lo"),
|
||||
127 => formatter.write_str("exec_hi"),
|
||||
register => write!(formatter, "s{register}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Instruction {
|
||||
/// Returns the mnemonic for the exact encoding family represented.
|
||||
pub fn mnemonic(self) -> &'static str {
|
||||
@@ -309,21 +183,19 @@ impl Instruction {
|
||||
Self::WaitLoad => "s_waitcnt",
|
||||
Self::WaitStore => "s_waitcnt_vscnt",
|
||||
Self::MoveB32 { .. } => "v_mov_b32_e32",
|
||||
Self::VectorUnary { op, .. } => op.assembly_name(),
|
||||
Self::VectorSwap { op, .. } => op.assembly_name(),
|
||||
Self::VectorAluVop3 { op, .. } => op.assembly_name(),
|
||||
Self::ScalarUnary { op, .. } => op.mnemonic(),
|
||||
Self::ScalarAlu { op, .. } => op.mnemonic(),
|
||||
Self::ScalarCompare { op, .. } => op.mnemonic(),
|
||||
Self::ScalarImmediate { op, .. } => op.mnemonic(),
|
||||
Self::ScalarImmediateCompare { op, .. } => op.mnemonic(),
|
||||
Self::VectorCompare { op, .. } => op.assembly_name(),
|
||||
Self::VectorCompareVop3 { op, .. } => op.assembly_name(),
|
||||
Self::VectorAlu { op, .. } => op.assembly_name(),
|
||||
Self::AddNoCarryU32 { .. } => "v_add_nc_u32_e64",
|
||||
Self::ScalarMoveB32 { .. } => "s_mov_b32",
|
||||
Self::ScalarCompareEqU32 { .. } => "s_cmp_eq_u32",
|
||||
Self::BranchSccZero { .. } => "s_cbranch_scc0",
|
||||
Self::BranchExecZero { .. } => "s_cbranch_execz",
|
||||
Self::BranchVccZero { .. } => "s_cbranch_vccz",
|
||||
Self::Branch { .. } => "s_branch",
|
||||
Self::VectorLshlrevB32 { .. } => "v_lshlrev_b32_e32",
|
||||
Self::VectorLshrrevB32 { .. } => "v_lshrrev_b32_e32",
|
||||
Self::VectorAshrrevI32 { .. } => "v_ashrrev_i32_e32",
|
||||
Self::VectorAndB32 { .. } => "v_and_b32_e32",
|
||||
Self::VectorOrB32 { .. } => "v_or_b32_e32",
|
||||
Self::VectorXorB32 { .. } => "v_xor_b32_e32",
|
||||
Self::VectorAddF32 { .. } => "v_add_f32_e32",
|
||||
Self::VectorMulF32 { .. } => "v_mul_f32_e32",
|
||||
Self::Export { .. } => "exp",
|
||||
@@ -363,65 +235,26 @@ impl fmt::Display for Instruction {
|
||||
}
|
||||
Self::WaitLoad => formatter.write_str(" vmcnt(0)"),
|
||||
Self::WaitStore => formatter.write_str(" null, 0"),
|
||||
Self::MoveB32 { dst, src } | Self::VectorUnary { dst, src, .. } => {
|
||||
write!(formatter, " v{dst}, {src}")
|
||||
}
|
||||
Self::VectorSwap { dst, src, .. } => write!(formatter, " v{dst}, v{src}"),
|
||||
Self::VectorAluVop3 {
|
||||
dst, src0, src1, ..
|
||||
}
|
||||
Self::MoveB32 { dst, src } => write!(formatter, " v{dst}, {src}"),
|
||||
Self::AddNoCarryU32 { dst, src0, src1 }
|
||||
| Self::VectorLshlrevB32 { dst, src0, src1 }
|
||||
| Self::VectorLshrrevB32 { dst, src0, src1 }
|
||||
| Self::VectorAshrrevI32 { dst, src0, src1 }
|
||||
| Self::VectorAndB32 { dst, src0, src1 }
|
||||
| Self::VectorOrB32 { dst, src0, src1 }
|
||||
| Self::VectorXorB32 { dst, src0, src1 }
|
||||
| Self::VectorAddF32 { dst, src0, src1 }
|
||||
| Self::VectorMulF32 { dst, src0, src1 } => {
|
||||
write!(formatter, " v{dst}, v{src0}, v{src1}")
|
||||
}
|
||||
Self::ScalarUnary { dst, src, .. } => {
|
||||
write!(formatter, " {}, {src}", ScalarDestination(dst))
|
||||
}
|
||||
Self::ScalarAlu {
|
||||
dst, src0, src1, ..
|
||||
} => write!(formatter, " {}, {src0}, {src1}", ScalarDestination(dst)),
|
||||
Self::ScalarCompare { src0, src1, .. } => write!(formatter, " {src0}, {src1}"),
|
||||
Self::ScalarImmediate { dst, simm16, .. } => {
|
||||
write!(formatter, " s{dst}, {simm16:#x}")
|
||||
}
|
||||
Self::ScalarImmediateCompare { src, simm16, .. } => {
|
||||
write!(formatter, " s{src}, {simm16:#x}")
|
||||
}
|
||||
Self::VectorCompare { op, src0, src1 } if op.semantics().width == 64 => {
|
||||
formatter.write_str(" vcc_lo, ")?;
|
||||
match src0 {
|
||||
VectorSource::Register(base) => {
|
||||
write!(formatter, "v[{base}:{}]", u16::from(base) + 1)?;
|
||||
}
|
||||
VectorSource::Scalar(base) => {
|
||||
write!(formatter, "s[{base}:{}]", u16::from(base) + 1)?;
|
||||
}
|
||||
VectorSource::Immediate(bits) => write!(formatter, "{}", bits as i32)?,
|
||||
}
|
||||
write!(formatter, ", v[{src1}:{}]", u16::from(src1) + 1)
|
||||
}
|
||||
Self::VectorCompare { src0, src1, .. } => {
|
||||
write!(formatter, " vcc_lo, {src0}, v{src1}")
|
||||
}
|
||||
Self::VectorCompareVop3 {
|
||||
sdst, src0, src1, ..
|
||||
} => write!(formatter, " {}, v{src0}, v{src1}", ScalarDestination(sdst)),
|
||||
Self::VectorAlu {
|
||||
op,
|
||||
dst,
|
||||
src0,
|
||||
src1,
|
||||
} => {
|
||||
write!(formatter, " v{dst}, ")?;
|
||||
if op.writes_vcc() {
|
||||
write!(formatter, "vcc_lo, ")?;
|
||||
}
|
||||
write!(formatter, "{src0}, v{src1}")?;
|
||||
if op.reads_vcc() {
|
||||
write!(formatter, ", vcc_lo")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Self::ScalarMoveB32 { dst, src } => match dst {
|
||||
106 => write!(formatter, " vcc_lo, {src}"),
|
||||
107 => write!(formatter, " vcc_hi, {src}"),
|
||||
126 => write!(formatter, " exec_lo, {src}"),
|
||||
127 => write!(formatter, " exec_hi, {src}"),
|
||||
_ => write!(formatter, " s{dst}, {src}"),
|
||||
},
|
||||
Self::ScalarCompareEqU32 { src0, src1 } => write!(formatter, " {src0}, {src1}"),
|
||||
Self::Branch { target }
|
||||
| Self::BranchSccZero { target }
|
||||
| Self::BranchExecZero { target }
|
||||
|
||||
@@ -1,424 +0,0 @@
|
||||
//! Complete gfx1030 instruction metadata generated from AMD's public RDNA 2 XML.
|
||||
//!
|
||||
//! Identification here establishes an instruction's form and length only. It is
|
||||
//! not semantic support: [`crate::Instruction`] lists the forms Xenora executes.
|
||||
//! The XML names literal, SDWA, DPP and NSA variants without saying when they
|
||||
//! apply, so [`identify`] implements those length rules by hand from the RDNA 2
|
||||
//! ISA reference guide (see docs/research/rdna2.md).
|
||||
|
||||
use std::fmt;
|
||||
|
||||
pub use crate::rdna2_meta::{FIELDS, FORMS, SOURCE_SHA256};
|
||||
|
||||
/// AMD base encoding of an instruction form.
|
||||
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
|
||||
#[allow(missing_docs)]
|
||||
pub enum EncodingFamily {
|
||||
Ds,
|
||||
Exp,
|
||||
Flat,
|
||||
Global,
|
||||
Mimg,
|
||||
Mtbuf,
|
||||
Mubuf,
|
||||
Scratch,
|
||||
Smem,
|
||||
Sop1,
|
||||
Sop2,
|
||||
Sopc,
|
||||
Sopk,
|
||||
Sopp,
|
||||
Vintrp,
|
||||
Vop1,
|
||||
Vop2,
|
||||
Vop3,
|
||||
Vop3Sdst,
|
||||
Vop3p,
|
||||
Vopc,
|
||||
}
|
||||
|
||||
impl EncodingFamily {
|
||||
/// Every family, in table order.
|
||||
pub const ALL: [Self; 21] = [
|
||||
Self::Ds,
|
||||
Self::Exp,
|
||||
Self::Flat,
|
||||
Self::Global,
|
||||
Self::Mimg,
|
||||
Self::Mtbuf,
|
||||
Self::Mubuf,
|
||||
Self::Scratch,
|
||||
Self::Smem,
|
||||
Self::Sop1,
|
||||
Self::Sop2,
|
||||
Self::Sopc,
|
||||
Self::Sopk,
|
||||
Self::Sopp,
|
||||
Self::Vintrp,
|
||||
Self::Vop1,
|
||||
Self::Vop2,
|
||||
Self::Vop3,
|
||||
Self::Vop3Sdst,
|
||||
Self::Vop3p,
|
||||
Self::Vopc,
|
||||
];
|
||||
|
||||
/// Lower-case name used in reports.
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Ds => "ds",
|
||||
Self::Exp => "exp",
|
||||
Self::Flat => "flat",
|
||||
Self::Global => "global",
|
||||
Self::Mimg => "mimg",
|
||||
Self::Mtbuf => "mtbuf",
|
||||
Self::Mubuf => "mubuf",
|
||||
Self::Scratch => "scratch",
|
||||
Self::Smem => "smem",
|
||||
Self::Sop1 => "sop1",
|
||||
Self::Sop2 => "sop2",
|
||||
Self::Sopc => "sopc",
|
||||
Self::Sopk => "sopk",
|
||||
Self::Sopp => "sopp",
|
||||
Self::Vintrp => "vintrp",
|
||||
Self::Vop1 => "vop1",
|
||||
Self::Vop2 => "vop2",
|
||||
Self::Vop3 => "vop3",
|
||||
Self::Vop3Sdst => "vop3-sdst",
|
||||
Self::Vop3p => "vop3p",
|
||||
Self::Vopc => "vopc",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Control-flow flags recorded by the XML.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct FormFlags(pub u8);
|
||||
|
||||
impl FormFlags {
|
||||
#[allow(missing_docs)]
|
||||
pub const NONE: Self = Self(0);
|
||||
#[allow(missing_docs)]
|
||||
pub const BRANCH: Self = Self(1);
|
||||
#[allow(missing_docs)]
|
||||
pub const CONDITIONAL: Self = Self(2);
|
||||
#[allow(missing_docs)]
|
||||
pub const INDIRECT: Self = Self(4);
|
||||
#[allow(missing_docs)]
|
||||
pub const TERMINATOR: Self = Self(8);
|
||||
#[allow(missing_docs)]
|
||||
pub const IMMEDIATE: Self = Self(16);
|
||||
|
||||
/// Whether every flag in `other` is set.
|
||||
pub fn contains(self, other: Self) -> bool {
|
||||
self.0 & other.0 == other.0
|
||||
}
|
||||
}
|
||||
|
||||
/// Extension words an instruction form may carry.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct Extensions(pub u8);
|
||||
|
||||
impl Extensions {
|
||||
#[allow(missing_docs)]
|
||||
pub const NONE: Self = Self(0);
|
||||
/// A source field may select a trailing 32-bit literal.
|
||||
pub const LITERAL: Self = Self(1);
|
||||
/// The form always carries a trailing 32-bit literal.
|
||||
pub const ALWAYS_LITERAL: Self = Self(2);
|
||||
#[allow(missing_docs)]
|
||||
pub const SDWA: Self = Self(4);
|
||||
#[allow(missing_docs)]
|
||||
pub const DPP8: Self = Self(8);
|
||||
#[allow(missing_docs)]
|
||||
pub const DPP16: Self = Self(16);
|
||||
/// MIMG non-sequential address dwords.
|
||||
pub const NSA: Self = Self(32);
|
||||
|
||||
/// Whether every extension in `other` is allowed.
|
||||
pub fn contains(self, other: Self) -> bool {
|
||||
self.0 & other.0 == other.0
|
||||
}
|
||||
}
|
||||
|
||||
/// One encoded field: pieces of (bit offset, bit count), least significant piece first.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct FieldLayout {
|
||||
#[allow(missing_docs)]
|
||||
pub name: &'static str,
|
||||
#[allow(missing_docs)]
|
||||
pub pieces: &'static [(u8, u8)],
|
||||
}
|
||||
|
||||
impl FieldLayout {
|
||||
/// Extracts the field from the instruction's first two dwords.
|
||||
pub fn extract(&self, value: u64) -> u32 {
|
||||
let mut result = 0u64;
|
||||
let mut shift = 0;
|
||||
for &(offset, count) in self.pieces {
|
||||
result |= ((value >> offset) & ((1u64 << count) - 1)) << shift;
|
||||
shift += count;
|
||||
}
|
||||
result as u32
|
||||
}
|
||||
}
|
||||
|
||||
/// An operand as described by the XML.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
#[allow(missing_docs)]
|
||||
pub struct OperandInfo {
|
||||
pub field: &'static str,
|
||||
pub format: &'static str,
|
||||
pub kind: &'static str,
|
||||
pub bits: u16,
|
||||
pub input: bool,
|
||||
pub output: bool,
|
||||
pub implicit: bool,
|
||||
/// Whether the operand occupies microcode bits.
|
||||
pub encoded: bool,
|
||||
}
|
||||
|
||||
/// One instruction in one base encoding.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
#[allow(missing_docs)]
|
||||
pub struct Form {
|
||||
pub name: &'static str,
|
||||
pub family: EncodingFamily,
|
||||
pub opcode: u16,
|
||||
/// Identifying bits over the first two dwords (little-endian, first dword low).
|
||||
pub mask: u64,
|
||||
pub bits: u64,
|
||||
/// Base length before literal, SDWA, DPP or NSA words.
|
||||
pub bytes: u8,
|
||||
pub flags: FormFlags,
|
||||
pub extensions: Extensions,
|
||||
pub group: &'static str,
|
||||
pub operands: &'static [OperandInfo],
|
||||
}
|
||||
|
||||
impl Form {
|
||||
/// The base encoding's field layouts.
|
||||
pub fn fields(&self) -> &'static [FieldLayout] {
|
||||
FIELDS
|
||||
.iter()
|
||||
.find(|(family, _)| *family == self.family)
|
||||
.map(|(_, fields)| *fields)
|
||||
.unwrap_or(&[])
|
||||
}
|
||||
|
||||
/// The named field's layout, if the encoding has one.
|
||||
pub fn field(&self, name: &str) -> Option<&'static FieldLayout> {
|
||||
self.fields().iter().find(|field| field.name == name)
|
||||
}
|
||||
}
|
||||
|
||||
/// Which extension words an identified instruction carries.
|
||||
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
|
||||
pub struct Trailer {
|
||||
/// A 32-bit literal follows the base encoding.
|
||||
pub literal: bool,
|
||||
/// SDWA, DPP8 or DPP16 control dword (VOP1, VOP2, VOPC only).
|
||||
pub vector_control: Option<VectorControl>,
|
||||
/// Extra MIMG address dwords.
|
||||
pub nsa_dwords: u8,
|
||||
}
|
||||
|
||||
/// The dword that replaces SRC0 in a VOP1, VOP2 or VOPC instruction.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
#[allow(missing_docs)]
|
||||
pub enum VectorControl {
|
||||
Sdwa,
|
||||
Dpp8 { fetch_inactive: bool },
|
||||
Dpp16,
|
||||
}
|
||||
|
||||
/// An identified instruction.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct Identified {
|
||||
/// The matched form.
|
||||
pub form: &'static Form,
|
||||
/// First two dwords; the second is zero for 32-bit encodings.
|
||||
pub raw: u64,
|
||||
/// Total length in bytes, including extension words.
|
||||
pub len: usize,
|
||||
/// Extension words present.
|
||||
pub trailer: Trailer,
|
||||
}
|
||||
|
||||
impl Identified {
|
||||
/// Extracts a named field of the base encoding.
|
||||
pub fn field(&self, name: &str) -> Option<u32> {
|
||||
self.form.field(name).map(|field| field.extract(self.raw))
|
||||
}
|
||||
}
|
||||
|
||||
/// Why an instruction could not be identified.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum IdentifyError {
|
||||
/// Fewer bytes remain than the encoding or its extension words need.
|
||||
Truncated {
|
||||
/// Bytes required from the instruction start.
|
||||
needed: usize,
|
||||
},
|
||||
/// No gfx1030 form matches; the bits are reserved or belong to another architecture.
|
||||
Unassigned,
|
||||
/// The bits select an extension the form does not allow.
|
||||
InvalidExtension(&'static str),
|
||||
}
|
||||
|
||||
impl fmt::Display for IdentifyError {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::Truncated { needed } => write!(formatter, "truncated: needs {needed} bytes"),
|
||||
Self::Unassigned => formatter.write_str("no gfx1030 instruction has this encoding"),
|
||||
Self::InvalidExtension(what) => write!(formatter, "invalid extension: {what}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for IdentifyError {}
|
||||
|
||||
/// Source operand value selecting a trailing literal (XML `SRC_LITERAL`).
|
||||
pub const SRC_LITERAL: u32 = 255;
|
||||
/// VOP1/VOP2/VOPC SRC0 value selecting an SDWA control dword.
|
||||
pub const SRC_SDWA: u32 = 0xf9;
|
||||
/// VOP1/VOP2/VOPC SRC0 value selecting a DPP16 control dword.
|
||||
pub const SRC_DPP16: u32 = 0xfa;
|
||||
/// VOP1/VOP2/VOPC SRC0 value selecting a DPP8 control dword.
|
||||
pub const SRC_DPP8: u32 = 0xe9;
|
||||
/// DPP8 with fetch-inactive set.
|
||||
pub const SRC_DPP8_FI: u32 = 0xea;
|
||||
|
||||
fn read_dword(bytes: &[u8], index: usize) -> Option<u32> {
|
||||
let start = index.checked_mul(4)?;
|
||||
let chunk = bytes.get(start..start.checked_add(4)?)?;
|
||||
Some(u32::from_le_bytes(chunk.try_into().ok()?))
|
||||
}
|
||||
|
||||
/// Finds the form whose identifying bits match.
|
||||
///
|
||||
/// Masks never overlap ambiguously; the generator rejects such tables.
|
||||
pub fn lookup(raw: u64) -> Option<&'static Form> {
|
||||
FORMS.iter().find(|form| raw & form.mask == form.bits)
|
||||
}
|
||||
|
||||
/// Identifies the instruction at the start of `bytes` and computes its length.
|
||||
pub fn identify(bytes: &[u8]) -> Result<Identified, IdentifyError> {
|
||||
let first = read_dword(bytes, 0).ok_or(IdentifyError::Truncated { needed: 4 })?;
|
||||
let second = read_dword(bytes, 1);
|
||||
let raw_guess = u64::from(first) | (u64::from(second.unwrap_or(0)) << 32);
|
||||
// A 32-bit form never inspects the second dword; a 64-bit form needs it.
|
||||
let form = FORMS
|
||||
.iter()
|
||||
.find(|form| (form.bytes == 4 || second.is_some()) && raw_guess & form.mask == form.bits)
|
||||
.or_else(|| {
|
||||
// Distinguish a truncated 64-bit instruction from unassigned bits.
|
||||
FORMS.iter().find(|form| {
|
||||
form.bytes == 8
|
||||
&& u64::from(first) & form.mask & 0xffff_ffff == form.bits & 0xffff_ffff
|
||||
})
|
||||
})
|
||||
.ok_or(IdentifyError::Unassigned)?;
|
||||
if form.bytes == 8 && second.is_none() {
|
||||
return Err(IdentifyError::Truncated { needed: 8 });
|
||||
}
|
||||
let raw = if form.bytes == 4 {
|
||||
u64::from(first)
|
||||
} else {
|
||||
raw_guess
|
||||
};
|
||||
let mut trailer = Trailer::default();
|
||||
let source = |name: &str| form.field(name).map(|field| field.extract(raw));
|
||||
match form.family {
|
||||
EncodingFamily::Sop1 | EncodingFamily::Sop2 | EncodingFamily::Sopc => {
|
||||
trailer.literal = [source("SSRC0"), source("SSRC1")]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.any(|value| value == SRC_LITERAL);
|
||||
}
|
||||
EncodingFamily::Vop1 | EncodingFamily::Vop2 | EncodingFamily::Vopc => {
|
||||
match source("SRC0") {
|
||||
Some(SRC_LITERAL) => trailer.literal = true,
|
||||
Some(SRC_SDWA) => trailer.vector_control = Some(VectorControl::Sdwa),
|
||||
Some(SRC_DPP16) => trailer.vector_control = Some(VectorControl::Dpp16),
|
||||
Some(SRC_DPP8) => {
|
||||
trailer.vector_control = Some(VectorControl::Dpp8 {
|
||||
fetch_inactive: false,
|
||||
})
|
||||
}
|
||||
Some(SRC_DPP8_FI) => {
|
||||
trailer.vector_control = Some(VectorControl::Dpp8 {
|
||||
fetch_inactive: true,
|
||||
})
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
EncodingFamily::Vop3 | EncodingFamily::Vop3Sdst | EncodingFamily::Vop3p => {
|
||||
// An attribute field (XML OPR_ATTR) is not an operand selector: in the
|
||||
// VOP3 interpolation forms SRC0 holds {attr_word, attr_chan, attr}
|
||||
// bit-fields (AMD RDNA 2 ISA guide, section 10.4.2), so 255 there
|
||||
// does not select a literal.
|
||||
trailer.literal = ["SRC0", "SRC1", "SRC2"]
|
||||
.into_iter()
|
||||
.filter(|name| {
|
||||
!form
|
||||
.operands
|
||||
.iter()
|
||||
.any(|operand| operand.field == *name && operand.kind == "OPR_ATTR")
|
||||
})
|
||||
.filter_map(source)
|
||||
.any(|value| value == SRC_LITERAL);
|
||||
}
|
||||
EncodingFamily::Mimg => {
|
||||
trailer.nsa_dwords = source("NSA").unwrap_or(0) as u8;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if form.extensions.contains(Extensions::ALWAYS_LITERAL) {
|
||||
trailer.literal = true;
|
||||
} else if trailer.literal && !form.extensions.contains(Extensions::LITERAL) {
|
||||
return Err(IdentifyError::InvalidExtension("literal"));
|
||||
}
|
||||
match trailer.vector_control {
|
||||
Some(VectorControl::Sdwa) if !form.extensions.contains(Extensions::SDWA) => {
|
||||
return Err(IdentifyError::InvalidExtension("sdwa"));
|
||||
}
|
||||
Some(VectorControl::Dpp8 { .. }) if !form.extensions.contains(Extensions::DPP8) => {
|
||||
return Err(IdentifyError::InvalidExtension("dpp8"));
|
||||
}
|
||||
Some(VectorControl::Dpp16) if !form.extensions.contains(Extensions::DPP16) => {
|
||||
return Err(IdentifyError::InvalidExtension("dpp16"));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if trailer.nsa_dwords > 0 && !form.extensions.contains(Extensions::NSA) {
|
||||
return Err(IdentifyError::InvalidExtension("nsa"));
|
||||
}
|
||||
let len = usize::from(form.bytes)
|
||||
+ 4 * usize::from(trailer.literal)
|
||||
+ 4 * usize::from(trailer.vector_control.is_some())
|
||||
+ 4 * usize::from(trailer.nsa_dwords);
|
||||
if bytes.len() < len {
|
||||
return Err(IdentifyError::Truncated { needed: len });
|
||||
}
|
||||
Ok(Identified {
|
||||
form,
|
||||
raw,
|
||||
len,
|
||||
trailer,
|
||||
})
|
||||
}
|
||||
|
||||
/// Number of forms per encoding family in the metadata.
|
||||
pub fn inventory() -> Vec<(EncodingFamily, usize)> {
|
||||
EncodingFamily::ALL
|
||||
.iter()
|
||||
.map(|&family| {
|
||||
(
|
||||
family,
|
||||
FORMS.iter().filter(|form| form.family == family).count(),
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -1,338 +0,0 @@
|
||||
//! 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)
|
||||
}
|
||||
|
||||
/// Bitwise `a & !b` and whether the result is nonzero.
|
||||
pub const fn andn2_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
|
||||
let value = a & !b;
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Bitwise `a | !b` and whether the result is nonzero.
|
||||
pub const fn orn2_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
|
||||
let value = a | !b;
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Bitwise `!(a & b)` and whether the result is nonzero.
|
||||
pub const fn nand_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
|
||||
let value = !(a & b);
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Bitwise `!(a | b)` and whether the result is nonzero.
|
||||
pub const fn nor_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
|
||||
let value = !(a | b);
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Bitwise `!(a ^ b)` and whether the result is nonzero.
|
||||
pub const fn xnor_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
|
||||
let value = !(a ^ b);
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// `a << count` and whether the result is nonzero. The caller masks the count
|
||||
/// to the declared count width, so `count` is below 32.
|
||||
pub const fn lshl_nonzero_b32(a: u32, count: u32) -> (u32, bool) {
|
||||
let value = a << count;
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Logical `a >> count` (zero fill) and whether the result is nonzero; `count` is below 32.
|
||||
pub const fn lshr_nonzero_b32(a: u32, count: u32) -> (u32, bool) {
|
||||
let value = a >> count;
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Arithmetic `a >> count` (sign fill) and whether the result is nonzero; `count` is below 32.
|
||||
pub const fn ashr_nonzero_i32(a: u32, count: u32) -> (u32, bool) {
|
||||
let value = ((a as i32) >> count) as u32;
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// The VOPC F test: false for every operand pair.
|
||||
pub const fn false_b32(_a: u32, _b: u32) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// The VOPC T test: true for every operand pair.
|
||||
pub const fn true_b32(_a: u32, _b: u32) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// `a == b` on the raw bits; signedness does not matter for equality.
|
||||
pub const fn eq_b32(a: u32, b: u32) -> bool {
|
||||
a == b
|
||||
}
|
||||
|
||||
/// `a != b` on the raw bits (the guide's LG, "less or greater").
|
||||
pub const fn ne_b32(a: u32, b: u32) -> bool {
|
||||
a != b
|
||||
}
|
||||
|
||||
/// Two's-complement `a > b`.
|
||||
pub const fn gt_i32(a: u32, b: u32) -> bool {
|
||||
(a as i32) > (b as i32)
|
||||
}
|
||||
|
||||
/// Two's-complement `a >= b`.
|
||||
pub const fn ge_i32(a: u32, b: u32) -> bool {
|
||||
(a as i32) >= (b as i32)
|
||||
}
|
||||
|
||||
/// Two's-complement `a < b`.
|
||||
pub const fn lt_i32(a: u32, b: u32) -> bool {
|
||||
(a as i32) < (b as i32)
|
||||
}
|
||||
|
||||
/// Two's-complement `a <= b`.
|
||||
pub const fn le_i32(a: u32, b: u32) -> bool {
|
||||
(a as i32) <= (b as i32)
|
||||
}
|
||||
|
||||
/// Unsigned `a > b`.
|
||||
pub const fn gt_u32(a: u32, b: u32) -> bool {
|
||||
a > b
|
||||
}
|
||||
|
||||
/// Unsigned `a >= b`.
|
||||
pub const fn ge_u32(a: u32, b: u32) -> bool {
|
||||
a >= b
|
||||
}
|
||||
|
||||
/// Unsigned `a < b`.
|
||||
pub const fn lt_u32(a: u32, b: u32) -> bool {
|
||||
a < b
|
||||
}
|
||||
|
||||
/// Unsigned `a <= b`.
|
||||
pub const fn le_u32(a: u32, b: u32) -> bool {
|
||||
a <= b
|
||||
}
|
||||
|
||||
/// `!a` and whether the result is nonzero.
|
||||
pub const fn not_nonzero_b32(a: u32) -> (u32, bool) {
|
||||
let value = !a;
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// `a` with bit `i` moved to bit `31 - i`.
|
||||
pub const fn brev_b32(a: u32) -> u32 {
|
||||
a.reverse_bits()
|
||||
}
|
||||
|
||||
/// Number of zero bits and whether that count is nonzero.
|
||||
pub const fn bcnt0_nonzero_b32(a: u32) -> (u32, bool) {
|
||||
let value = a.count_zeros();
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Number of one bits and whether that count is nonzero.
|
||||
pub const fn bcnt1_nonzero_b32(a: u32) -> (u32, bool) {
|
||||
let value = a.count_ones();
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Index of the lowest zero bit, or `0xffffffff` (-1) when every bit is one.
|
||||
pub const fn ff0_b32(a: u32) -> u32 {
|
||||
if a == u32::MAX {
|
||||
u32::MAX
|
||||
} else {
|
||||
a.trailing_ones()
|
||||
}
|
||||
}
|
||||
|
||||
/// Index of the lowest one bit, or `0xffffffff` (-1) when every bit is zero.
|
||||
pub const fn ff1_b32(a: u32) -> u32 {
|
||||
if a == 0 { u32::MAX } else { a.trailing_zeros() }
|
||||
}
|
||||
|
||||
/// Zeros above the highest one bit, or `0xffffffff` (-1) when `a` is zero.
|
||||
pub const fn flbit_b32(a: u32) -> u32 {
|
||||
if a == 0 { u32::MAX } else { a.leading_zeros() }
|
||||
}
|
||||
|
||||
/// Bits above the highest bit that differs from the sign bit, or `0xffffffff`
|
||||
/// (-1) when every bit equals the sign bit (`a` is 0 or -1).
|
||||
pub const fn flbit_i32(a: u32) -> u32 {
|
||||
let differing = if a >> 31 == 0 { a } else { !a };
|
||||
if differing == 0 {
|
||||
u32::MAX
|
||||
} else {
|
||||
differing.leading_zeros()
|
||||
}
|
||||
}
|
||||
|
||||
/// The low `bits` of `a` sign-extended to 32 bits; `bits` is 8 or 16.
|
||||
pub const fn sext_i32(a: u32, bits: u32) -> u32 {
|
||||
let shift = 32 - bits;
|
||||
(((a << shift) as i32) >> shift) as u32
|
||||
}
|
||||
|
||||
/// SIMM16 sign-extended to 32 bits (SOPK, guide 12.2).
|
||||
pub const fn sext_simm16(simm16: u16) -> u32 {
|
||||
simm16 as i16 as i32 as u32
|
||||
}
|
||||
|
||||
/// Two's-complement absolute value (wrapping, so `0x80000000` stays) and
|
||||
/// whether the result is nonzero.
|
||||
pub const fn abs_nonzero_i32(a: u32) -> (u32, bool) {
|
||||
let value = (a as i32).wrapping_abs() as u32;
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Two's-complement minimum and whether S0 was strictly smaller (so equal
|
||||
/// operands give S1 and `false`).
|
||||
pub const fn min_i32(a: u32, b: u32) -> (u32, bool) {
|
||||
let first = (a as i32) < (b as i32);
|
||||
(if first { a } else { b }, first)
|
||||
}
|
||||
|
||||
/// Unsigned minimum and whether S0 was strictly smaller.
|
||||
pub const fn min_u32(a: u32, b: u32) -> (u32, bool) {
|
||||
let first = a < b;
|
||||
(if first { a } else { b }, first)
|
||||
}
|
||||
|
||||
/// Two's-complement maximum and whether S0 was strictly greater (so equal
|
||||
/// operands give S1 and `false`).
|
||||
pub const fn max_i32(a: u32, b: u32) -> (u32, bool) {
|
||||
let first = (a as i32) > (b as i32);
|
||||
(if first { a } else { b }, first)
|
||||
}
|
||||
|
||||
/// Unsigned maximum and whether S0 was strictly greater.
|
||||
pub const fn max_u32(a: u32, b: u32) -> (u32, bool) {
|
||||
let first = a > b;
|
||||
(if first { a } else { b }, first)
|
||||
}
|
||||
|
||||
/// `a` when `condition` (SCC) is set, otherwise `b`.
|
||||
pub const fn cselect_b32(a: u32, b: u32, condition: bool) -> u32 {
|
||||
if condition { a } else { b }
|
||||
}
|
||||
|
||||
/// `((1 << a[4:0]) - 1) << b[4:0]`: a mask of `a[4:0]` ones starting at bit `b[4:0]`.
|
||||
pub const fn bfm_b32(a: u32, b: u32) -> u32 {
|
||||
((1u32 << (a & 0x1f)) - 1) << (b & 0x1f)
|
||||
}
|
||||
|
||||
/// The low 32 bits of the product (identical for signed and unsigned operands).
|
||||
pub const fn mul_lo_i32(a: u32, b: u32) -> u32 {
|
||||
a.wrapping_mul(b)
|
||||
}
|
||||
|
||||
/// The high 32 bits of the unsigned 64-bit product.
|
||||
pub const fn mul_hi_u32(a: u32, b: u32) -> u32 {
|
||||
((a as u64 * b as u64) >> 32) as u32
|
||||
}
|
||||
|
||||
/// The high 32 bits of the two's-complement 64-bit product.
|
||||
pub const fn mul_hi_i32(a: u32, b: u32) -> u32 {
|
||||
((a as i32 as i64 * b as i32 as i64) >> 32) as u32
|
||||
}
|
||||
|
||||
/// The `bfe` field descriptor: offset `b[4:0]` and width `b[22:16]` (0-127).
|
||||
const fn bfe_field(b: u32) -> (u32, u32) {
|
||||
(b & 0x1f, (b >> 16) & 0x7f)
|
||||
}
|
||||
|
||||
/// Unsigned bit-field extract: `(a >> offset) & ((1 << width) - 1)`, where a
|
||||
/// width of 32 or more keeps every shifted bit; and whether the result is nonzero.
|
||||
pub const fn bfe_nonzero_u32(a: u32, b: u32) -> (u32, bool) {
|
||||
let (offset, width) = bfe_field(b);
|
||||
let shifted = a >> offset;
|
||||
let value = if width == 0 {
|
||||
0
|
||||
} else if width >= 32 {
|
||||
shifted
|
||||
} else {
|
||||
shifted & ((1 << width) - 1)
|
||||
};
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Signed bit-field extract: `a` shifted arithmetically by the offset, the low
|
||||
/// `width` bits kept and sign-extended from bit `width - 1` (a width of 32 or
|
||||
/// more keeps the whole shifted word); and whether the result is nonzero.
|
||||
pub const fn bfe_nonzero_i32(a: u32, b: u32) -> (u32, bool) {
|
||||
let (offset, width) = bfe_field(b);
|
||||
let shifted = ((a as i32) >> offset) as u32;
|
||||
let value = if width == 0 {
|
||||
0
|
||||
} else if width >= 32 {
|
||||
shifted
|
||||
} else {
|
||||
let unused = 32 - width;
|
||||
(((shifted << unused) as i32) >> unused) as u32
|
||||
};
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// `|a - b|` of the wrapped 32-bit difference (so `0x80000000` stays) and
|
||||
/// whether the result is nonzero.
|
||||
pub const fn absdiff_nonzero_i32(a: u32, b: u32) -> (u32, bool) {
|
||||
let value = (a.wrapping_sub(b) as i32).unsigned_abs();
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// `(a << shift) + b` and the carry out of the exact sum, which counts the bits
|
||||
/// shifted out of `a`; `shift` is 1 to 4.
|
||||
pub const fn lshl_add_carry_u32(a: u32, b: u32, shift: u32) -> (u32, bool) {
|
||||
let sum = ((a as u64) << shift) + b as u64;
|
||||
(sum as u32, sum >> 32 != 0)
|
||||
}
|
||||
|
||||
/// A bitwise copy of the source (RDNA 2 guide section 12.3).
|
||||
pub(crate) const fn mov_b32(src: u32) -> u32 {
|
||||
src
|
||||
}
|
||||
+5
-60
@@ -45,6 +45,11 @@ pub const S_MOV_B32: Opcode = Opcode {
|
||||
bits: 0xbe800300,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const S_CMP_EQ_U32: Opcode = Opcode {
|
||||
mask: 0xffff0000,
|
||||
bits: 0xbf060000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const S_CBRANCH_SCC0: Opcode = Opcode {
|
||||
mask: 0xffff0000,
|
||||
bits: 0xbf840000,
|
||||
@@ -105,66 +110,6 @@ pub const V_MUL_F32: Opcode = Opcode {
|
||||
bits: 0x10000000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const V_CMP_LT_I32: Opcode = Opcode {
|
||||
mask: 0xfffe0000,
|
||||
bits: 0x7d020000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const V_CMP_EQ_I32: Opcode = Opcode {
|
||||
mask: 0xfffe0000,
|
||||
bits: 0x7d040000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const V_CMP_LE_I32: Opcode = Opcode {
|
||||
mask: 0xfffe0000,
|
||||
bits: 0x7d060000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const V_CMP_GT_I32: Opcode = Opcode {
|
||||
mask: 0xfffe0000,
|
||||
bits: 0x7d080000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const V_CMP_NE_I32: Opcode = Opcode {
|
||||
mask: 0xfffe0000,
|
||||
bits: 0x7d0a0000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const V_CMP_GE_I32: Opcode = Opcode {
|
||||
mask: 0xfffe0000,
|
||||
bits: 0x7d0c0000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const V_CMP_LT_U32: Opcode = Opcode {
|
||||
mask: 0xfffe0000,
|
||||
bits: 0x7d820000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const V_CMP_EQ_U32: Opcode = Opcode {
|
||||
mask: 0xfffe0000,
|
||||
bits: 0x7d840000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const V_CMP_LE_U32: Opcode = Opcode {
|
||||
mask: 0xfffe0000,
|
||||
bits: 0x7d860000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const V_CMP_GT_U32: Opcode = Opcode {
|
||||
mask: 0xfffe0000,
|
||||
bits: 0x7d880000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const V_CMP_NE_U32: Opcode = Opcode {
|
||||
mask: 0xfffe0000,
|
||||
bits: 0x7d8a0000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const V_CMP_GE_U32: Opcode = Opcode {
|
||||
mask: 0xfffe0000,
|
||||
bits: 0x7d8c0000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const EXP: Opcode = Opcode {
|
||||
mask: 0xfc000000,
|
||||
bits: 0xf8000000,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,385 +0,0 @@
|
||||
//! 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::CompareRelation;
|
||||
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,
|
||||
/// Bitwise AND with the complement of S1.
|
||||
AndNot,
|
||||
/// Bitwise OR with the complement of S1.
|
||||
OrNot,
|
||||
/// Complement of bitwise AND.
|
||||
Nand,
|
||||
/// Complement of bitwise OR.
|
||||
Nor,
|
||||
/// Complement of bitwise exclusive OR.
|
||||
Xnor,
|
||||
/// Shift S0 left by the masked count in S1, filling with zeros.
|
||||
ShiftLeft,
|
||||
/// Shift S0 right by the masked count in S1, filling with zeros.
|
||||
LogicalShiftRight,
|
||||
/// Shift S0 right by the masked count in S1, filling with its sign bit.
|
||||
ArithmeticShiftRight,
|
||||
/// Compare S0 with S1 under the form's relation, producing SCC or a lane mask.
|
||||
Compare,
|
||||
/// Bitwise complement of S0.
|
||||
Not,
|
||||
/// S0 with its bit order reversed.
|
||||
ReverseBits,
|
||||
/// Number of zero bits in S0.
|
||||
CountZeros,
|
||||
/// Number of one bits in S0.
|
||||
CountOnes,
|
||||
/// Index of the lowest zero bit of S0, or -1 when there is none.
|
||||
FindFirstZero,
|
||||
/// Index of the lowest one bit of S0, or -1 when there is none.
|
||||
FindFirstOne,
|
||||
/// Unsigned: count of zeros above the highest one bit; signed: count of bits
|
||||
/// above the highest bit that differs from the sign bit. -1 when none.
|
||||
FindLastBit,
|
||||
/// Sign-extend the low `source_bits` of S0 to 32 bits.
|
||||
SignExtend,
|
||||
/// Two's-complement absolute value; the most negative value maps to itself.
|
||||
Absolute,
|
||||
/// S0 when it is strictly less than S1, otherwise S1.
|
||||
Minimum,
|
||||
/// S0 when it is strictly greater than S1, otherwise S1.
|
||||
Maximum,
|
||||
/// S0 when SCC is set, otherwise S1.
|
||||
Select,
|
||||
/// `((1 << S0[4:0]) - 1) << S1[4:0]`.
|
||||
BitfieldMask,
|
||||
/// Low 32 bits of the product.
|
||||
Multiply,
|
||||
/// High 32 bits of the 64-bit product.
|
||||
MultiplyHigh,
|
||||
/// The field of S0 at offset S1[4:0] with width S1[22:16]; sign-extended when signed.
|
||||
BitfieldExtract,
|
||||
/// Absolute value of the wrapped 32-bit difference S0 - S1.
|
||||
AbsoluteDifference,
|
||||
/// `(S0 << shift_amount) + S1`.
|
||||
ShiftLeftAdd,
|
||||
/// Low 32 bits of the product of S0[23:0] and S1[23:0] (sign-extended when signed).
|
||||
Multiply24,
|
||||
/// Bits 63:32 of the product of S0[23:0] and S1[23:0] (sign-extended when signed).
|
||||
MultiplyHigh24,
|
||||
/// SOPK: SDST receives the sign-extended SIMM16.
|
||||
Move,
|
||||
/// SOPK: SDST receives the sign-extended SIMM16 when SCC is set.
|
||||
ConditionalMove,
|
||||
/// Terminate the program.
|
||||
EndProgram,
|
||||
/// Unconditional PC-relative branch.
|
||||
Branch,
|
||||
/// Branch when SCC is clear.
|
||||
BranchSccZero,
|
||||
/// Branch when VCC is zero.
|
||||
BranchVccZero,
|
||||
/// Branch when EXEC is zero.
|
||||
BranchExecZero,
|
||||
/// Complete an outstanding vector load.
|
||||
WaitLoad,
|
||||
/// Swap the two old per-lane VGPR values (guide 12.8).
|
||||
Swap,
|
||||
}
|
||||
|
||||
/// Per-lane integer operation with one input and one result.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum VectorUnary {
|
||||
/// Bitwise complement.
|
||||
Not,
|
||||
/// Reverse bit order.
|
||||
ReverseBits,
|
||||
/// Count leading zeros, or return all ones for zero.
|
||||
FindHighUnsigned,
|
||||
/// Count trailing zeros, or return all ones for zero.
|
||||
FindLow,
|
||||
/// Count leading sign bits, or return all ones if every bit matches.
|
||||
FindHighSigned,
|
||||
}
|
||||
|
||||
/// The per-lane integer operation a vector form lowers to. One reusable MSL
|
||||
/// template exists per variant; a form selects it through its declared
|
||||
/// operation and signedness, never through its opcode.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum VectorBinary {
|
||||
/// Wrapping `a + b`.
|
||||
Add,
|
||||
/// Wrapping `a - b`.
|
||||
Sub,
|
||||
/// `!(a ^ b)`.
|
||||
Xnor,
|
||||
/// Two's-complement minimum.
|
||||
MinSigned,
|
||||
/// Unsigned minimum.
|
||||
MinUnsigned,
|
||||
/// Two's-complement maximum.
|
||||
MaxSigned,
|
||||
/// Unsigned maximum.
|
||||
MaxUnsigned,
|
||||
/// Low 32 bits of `sext(a[23:0]) * sext(b[23:0])`.
|
||||
Mul24Signed,
|
||||
/// Low 32 bits of `a[23:0] * b[23:0]`.
|
||||
Mul24Unsigned,
|
||||
/// Bits 63:32 of `sext(a[23:0]) * sext(b[23:0])`.
|
||||
MulHi24Signed,
|
||||
/// Bits 63:32 of `a[23:0] * b[23:0]`.
|
||||
MulHi24Unsigned,
|
||||
/// `a & b`.
|
||||
And,
|
||||
/// `a | b`.
|
||||
Or,
|
||||
/// `a ^ b`.
|
||||
Xor,
|
||||
/// `a << (b & 31)`.
|
||||
ShiftLeft,
|
||||
/// Logical `a >> (b & 31)`.
|
||||
ShiftRight,
|
||||
/// Arithmetic (sign-filling) `a >> (b & 31)`.
|
||||
ArithmeticShiftRight,
|
||||
}
|
||||
|
||||
/// How the operands are interpreted. `Bitwise` exactly when the operation is logical.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum Signedness {
|
||||
/// Unsigned integers.
|
||||
Unsigned,
|
||||
/// Two's-complement integers.
|
||||
Signed,
|
||||
/// Untyped bits.
|
||||
Bitwise,
|
||||
}
|
||||
|
||||
/// Per-lane VOP2 operation selected by the semantic registry.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum VectorLowering {
|
||||
/// Two explicit operands, with no implicit lane input.
|
||||
Binary(VectorBinary),
|
||||
/// Two explicit operands and the lane's VCC bit.
|
||||
Vcc(VectorVcc),
|
||||
}
|
||||
|
||||
/// VOP2 primitives with an implicit per-lane VCC input.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum VectorVcc {
|
||||
/// Choose S1 when the VCC bit is set, otherwise S0.
|
||||
Select,
|
||||
/// Unsigned addition with carry-in and carry-out.
|
||||
AddCarry,
|
||||
/// Unsigned subtraction with borrow-in and borrow-out.
|
||||
SubtractBorrow,
|
||||
}
|
||||
|
||||
/// Implicit condition or carry input.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum CarryIn {
|
||||
/// No implicit condition or carry input.
|
||||
None,
|
||||
/// SCC as carry-in (add), borrow-in (sub) or the select condition (select).
|
||||
Scc,
|
||||
/// Per-lane Wave32 VCC_LO bit.
|
||||
Vcc,
|
||||
}
|
||||
|
||||
/// 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,
|
||||
/// The compare's relation holds for S0 and S1.
|
||||
Relation,
|
||||
/// The result is S0 by the strict comparison (min, max): equal operands give 0.
|
||||
SelectedSrc0,
|
||||
}
|
||||
|
||||
/// Where a form writes its lane mask, if any.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum MaskEffect {
|
||||
/// Not written.
|
||||
Unchanged,
|
||||
/// Wave32 VOPC result (VCC only): `VCC_LO` bit n is EXEC[n] & (lane n
|
||||
/// exists) & test(lane n), fully written; `VCC_HI` has no known value after
|
||||
/// it (docs/shaders/vector-compare.md section 3).
|
||||
LaneMask,
|
||||
/// Wave32 VOP3A compare mask written to SDST, which may be `vcc_lo`.
|
||||
SdstLaneMask,
|
||||
}
|
||||
|
||||
/// 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,
|
||||
/// SOPC: no destination; SSRC0/SSRC1 as for SOP2 sources (s0-s105, inline
|
||||
/// integers -16..64 or one literal word). Everything else is rejected.
|
||||
SopcScalar,
|
||||
/// SOP1 unary: SDST is s0-s105; SSRC0 is s0-s105, an inline integer -16..64 or
|
||||
/// a literal word. Everything else is rejected as unsupported.
|
||||
Sop1Sgpr,
|
||||
/// SOP1 move: the same sources as Sop1Sgpr, with VCC and EXEC halves
|
||||
/// also allowed as explicit destinations.
|
||||
Sop1Move,
|
||||
/// SOPK integer: SDST is s0-s105 and, except for compares, written (never s0-s7,
|
||||
/// which hold resource descriptors); SIMM16 is the 16-bit immediate. The word
|
||||
/// never takes a literal. Everything else is rejected as unsupported.
|
||||
SopkSgpr,
|
||||
/// SOPK integer compare: SDST (s0-s105) is the left operand, SIMM16 the right
|
||||
/// (sign-extended for `_i32`, zero-extended for `_u32`); only SCC is written.
|
||||
SopkCompare,
|
||||
/// SOPP termination with zero in the reserved immediate field.
|
||||
SoppEnd,
|
||||
/// SOPP branch with a signed dword displacement from the next instruction.
|
||||
SoppBranch,
|
||||
/// SOPP wait with exactly vmcnt(0) and the other counters disabled.
|
||||
SoppWait,
|
||||
/// VOPC vector compare: the destination is `vcc_lo` (Wave32); SRC0 is a VGPR,
|
||||
/// s0-s105, `vcc_lo`, an inline integer -16..64 or a literal word; VSRC1 is a
|
||||
/// VGPR. Everything else is rejected as unsupported.
|
||||
VopcVcc,
|
||||
/// Wave32 VOPC with a VGPR pair, even normal SGPR pair or inline integer
|
||||
/// as SRC0 and a VGPR pair as VSRC1. The destination is `vcc_lo`.
|
||||
VopcVccPair,
|
||||
/// VOPC with low-half operands and no literal selector.
|
||||
VopcVccHalf,
|
||||
/// VOP3 encoding of a VOP2 vector form: VDST is v0-v255, SRC0 and SRC1 are
|
||||
/// VGPRs, no input or output modifiers, SRC2 unused. Everything else is
|
||||
/// rejected as unsupported.
|
||||
Vop3Vgpr2,
|
||||
/// VOP3A compare: VDST encodes s0-s105 or `vcc_lo`; SRC0 and SRC1 are
|
||||
/// VGPRs, SRC2 is unused and all modifiers are clear.
|
||||
Vop3CmpVgpr2,
|
||||
/// VOP2 vector: VDST is v0-v255; SRC0 is a VGPR, s0-s105, `vcc_lo`, an inline
|
||||
/// integer -16..64 or a literal word; VSRC1 is a VGPR. Everything else is
|
||||
/// rejected as unsupported.
|
||||
Vop2Vgpr,
|
||||
/// VOP2 general SRC0 and VGPR VSRC1 with an implicit VCC_LO input.
|
||||
Vop2Vcc,
|
||||
/// VOP2 vector, VGPR sources only: VDST is v0-v255; SRC0 and VSRC1 are VGPRs.
|
||||
/// Everything else (SGPR, inline, literal SRC0) is rejected as unsupported.
|
||||
Vop2Vgpr2,
|
||||
/// VOP1 unary: VGPR VDST and the same SRC0 domain as VOP2.
|
||||
Vop1Vgpr,
|
||||
/// VOP1 swap: VDST and SRC0 each read and write a VGPR.
|
||||
Vop1Swap,
|
||||
}
|
||||
|
||||
/// 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, or 0 when the page has not been recorded.
|
||||
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,
|
||||
/// SCC input.
|
||||
pub carry_in: CarryIn,
|
||||
/// Operand and result width in bits.
|
||||
pub width: u8,
|
||||
/// Low bits of S1 used as the shift count by shift operations; 0 otherwise.
|
||||
pub shift_count_bits: u8,
|
||||
/// Fixed left shift of S0 for shift-and-add operations (1 to 4); 0 otherwise.
|
||||
pub shift_amount: u8,
|
||||
/// Whether the operation reads its sources in reverse order (`D = op(S1, S0)`).
|
||||
pub swap_sources: bool,
|
||||
/// Low bits of S0 that the operation reads: `width`, or 8 or 16 for sign extension.
|
||||
pub source_bits: u8,
|
||||
/// The relation tested by compares (S0 on the left); `None` otherwise.
|
||||
pub relation: Option<CompareRelation>,
|
||||
/// SCC write.
|
||||
pub scc: SccEffect,
|
||||
/// Implicit VCC write or explicit scalar destination for a compare mask.
|
||||
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],
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,454 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
//! gfx1030 extension-word negative tests (issue #172): truncated and invalid
|
||||
//! literal, SDWA, DPP16, DPP8 and MIMG NSA trailers.
|
||||
//!
|
||||
//! Every source instruction is original and was assembled by llvm-mc 23.1.6
|
||||
//! (`source_encodings_match_llvm` re-checks the bytes). Expected results come
|
||||
//! from LLVM's disassembly of the cut or altered bytes and from the field
|
||||
//! layouts in AMD's public "RDNA 2 Instruction Set Architecture" reference
|
||||
//! (microcode formats: SDWA, DPP16, DPP8, MIMG NSA), never from Xenora's
|
||||
//! decoder. `identify` recognises lengths and allowed extensions; it does not
|
||||
//! validate control-word values (see `reserved_control_values_keep_their_trailer_lengths`).
|
||||
|
||||
use std::io::Write;
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
use xenora_isa::meta::{
|
||||
IdentifyError, SRC_DPP8, SRC_DPP16, SRC_LITERAL, SRC_SDWA, Trailer, VectorControl, identify,
|
||||
};
|
||||
|
||||
struct Fixture {
|
||||
source: &'static str,
|
||||
bytes: &'static [u8],
|
||||
}
|
||||
|
||||
const SOP2_LITERAL: Fixture = Fixture {
|
||||
source: "s_add_u32 s9, 0x12345679, s11",
|
||||
bytes: &[0xff, 0x0b, 0x09, 0x80, 0x79, 0x56, 0x34, 0x12],
|
||||
};
|
||||
const SOPK_IMMEDIATE: Fixture = Fixture {
|
||||
source: "s_setreg_imm32_b32 hwreg(HW_REG_MODE), 0x125678ab",
|
||||
bytes: &[0x01, 0xf8, 0x80, 0xba, 0xab, 0x78, 0x56, 0x12],
|
||||
};
|
||||
const VOP1_LITERAL: Fixture = Fixture {
|
||||
source: "v_mov_b32_e32 v7, 0x12345679",
|
||||
bytes: &[0xff, 0x02, 0x0e, 0x7e, 0x79, 0x56, 0x34, 0x12],
|
||||
};
|
||||
const VOP2_LITERAL: Fixture = Fixture {
|
||||
source: "v_add_f32_e32 v7, 0x3f800003, v8",
|
||||
bytes: &[0xff, 0x10, 0x0e, 0x06, 0x03, 0x00, 0x80, 0x3f],
|
||||
};
|
||||
const FMAMK: Fixture = Fixture {
|
||||
source: "v_fmamk_f32 v7, v8, 0x40000001, v9",
|
||||
bytes: &[0x08, 0x13, 0x0e, 0x58, 0x01, 0x00, 0x00, 0x40],
|
||||
};
|
||||
const FMAAK: Fixture = Fixture {
|
||||
source: "v_fmaak_f32 v7, v8, v9, 0x40000002",
|
||||
bytes: &[0x08, 0x13, 0x0e, 0x5a, 0x02, 0x00, 0x00, 0x40],
|
||||
};
|
||||
const VOPC_LITERAL: Fixture = Fixture {
|
||||
source: "v_cmp_eq_u32_e32 vcc_lo, 0x1235, v9",
|
||||
bytes: &[0xff, 0x12, 0x84, 0x7d, 0x35, 0x12, 0x00, 0x00],
|
||||
};
|
||||
const VOP3_LITERAL: Fixture = Fixture {
|
||||
source: "v_fma_f32 v7, v8, v9, 0x3f800003",
|
||||
bytes: &[
|
||||
0x07, 0x00, 0x4b, 0xd5, 0x08, 0x13, 0xfe, 0x03, 0x03, 0x00, 0x80, 0x3f,
|
||||
],
|
||||
};
|
||||
const VOP3P_LITERAL: Fixture = Fixture {
|
||||
source: "v_pk_fma_f16 v7, v8, v9, 0x3c02",
|
||||
bytes: &[
|
||||
0x07, 0x40, 0x0e, 0xcc, 0x08, 0x13, 0xfe, 0x1b, 0x02, 0x3c, 0x00, 0x00,
|
||||
],
|
||||
};
|
||||
const VOP1_SDWA: Fixture = Fixture {
|
||||
source: "v_mov_b32_sdwa v7, v8 dst_sel:BYTE_1 dst_unused:UNUSED_PAD src0_sel:DWORD",
|
||||
bytes: &[0xf9, 0x02, 0x0e, 0x7e, 0x08, 0x01, 0x06, 0x00],
|
||||
};
|
||||
const VOP2_SDWA: Fixture = Fixture {
|
||||
source: "v_add_f32_sdwa v7, v8, v9 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0 src1_sel:DWORD",
|
||||
bytes: &[0xf9, 0x12, 0x0e, 0x06, 0x08, 0x06, 0x04, 0x06],
|
||||
};
|
||||
const VOPC_SDWA: Fixture = Fixture {
|
||||
source: "v_cmp_eq_u32_sdwa s4, v8, v9 src0_sel:DWORD src1_sel:DWORD",
|
||||
bytes: &[0xf9, 0x12, 0x84, 0x7d, 0x08, 0x84, 0x06, 0x06],
|
||||
};
|
||||
const DPP16: Fixture = Fixture {
|
||||
source: "v_add_f32_dpp v7, v8, v9 row_shl:2 row_mask:0xf bank_mask:0xf",
|
||||
bytes: &[0xfa, 0x12, 0x0e, 0x06, 0x08, 0x02, 0x01, 0xff],
|
||||
};
|
||||
const DPP8: Fixture = Fixture {
|
||||
source: "v_mov_b32_dpp v7, v8 dpp8:[2,3,0,1,6,7,4,5]",
|
||||
bytes: &[0xe9, 0x02, 0x0e, 0x7e, 0x08, 0x1a, 0xe2, 0xb3],
|
||||
};
|
||||
const DPP8_FI: Fixture = Fixture {
|
||||
source: "v_mov_b32_dpp v7, v8 dpp8:[2,3,0,1,6,7,4,5] fi:1",
|
||||
bytes: &[0xea, 0x02, 0x0e, 0x7e, 0x08, 0x1a, 0xe2, 0xb3],
|
||||
};
|
||||
const NSA1: Fixture = Fixture {
|
||||
source: "image_sample v[4:7], [v8, v10], s[0:7], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D",
|
||||
bytes: &[
|
||||
0x0a, 0x0f, 0x80, 0xf0, 0x08, 0x04, 0x40, 0x00, 0x0a, 0x00, 0x00, 0x00,
|
||||
],
|
||||
};
|
||||
const NSA2: Fixture = Fixture {
|
||||
source: "image_sample_d v[4:7], [v8, v10, v12, v14, v16, v18], s[0:7], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D",
|
||||
bytes: &[
|
||||
0x0c, 0x0f, 0x88, 0xf0, 0x08, 0x04, 0x40, 0x00, 0x0a, 0x0c, 0x0e, 0x10, 0x12, 0x00, 0x00,
|
||||
0x00,
|
||||
],
|
||||
};
|
||||
const NSA3: Fixture = Fixture {
|
||||
source: "image_sample_c_d_cl v[4:7], [v8, v10, v12, v14, v16, v18, v20, v22, v24, v26, v28], s[0:7], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_3D",
|
||||
bytes: &[
|
||||
0x16, 0x0f, 0xac, 0xf0, 0x08, 0x04, 0x40, 0x00, 0x0a, 0x0c, 0x0e, 0x10, 0x12, 0x14, 0x16,
|
||||
0x18, 0x1a, 0x1c, 0x00, 0x00,
|
||||
],
|
||||
};
|
||||
const FRACT_F64: Fixture = Fixture {
|
||||
source: "v_fract_f64_e32 v[6:7], v[8:9]",
|
||||
bytes: &[0x08, 0x7d, 0x0c, 0x7e],
|
||||
};
|
||||
const READFIRSTLANE: Fixture = Fixture {
|
||||
source: "v_readfirstlane_b32 s7, v8",
|
||||
bytes: &[0x08, 0x05, 0x0e, 0x7e],
|
||||
};
|
||||
const FMAC: Fixture = Fixture {
|
||||
source: "v_fmac_f32_e32 v7, v8, v9",
|
||||
bytes: &[0x08, 0x13, 0x0e, 0x56],
|
||||
};
|
||||
const READLANE: Fixture = Fixture {
|
||||
source: "v_readlane_b32 s7, v8, s9",
|
||||
bytes: &[0x07, 0x00, 0x60, 0xd7, 0x08, 0x13, 0x00, 0x02],
|
||||
};
|
||||
const NOP: Fixture = Fixture {
|
||||
source: "s_nop 7",
|
||||
bytes: &[0x07, 0x00, 0x80, 0xbf],
|
||||
};
|
||||
const VOPC_REGISTER: Fixture = Fixture {
|
||||
source: "v_cmp_eq_u32_e32 vcc_lo, v8, v9",
|
||||
bytes: &[0x08, 0x13, 0x84, 0x7d],
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn proper_prefixes_report_exact_required_lengths() {
|
||||
// Each row cuts at every dword boundary and one byte before the end.
|
||||
// LLVM emits no original instruction for any prefix. Below, "silent"
|
||||
// means no diagnostic, and "invalid" means LLVM's invalid encoding warning.
|
||||
// Empty input is silent in all rows. The expected values are the next
|
||||
// base boundary (4 or 8) until the base is present, then the LLVM length.
|
||||
let cases: &[(&Fixture, &[usize])] = &[
|
||||
// silent, SSRC0 selects the literal dword.
|
||||
(&SOP2_LITERAL, &[4, 8, 8]),
|
||||
// invalid, mandatory SOPK immediate.
|
||||
(&SOPK_IMMEDIATE, &[4, 8, 8]),
|
||||
// silent, literal selector.
|
||||
(&VOP1_LITERAL, &[4, 8, 8]),
|
||||
// silent, literal selector.
|
||||
(&VOP2_LITERAL, &[4, 8, 8]),
|
||||
// invalid, embedded multiplier dword.
|
||||
(&FMAMK, &[4, 8, 8]),
|
||||
// invalid, embedded addend dword.
|
||||
(&FMAAK, &[4, 8, 8]),
|
||||
// silent, literal selector.
|
||||
(&VOPC_LITERAL, &[4, 8, 8]),
|
||||
// invalid at 4 then silent, 8-byte base and literal.
|
||||
(&VOP3_LITERAL, &[4, 8, 12, 12]),
|
||||
// invalid at 4 then silent, 8-byte base and literal.
|
||||
(&VOP3P_LITERAL, &[4, 8, 12, 12]),
|
||||
// invalid, SDWA control dword.
|
||||
(&VOP1_SDWA, &[4, 8, 8]),
|
||||
// invalid, SDWA control dword.
|
||||
(&VOP2_SDWA, &[4, 8, 8]),
|
||||
// invalid, SDWAB control dword.
|
||||
(&VOPC_SDWA, &[4, 8, 8]),
|
||||
// invalid, DPP16 control dword.
|
||||
(&DPP16, &[4, 8, 8]),
|
||||
// invalid, DPP8 control dword (fi:0).
|
||||
(&DPP8, &[4, 8, 8]),
|
||||
// invalid, DPP8 control dword (fi:1).
|
||||
(&DPP8_FI, &[4, 8, 8]),
|
||||
// invalid, 8-byte base and one NSA dword.
|
||||
(&NSA1, &[4, 8, 12, 12]),
|
||||
// invalid, 8-byte base and two NSA dwords.
|
||||
// LLVM also prints a stray v_mul_f32 from the address bytes.
|
||||
(&NSA2, &[4, 8, 16, 16, 16]),
|
||||
// invalid, 8-byte base and three NSA dwords.
|
||||
// LLVM also prints stray v_mul_f32 and v_mul_hi_u32_u24 from the address bytes.
|
||||
(&NSA3, &[4, 8, 20, 20, 20, 20]),
|
||||
];
|
||||
for &(fixture, expected) in cases {
|
||||
let len = fixture.bytes.len();
|
||||
let prefixes: Vec<_> = (0..len).step_by(4).chain([len - 1]).collect();
|
||||
assert_eq!(prefixes.len(), expected.len(), "{}", fixture.source);
|
||||
for (prefix, &needed) in prefixes.into_iter().zip(expected) {
|
||||
assert_eq!(
|
||||
identify(&fixture.bytes[..prefix]),
|
||||
Err(IdentifyError::Truncated { needed }),
|
||||
"{} at {prefix}/{len} bytes",
|
||||
fixture.source,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disallowed_vector_selectors_and_literal_are_rejected() {
|
||||
// Replace the nine-bit SRC0 field of each assembled e32 instruction
|
||||
// and append a known control or literal dword.
|
||||
let cases = [
|
||||
// LLVM rejects SDWA on v_fract_f64. Expect InvalidExtension("sdwa").
|
||||
(&FRACT_F64, SRC_SDWA, &VOP1_SDWA, "sdwa"),
|
||||
// LLVM rejects DPP16 on v_fract_f64. Expect InvalidExtension("dpp16").
|
||||
(&FRACT_F64, SRC_DPP16, &DPP16, "dpp16"),
|
||||
// LLVM rejects DPP8 on v_fract_f64 and prints the trailer as s_cmpk_lt_i32.
|
||||
// Expect InvalidExtension("dpp8") for the rejected first instruction.
|
||||
(&FRACT_F64, SRC_DPP8, &DPP8, "dpp8"),
|
||||
// LLVM rejects SDWA on v_fmac_f32. Expect InvalidExtension("sdwa").
|
||||
(&FMAC, SRC_SDWA, &VOP1_SDWA, "sdwa"),
|
||||
// LLVM rejects DPP16 on this v_cmp_eq_u32. Expect InvalidExtension("dpp16").
|
||||
(&VOPC_REGISTER, SRC_DPP16, &DPP16, "dpp16"),
|
||||
// LLVM prints v_readfirstlane_b32 with "Invalid immediate" because
|
||||
// this source must be a VGPR. Expect InvalidExtension("literal").
|
||||
(&READFIRSTLANE, SRC_LITERAL, &VOP1_LITERAL, "literal"),
|
||||
];
|
||||
for (fixture, selector, trailer, reason) in cases {
|
||||
let mut bytes = fixture.bytes.to_vec();
|
||||
let word = u32::from_le_bytes(fixture.bytes.try_into().unwrap());
|
||||
bytes.copy_from_slice(&((word & !0x1ff) | selector).to_le_bytes());
|
||||
bytes.extend_from_slice(&trailer.bytes[4..]);
|
||||
assert_eq!(
|
||||
identify(&bytes),
|
||||
Err(IdentifyError::InvalidExtension(reason)),
|
||||
"{} with SRC0={selector:#x}: {bytes:02x?}",
|
||||
fixture.source,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_for_vop3_readlane_is_rejected() {
|
||||
// v_readlane_b32: change SRC0 in the second base dword at bits 8:0
|
||||
// and append the v_mov_b32 literal. LLVM prints "Invalid immediate"
|
||||
// for the VGPR-only source. Expect the form to reject the literal.
|
||||
let mut bytes = READLANE.bytes.to_vec();
|
||||
let word = u32::from_le_bytes(bytes[4..8].try_into().unwrap());
|
||||
bytes[4..8].copy_from_slice(&((word & !0x1ff) | SRC_LITERAL).to_le_bytes());
|
||||
bytes.extend_from_slice(&VOP1_LITERAL.bytes[4..]);
|
||||
assert_eq!(
|
||||
identify(&bytes),
|
||||
Err(IdentifyError::InvalidExtension("literal"))
|
||||
);
|
||||
}
|
||||
|
||||
/// Identification recognizes length independently of control-word validation.
|
||||
#[test]
|
||||
fn reserved_control_values_keep_their_trailer_lengths() {
|
||||
let cases = [
|
||||
// v_add_f32_dpp: replace DPP_CTRL 0x102 with 0x100, which LLVM reports as reserved.
|
||||
// LLVM prints "Invalid dpp_ctrl value". Expect 8 bytes and DPP16.
|
||||
(&DPP16, 5, 0, "V_ADD_F32", VectorControl::Dpp16),
|
||||
// v_mov_b32_sdwa: change SRC0_SEL from 6 to 7, which LLVM treats as reserved.
|
||||
// LLVM prints DWORD and reassembles it as 6. Expect 8 bytes and SDWA.
|
||||
(&VOP1_SDWA, 6, 7, "V_MOV_B32", VectorControl::Sdwa),
|
||||
];
|
||||
for (fixture, offset, value, name, control) in cases {
|
||||
let mut bytes = fixture.bytes.to_vec();
|
||||
bytes[offset] = value;
|
||||
let found = identify(&bytes).unwrap();
|
||||
assert_eq!(found.form.name, name);
|
||||
assert_eq!(found.len, 8);
|
||||
assert_eq!(
|
||||
found.trailer,
|
||||
Trailer {
|
||||
vector_control: Some(control),
|
||||
..Trailer::default()
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn next_instruction_starts_after_the_trailer() {
|
||||
// Append s_nop 7 to each original instruction. LLVM disassembles the
|
||||
// two instructions with lengths (offset, 4). Expect that boundary from
|
||||
// identify and the trailer selected by SRC0, SSRC0, or MIMG.NSA.
|
||||
let cases = [
|
||||
// LLVM emits s_nop at byte 8. Expect a scalar literal dword.
|
||||
(
|
||||
&SOP2_LITERAL,
|
||||
"S_ADD_U32",
|
||||
8,
|
||||
Trailer {
|
||||
literal: true,
|
||||
..Trailer::default()
|
||||
},
|
||||
),
|
||||
// LLVM emits s_nop at byte 8. Expect an SDWA control dword.
|
||||
(
|
||||
&VOP1_SDWA,
|
||||
"V_MOV_B32",
|
||||
8,
|
||||
Trailer {
|
||||
vector_control: Some(VectorControl::Sdwa),
|
||||
..Trailer::default()
|
||||
},
|
||||
),
|
||||
// LLVM emits s_nop at byte 8. Expect a DPP16 control dword.
|
||||
(
|
||||
&DPP16,
|
||||
"V_ADD_F32",
|
||||
8,
|
||||
Trailer {
|
||||
vector_control: Some(VectorControl::Dpp16),
|
||||
..Trailer::default()
|
||||
},
|
||||
),
|
||||
// LLVM emits s_nop at byte 8. Expect DPP8 with fi:0.
|
||||
(
|
||||
&DPP8,
|
||||
"V_MOV_B32",
|
||||
8,
|
||||
Trailer {
|
||||
vector_control: Some(VectorControl::Dpp8 {
|
||||
fetch_inactive: false,
|
||||
}),
|
||||
..Trailer::default()
|
||||
},
|
||||
),
|
||||
// LLVM emits s_nop at byte 8. Expect DPP8 with fi:1.
|
||||
(
|
||||
&DPP8_FI,
|
||||
"V_MOV_B32",
|
||||
8,
|
||||
Trailer {
|
||||
vector_control: Some(VectorControl::Dpp8 {
|
||||
fetch_inactive: true,
|
||||
}),
|
||||
..Trailer::default()
|
||||
},
|
||||
),
|
||||
// LLVM emits s_nop at byte 12. Expect one NSA dword.
|
||||
(
|
||||
&NSA1,
|
||||
"IMAGE_SAMPLE",
|
||||
12,
|
||||
Trailer {
|
||||
nsa_dwords: 1,
|
||||
..Trailer::default()
|
||||
},
|
||||
),
|
||||
// LLVM emits s_nop at byte 16. Expect two NSA dwords.
|
||||
(
|
||||
&NSA2,
|
||||
"IMAGE_SAMPLE_D",
|
||||
16,
|
||||
Trailer {
|
||||
nsa_dwords: 2,
|
||||
..Trailer::default()
|
||||
},
|
||||
),
|
||||
// LLVM emits s_nop at byte 20. Expect three NSA dwords.
|
||||
(
|
||||
&NSA3,
|
||||
"IMAGE_SAMPLE_C_D_CL",
|
||||
20,
|
||||
Trailer {
|
||||
nsa_dwords: 3,
|
||||
..Trailer::default()
|
||||
},
|
||||
),
|
||||
];
|
||||
for (fixture, name, offset, trailer) in cases {
|
||||
let bytes = [fixture.bytes, NOP.bytes].concat();
|
||||
let first = identify(&bytes).unwrap();
|
||||
assert_eq!(
|
||||
(first.form.name, first.len, first.trailer),
|
||||
(name, offset, trailer),
|
||||
"{} followed by {}",
|
||||
fixture.source,
|
||||
NOP.source,
|
||||
);
|
||||
let second = identify(&bytes[first.len..]).unwrap();
|
||||
assert_eq!(
|
||||
(second.form.name, second.len, second.trailer),
|
||||
("S_NOP", 4, Trailer::default()),
|
||||
);
|
||||
assert_eq!(first.len + second.len, bytes.len());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires LLVM with the gfx1030 AMDGPU target"]
|
||||
fn source_encodings_match_llvm() {
|
||||
let fixtures = [
|
||||
&SOP2_LITERAL,
|
||||
&SOPK_IMMEDIATE,
|
||||
&VOP1_LITERAL,
|
||||
&VOP2_LITERAL,
|
||||
&FMAMK,
|
||||
&FMAAK,
|
||||
&VOPC_LITERAL,
|
||||
&VOP3_LITERAL,
|
||||
&VOP3P_LITERAL,
|
||||
&VOP1_SDWA,
|
||||
&VOP2_SDWA,
|
||||
&VOPC_SDWA,
|
||||
&DPP16,
|
||||
&DPP8,
|
||||
&DPP8_FI,
|
||||
&NSA1,
|
||||
&NSA2,
|
||||
&NSA3,
|
||||
&FRACT_F64,
|
||||
&READFIRSTLANE,
|
||||
&FMAC,
|
||||
&READLANE,
|
||||
&NOP,
|
||||
&VOPC_REGISTER,
|
||||
];
|
||||
let executable = std::env::var_os("LLVM_BIN").map_or_else(
|
||||
|| "llvm-mc".into(),
|
||||
|directory| std::path::PathBuf::from(directory).join("llvm-mc"),
|
||||
);
|
||||
let mut llvm = Command::new(executable)
|
||||
.args([
|
||||
"-triple=amdgcn-amd-amdhsa",
|
||||
"-mcpu=gfx1030",
|
||||
"-mattr=+wavefrontsize32",
|
||||
"-show-encoding",
|
||||
])
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.expect("launch llvm-mc (provide its directory in LLVM_BIN or put it on PATH)");
|
||||
{
|
||||
let mut input = llvm.stdin.take().unwrap();
|
||||
for fixture in fixtures {
|
||||
writeln!(input, "{}", fixture.source).unwrap();
|
||||
}
|
||||
}
|
||||
let output = llvm.wait_with_output().unwrap();
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr),
|
||||
);
|
||||
let assembly = String::from_utf8(output.stdout).unwrap();
|
||||
let encodings: Vec<_> = assembly
|
||||
.lines()
|
||||
.filter_map(|line| line.split_once("; encoding: [").map(|(_, bytes)| bytes))
|
||||
.collect();
|
||||
assert_eq!(encodings.len(), fixtures.len());
|
||||
for (fixture, encoding) in fixtures.into_iter().zip(encodings) {
|
||||
let bytes: Vec<_> = encoding
|
||||
.strip_suffix(']')
|
||||
.unwrap()
|
||||
.split(',')
|
||||
.map(|byte| u8::from_str_radix(byte.trim().strip_prefix("0x").unwrap(), 16).unwrap())
|
||||
.collect();
|
||||
assert_eq!(bytes, fixture.bytes, "{}", fixture.source);
|
||||
}
|
||||
}
|
||||
@@ -1,311 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Regenerate the gfx1030 Wave32 instruction-identification oracle corpus."""
|
||||
|
||||
import argparse
|
||||
from collections import defaultdict
|
||||
from itertools import islice, zip_longest
|
||||
from pathlib import Path
|
||||
import random
|
||||
import re
|
||||
import runpy
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
ISA = HERE.parents[1]
|
||||
TARGET = ("-triple=amdgcn-amd-amdhsa", "-mcpu=gfx1030", "-mattr=+wavefrontsize32")
|
||||
BASE_32 = {"SOP1", "SOP2", "SOPC", "SOPK", "SOPP", "VINTRP", "VOP1", "VOP2", "VOPC"}
|
||||
ENCODING = re.compile(r"^\s*(.*?)\s*; encoding: \[([^\]]+)\]", re.MULTILINE)
|
||||
SECTION = re.compile(r"^Disassembly of section \.text\.(\d+):")
|
||||
# Instruction text, offset, consumed words, then optional trailing text: a
|
||||
# branch-target annotation such as `<.text+0x841c>` or an LLVM warning such as
|
||||
# `; Warning: ... scalar reg isn't aligned`, neither of which stops decoding.
|
||||
INSTRUCTION = re.compile(r"^\t(.*?)\s*// ([0-9A-F]{12}): ((?:[0-9A-F]{8}(?: |$))+)(.*)$")
|
||||
|
||||
|
||||
def llvm(executable, *args, source=None):
|
||||
return subprocess.run(
|
||||
[executable, *TARGET, "-show-encoding", *args],
|
||||
input=source, text=True, capture_output=True, check=True,
|
||||
)
|
||||
|
||||
|
||||
def encodings(output):
|
||||
for text, bytes_text in ENCODING.findall(output):
|
||||
yield " ".join(text.split()), bytes(int(token, 16) for token in bytes_text.split(","))
|
||||
|
||||
|
||||
def disassemble_batch(llvm_bin, blobs):
|
||||
"""LLVM's decode of the first instruction of each blob.
|
||||
|
||||
Each blob goes into its own section of one object built from `.byte`
|
||||
directives; llvm-objdump disassembles every section from offset zero and
|
||||
prints the words it consumed. That length is what the decoder read, not the
|
||||
length of a re-encoding (llvm-mc --disassemble re-encodes, which shortens
|
||||
inconsistent MIMG NSA probes). Returns (text, consumed bytes) or None when
|
||||
LLVM cannot decode offset zero (it prints `.long`/`.short`/`.byte`).
|
||||
"""
|
||||
source = []
|
||||
for index, blob in enumerate(blobs):
|
||||
source.append(f'.section .text.{index},"ax"')
|
||||
if blob:
|
||||
source.append(".byte " + ",".join(f"0x{byte:02x}" for byte in blob))
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
assembly_path = Path(directory) / "probes.s"
|
||||
object_path = Path(directory) / "probes.o"
|
||||
assembly_path.write_text("\n".join(source) + "\n")
|
||||
subprocess.run(
|
||||
[llvm_bin / "llvm-mc", *TARGET, "-filetype=obj", assembly_path, "-o", object_path],
|
||||
check=True, capture_output=True,
|
||||
)
|
||||
dump = subprocess.run(
|
||||
[llvm_bin / "llvm-objdump", "-d", "--mcpu=gfx1030", "--mattr=+wavefrontsize32", object_path],
|
||||
check=True, capture_output=True, text=True,
|
||||
).stdout
|
||||
first = {}
|
||||
section = None
|
||||
for line in dump.splitlines():
|
||||
header = SECTION.match(line)
|
||||
if header:
|
||||
section = int(header.group(1))
|
||||
continue
|
||||
instruction = INSTRUCTION.match(line)
|
||||
if section is None or section in first or not instruction:
|
||||
continue
|
||||
text, offset, words, warning = instruction.groups()
|
||||
if int(offset, 16) != 0:
|
||||
continue
|
||||
if text.startswith((".long", ".short", ".byte")):
|
||||
first[section] = None
|
||||
else:
|
||||
text = " ".join(text.split())
|
||||
warning = warning.strip()
|
||||
if warning.startswith(";"):
|
||||
text += f" [LLVM: {warning.lstrip('; ')}]"
|
||||
first[section] = (text, 4 * len(words.split()))
|
||||
return [first.get(index) for index in range(len(blobs))]
|
||||
|
||||
|
||||
CRASHED = "crashed"
|
||||
|
||||
|
||||
def disassemble_all(llvm_bin, blobs):
|
||||
"""Batches of 128; a batch that crashes llvm-objdump is split until the
|
||||
crashing blobs are isolated, and each of those is reported as CRASHED."""
|
||||
results = []
|
||||
for start in range(0, len(blobs), 128):
|
||||
results.extend(_isolate(llvm_bin, blobs[start:start + 128]))
|
||||
return results
|
||||
|
||||
|
||||
def _isolate(llvm_bin, blobs):
|
||||
try:
|
||||
return disassemble_batch(llvm_bin, blobs)
|
||||
except subprocess.CalledProcessError as error:
|
||||
if error.returncode != -11:
|
||||
raise
|
||||
if len(blobs) == 1:
|
||||
return [CRASHED]
|
||||
half = len(blobs) // 2
|
||||
return _isolate(llvm_bin, blobs[:half]) + _isolate(llvm_bin, blobs[half:])
|
||||
|
||||
|
||||
def extension(text, length, family):
|
||||
mnemonic = text.split()[0]
|
||||
if "dpp8:" in text:
|
||||
return "dpp8fi" if "fi:1" in text else "dpp8"
|
||||
if mnemonic.endswith("_dpp"):
|
||||
return "dpp16"
|
||||
if mnemonic.endswith("_sdwa"):
|
||||
return "sdwa"
|
||||
base_bytes = 4 if family in BASE_32 else 8
|
||||
if mnemonic.endswith("_e64"):
|
||||
base_bytes = 8
|
||||
extra = length - base_bytes
|
||||
if mnemonic.startswith("image_") and extra > 0:
|
||||
return f"nsa{extra // 4}"
|
||||
# After excluding vector control and image addresses, an extra dword
|
||||
# carrying a numeric operand is the literal (including mandatory literals).
|
||||
if extra == 4 and re.search(r"(?:,|\s)\s*-?(?:0x[\da-f]+|\d+)(?=,|\s|$|/\*)", text):
|
||||
return "literal"
|
||||
if extra > 0:
|
||||
raise ValueError(f"unclassified LLVM extension: {length} bytes {text}")
|
||||
return "-"
|
||||
|
||||
|
||||
def assembly(executable):
|
||||
source = HERE / "corpus.s"
|
||||
families = [
|
||||
line.split("//", 1)[1].strip()
|
||||
for line in source.read_text().splitlines()
|
||||
if line.split("//", 1)[0].strip()
|
||||
]
|
||||
result = llvm(executable, source)
|
||||
if result.stderr:
|
||||
raise ValueError(result.stderr)
|
||||
decoded = list(encodings(result.stdout))
|
||||
if len(decoded) != len(families):
|
||||
raise ValueError("LLVM must emit exactly one encoding per assembly line")
|
||||
return [(family, text, data) for family, (text, data) in zip(families, decoded)]
|
||||
|
||||
|
||||
def metadata_forms():
|
||||
snapshot = ISA / "data/rdna2.jsonl"
|
||||
project = runpy.run_path(str(ISA / "generate_rdna2_meta.py"))["forms_from_snapshot"]
|
||||
return project(snapshot.read_text())[2]
|
||||
|
||||
|
||||
def probes():
|
||||
# The normalized snapshot stores instruction variants and encoding records
|
||||
# separately. Reuse its projection to obtain identifiers, widths and labels
|
||||
# for coverage. The projected mnemonic and extensions are never consulted.
|
||||
forms = metadata_forms()
|
||||
rng = random.Random(209)
|
||||
for form in forms:
|
||||
width = form["bytes"]
|
||||
# One probe with every non-identifying bit zero (operands s0/v0, no
|
||||
# modifiers), then two with seeded random operand bits.
|
||||
yield "zero", form["encoding"].upper(), form["bits"].to_bytes(width, "little") + bytes(16)
|
||||
for _ in range(2):
|
||||
value = form["bits"] | (rng.getrandbits(width * 8) & ~form["mask"])
|
||||
yield "random", form["encoding"].upper(), value.to_bytes(width, "little") + rng.randbytes(16)
|
||||
|
||||
|
||||
# Extension selectors from the RDNA 2 ISA reference: the SRC0 (VOP1, VOP2,
|
||||
# VOPC, VOP3*) or SSRC0 (SOP1, SOP2, SOPC) value that makes one extra dword
|
||||
# follow the base encoding.
|
||||
SELECTORS = {"literal": 0xFF, "sdwa": 0xF9, "dpp16": 0xFA, "dpp8": 0xE9, "dpp8fi": 0xEA}
|
||||
# Instructions whose last dword is a legal control word for each extension;
|
||||
# LLVM assembles them, so the control words are LLVM's own.
|
||||
CONTROL_SOURCES = {
|
||||
"sdwa": "v_add_f32_sdwa v0, v0, v0 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:DWORD src1_sel:DWORD",
|
||||
"sdwa-vop1": "v_mov_b32_sdwa v0, v0 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:DWORD",
|
||||
"sdwa-vopc": "v_cmp_eq_f32_sdwa vcc_lo, v0, v0 src0_sel:DWORD src1_sel:DWORD",
|
||||
"dpp16": "v_add_f32_dpp v0, v0, v0 quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0xf",
|
||||
"dpp8": "v_add_f32_dpp v0, v0, v0 dpp8:[0,1,2,3,4,5,6,7]",
|
||||
"dpp8fi": "v_add_f32_dpp v0, v0, v0 dpp8:[0,1,2,3,4,5,6,7] fi:1",
|
||||
}
|
||||
LITERAL = (0x12345678).to_bytes(4, "little")
|
||||
|
||||
|
||||
def controls(executable):
|
||||
source = "\n".join(CONTROL_SOURCES.values()) + "\n"
|
||||
decoded = list(encodings(llvm(executable, source=source).stdout))
|
||||
return {name: data[-4:] for name, (_, data) in zip(CONTROL_SOURCES, decoded)}
|
||||
|
||||
|
||||
def extension_probes(executable, forms):
|
||||
"""Every form's zero-operand base with each extension selector its family
|
||||
can carry, followed by a legal control dword or literal. LLVM decides which
|
||||
combinations are instructions; the metadata's extension list is not read."""
|
||||
control = controls(executable)
|
||||
for form in forms:
|
||||
family = form["encoding"].upper()
|
||||
base = form["bits"]
|
||||
if family in ("VOP1", "VOP2", "VOPC"):
|
||||
kinds = ["literal", "sdwa", "dpp16", "dpp8", "dpp8fi"]
|
||||
shift = 0
|
||||
elif family in ("VOP3", "VOP3SDST", "VOP3P"):
|
||||
kinds, shift = ["literal"], 32
|
||||
elif family in ("SOP1", "SOP2", "SOPC"):
|
||||
kinds, shift = ["literal"], 0
|
||||
else:
|
||||
continue
|
||||
field = 0x1FF if shift == 32 or family.startswith("VOP") else 0xFF
|
||||
if base & form["mask"] & (field << shift):
|
||||
continue # SRC0/SSRC0 is part of this form's identifier
|
||||
for kind in kinds:
|
||||
value = (base & ~(field << shift)) | (SELECTORS[kind] << shift)
|
||||
if kind == "literal":
|
||||
trailer = LITERAL
|
||||
elif kind == "sdwa" and family in ("VOPC", "VOP1"):
|
||||
trailer = control[f"sdwa-{family.lower()}"]
|
||||
else:
|
||||
trailer = control[kind]
|
||||
yield kind, family, value.to_bytes(form["bytes"], "little") + trailer + bytes(12)
|
||||
|
||||
|
||||
def truncations(entries):
|
||||
by_family = defaultdict(list)
|
||||
for entry in entries:
|
||||
by_family[entry[0]].append(entry)
|
||||
groups = [
|
||||
sorted(group, key=lambda entry: -len(entry[2]))
|
||||
for _, group in sorted(by_family.items())
|
||||
]
|
||||
interleaved = (entry for batch in zip_longest(*groups) for entry in batch if entry)
|
||||
yield from islice(interleaved, 40)
|
||||
|
||||
|
||||
def decoded_columns(text, length, family):
|
||||
return text.split()[0], str(length), extension(text, length, family)
|
||||
|
||||
|
||||
def generate(llvm_bin):
|
||||
rows = []
|
||||
entries = assembly(llvm_bin / "llvm-mc")
|
||||
for family, text, data in entries:
|
||||
rows.append(("asm", data.hex(), *decoded_columns(text, len(data), family), f"{family} {text}"))
|
||||
probe_list = list(probes()) + [
|
||||
(f"ext-{kind}", family, data)
|
||||
for kind, family, data in extension_probes(llvm_bin / "llvm-mc", metadata_forms())
|
||||
]
|
||||
cut_list = [
|
||||
(family, text, data, data[:size])
|
||||
for family, text, data in truncations(entries)
|
||||
for size in range(0, len(data), 4)
|
||||
]
|
||||
decoded_all = disassemble_all(llvm_bin, [data for _, _, data in probe_list] + [cut for *_, cut in cut_list])
|
||||
for (kind, family, data), decoded in zip(probe_list, decoded_all):
|
||||
if decoded is None:
|
||||
columns = ("invalid", "0", "-")
|
||||
note = "LLVM cannot decode offset zero"
|
||||
elif decoded == CRASHED:
|
||||
columns = ("crashed", "0", "-")
|
||||
note = "llvm-objdump crashed (SIGSEGV)"
|
||||
elif "/*Invalid" not in decoded[0]:
|
||||
text, length = decoded
|
||||
columns = decoded_columns(text, length, family)
|
||||
note = text
|
||||
if decoded not in (None, CRASHED) and "/*Invalid" in decoded[0]:
|
||||
# LLVM decodes the words (so it knows the opcode and the length)
|
||||
# but flags an operand the instruction cannot take, for example an
|
||||
# SGPR or literal for a VGPR-only source.
|
||||
text, length = decoded
|
||||
mnemonic, *rest = decoded_columns(text, length, family)
|
||||
columns = (f"invalid-operand:{mnemonic}", *rest)
|
||||
note = text
|
||||
source = f"probe-{kind}" if kind in ("zero", "random") else "probe-ext"
|
||||
if kind.startswith("ext-"):
|
||||
note = f"{kind[4:]} {note}"
|
||||
rows.append((source, data.hex(), *columns, f"{family} {note}"))
|
||||
for (family, text, data, prefix), decoded in zip(cut_list, decoded_all[len(probe_list):]):
|
||||
if decoded is None:
|
||||
observed = "cannot decode" if prefix else "no instruction"
|
||||
elif decoded == CRASHED:
|
||||
observed = "crashed (SIGSEGV)"
|
||||
else:
|
||||
observed = f"decoded {decoded[1]} bytes: {decoded[0]}"
|
||||
note = f"{family} LLVM {observed} | cut {data.hex()} {text}"
|
||||
rows.append(("truncation", prefix.hex(), "truncated", "0", "-", note))
|
||||
header = "source\thex\tllvm_mnemonic\tllvm_len\tllvm_ext\tnote\n"
|
||||
return header + "".join("\t".join(row) + "\n" for row in sorted(rows))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--llvm-bin", required=True, type=Path)
|
||||
parser.add_argument("--check", action="store_true")
|
||||
args = parser.parse_args()
|
||||
data = generate(args.llvm_bin.resolve())
|
||||
output = HERE / "corpus.tsv"
|
||||
if args.check:
|
||||
if output.read_bytes() != data.encode():
|
||||
parser.exit(1, f"{output} differs from the LLVM output\n")
|
||||
else:
|
||||
output.write_bytes(data.encode())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,320 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Original gfx1030 Wave32 instruction identification cases.
|
||||
s_mov_b32 s105, s0 // SOP1
|
||||
s_mov_b32 exec_lo, -16 // SOP1
|
||||
s_mov_b32 m0, 64 // SOP1
|
||||
s_mov_b32 vcc_hi, 0xdeadbeef // SOP1
|
||||
s_mov_b64 exec, vcc // SOP1
|
||||
s_mov_b64 vcc, 0x12345678 // SOP1
|
||||
s_not_b32 s0, s105 // SOP1
|
||||
s_not_b64 s[104:105], s[0:1] // SOP1
|
||||
s_brev_b32 s105, m0 // SOP1
|
||||
s_bcnt1_i32_b32 s0, exec_lo // SOP1
|
||||
s_ff1_i32_b32 s105, -16 // SOP1
|
||||
s_flbit_i32_b32 s105, 0x80000100 // SOP1
|
||||
s_sext_i32_i8 s0, s105 // SOP1
|
||||
s_sext_i32_i16 s105, s0 // SOP1
|
||||
s_getpc_b64 s[104:105] // SOP1
|
||||
s_setpc_b64 s[0:1] // SOP1
|
||||
s_and_saveexec_b64 s[0:1], s[104:105] // SOP1
|
||||
s_wqm_b64 s[104:105], exec // SOP1
|
||||
s_add_u32 s105, s0, 0x12345678 // SOP2
|
||||
s_add_u32 s0, 0xdeadbeef, s105 // SOP2
|
||||
s_add_i32 s0, -16, 64 // SOP2
|
||||
s_sub_i32 s105, s0, m0 // SOP2
|
||||
s_subb_u32 s0, vcc_lo, exec_lo // SOP2
|
||||
s_min_i32 s105, s104, -16 // SOP2
|
||||
s_max_u32 s0, s105, 64 // SOP2
|
||||
s_cselect_b32 s105, -1, s0 // SOP2
|
||||
s_and_b64 s[104:105], exec, vcc // SOP2
|
||||
s_or_b64 vcc, s[0:1], exec // SOP2
|
||||
s_xor_b32 s0, s0, 0xdeadbeef // SOP2
|
||||
s_nand_b32 s105, m0, vcc_lo // SOP2
|
||||
s_lshl_b32 s0, s105, 31 // SOP2
|
||||
s_lshr_b64 s[104:105], s[0:1], 63 // SOP2
|
||||
s_ashr_i32 s105, 0x87654321, 31 // SOP2
|
||||
s_mul_i32 s0, s105, -16 // SOP2
|
||||
s_bfe_u32 s105, s0, 0x0010000f // SOP2
|
||||
s_cmp_eq_i32 s0, s105 // SOPC
|
||||
s_cmp_lg_i32 m0, -16 // SOPC
|
||||
s_cmp_gt_i32 64, s105 // SOPC
|
||||
s_cmp_ge_i32 s105, 0xdeadbeef // SOPC
|
||||
s_cmp_lt_u32 0x12345678, exec_hi // SOPC
|
||||
s_cmp_le_u32 vcc_lo, 64 // SOPC
|
||||
s_cmp_eq_u64 s[104:105], vcc // SOPC
|
||||
s_bitcmp0_b32 s105, 31 // SOPC
|
||||
s_bitcmp1_b64 exec, 63 // SOPC
|
||||
s_movk_i32 s0, -32768 // SOPK
|
||||
s_movk_i32 s105, 32767 // SOPK
|
||||
s_movk_i32 m0, -1 // SOPK
|
||||
s_addk_i32 s105, -32768 // SOPK
|
||||
s_mulk_i32 s0, 32767 // SOPK
|
||||
s_cmpk_eq_i32 s105, -32768 // SOPK
|
||||
s_cmpk_lg_u32 s0, 65535 // SOPK
|
||||
s_getreg_b32 s105, hwreg(HW_REG_MODE) // SOPK
|
||||
s_setreg_b32 hwreg(HW_REG_MODE, 4, 8), s0 // SOPK
|
||||
s_setreg_imm32_b32 hwreg(HW_REG_MODE, 8, 16), 0xdeadbeef // SOPK
|
||||
s_setreg_imm32_b32 hwreg(HW_REG_MODE), 0 // SOPK
|
||||
s_nop 15 // SOPP
|
||||
s_endpgm 0 // SOPP
|
||||
s_branch -32768 // SOPP
|
||||
s_cbranch_scc0 32767 // SOPP
|
||||
s_cbranch_scc1 -1 // SOPP
|
||||
s_cbranch_vccz 0 // SOPP
|
||||
s_cbranch_vccnz 3 // SOPP
|
||||
s_cbranch_execz 7 // SOPP
|
||||
s_cbranch_execnz -7 // SOPP
|
||||
s_barrier // SOPP
|
||||
s_waitcnt vmcnt(0) lgkmcnt(1) expcnt(7) // SOPP
|
||||
s_sleep 127 // SOPP
|
||||
s_trap 255 // SOPP
|
||||
s_load_dword s105, s[0:1], 1048575 // SMEM
|
||||
s_load_dword s0, s[104:105], -1048576 // SMEM
|
||||
s_load_dwordx2 s[104:105], s[0:1], 0 glc // SMEM
|
||||
s_load_dwordx4 s[0:3], s[100:101], s105 // SMEM
|
||||
s_load_dwordx8 s[96:103], s[0:1], 7 // SMEM
|
||||
s_load_dwordx16 s[0:15], s[104:105], 16 // SMEM
|
||||
s_buffer_load_dword s105, s[0:3], 4095 // SMEM
|
||||
s_buffer_load_dwordx2 s[104:105], s[0:3], 0 // SMEM
|
||||
s_buffer_load_dwordx4 s[0:3], s[100:103], s105 // SMEM
|
||||
s_memtime s[104:105] // SMEM
|
||||
s_dcache_inv // SMEM
|
||||
v_mov_b32_e32 v255, v0 // VOP1
|
||||
v_mov_b32_e32 v0, s105 // VOP1
|
||||
v_mov_b32_e32 v255, 0xdeadbeef // VOP1
|
||||
v_mov_b32_e32 v0, -16 // VOP1
|
||||
v_mov_b32_e32 v255, 64 // VOP1
|
||||
v_mov_b32_e32 v0, 0.5 // VOP1
|
||||
v_mov_b32_e32 v255, -4.0 // VOP1
|
||||
v_mov_b32_e32 v0, 0.15915494 // VOP1
|
||||
v_cvt_f32_i32_e32 v255, v0 // VOP1
|
||||
v_cvt_f32_u32_e32 v0, v255 // VOP1
|
||||
v_cvt_i32_f32_e32 v255, 0x3f800001 // VOP1
|
||||
v_rcp_f32_e32 v0, v255 // VOP1
|
||||
v_sqrt_f32_e32 v255, v0 // VOP1
|
||||
v_readfirstlane_b32 s105, v255 // VOP1
|
||||
v_mov_b32_sdwa v255, v0 dst_sel:BYTE_3 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0 // VOP1
|
||||
v_mov_b32_dpp v0, v255 quad_perm:[3,2,1,0] row_mask:0x1 bank_mask:0x8 // VOP1
|
||||
v_mov_b32_dpp v255, v0 row_shl:15 bound_ctrl:1 // VOP1
|
||||
v_mov_b32_dpp v0, v255 row_share:15 // VOP1
|
||||
v_mov_b32_dpp v255, v0 dpp8:[7,6,5,4,3,2,1,0] fi:0 // VOP1
|
||||
v_mov_b32_dpp v0, v255 dpp8:[0,0,0,0,7,7,7,7] fi:1 // VOP1
|
||||
v_mov_b32_e32 v255, 0x3e22f983 // VOP1
|
||||
v_add_f32_e32 v0, v255, v0 // VOP2
|
||||
v_sub_f32_e32 v255, 0x3f800001, v0 // VOP2
|
||||
v_subrev_f32_e32 v0, s105, v255 // VOP2
|
||||
v_mul_f32_e32 v255, -4.0, v0 // VOP2
|
||||
v_mul_i32_i24_e32 v0, -16, v255 // VOP2
|
||||
v_mul_u32_u24_e32 v255, 64, v0 // VOP2
|
||||
v_min_f32_e32 v0, 0.5, v255 // VOP2
|
||||
v_max_f32_e32 v255, 0.15915494, v0 // VOP2
|
||||
v_lshrrev_b32_e32 v0, 31, v255 // VOP2
|
||||
v_ashrrev_i32_e32 v255, 31, v0 // VOP2
|
||||
v_lshlrev_b32_e32 v0, 31, v255 // VOP2
|
||||
v_and_b32_e32 v255, 0xdeadbeef, v0 // VOP2
|
||||
v_or_b32_e32 v0, m0, v255 // VOP2
|
||||
v_xor_b32_e32 v255, vcc_lo, v0 // VOP2
|
||||
v_add_nc_u32_e32 v0, exec_lo, v255 // VOP2
|
||||
v_fmamk_f32 v255, v0, 0x3f800001, v255 // VOP2
|
||||
v_fmaak_f32 v0, v255, v0, 0xdeadbeef // VOP2
|
||||
v_add_f32_sdwa v255, v0, v255 dst_sel:WORD_1 dst_unused:UNUSED_SEXT src0_sel:BYTE_0 src1_sel:WORD_0 // VOP2
|
||||
v_add_f32_dpp v0, v255, v0 row_shl:7 bound_ctrl:1 // VOP2
|
||||
v_mul_f32_dpp v255, v0, v255 dpp8:[1,2,3,4,5,6,7,0] fi:1 // VOP2
|
||||
v_cmp_eq_f32_e32 vcc_lo, 0.5, v255 // VOPC
|
||||
v_cmp_lt_f32_e32 vcc_lo, -4.0, v0 // VOPC
|
||||
v_cmp_ge_f32_e32 vcc_lo, 0x3f800001, v255 // VOPC
|
||||
v_cmp_ne_u32_e32 vcc_lo, 0xdeadbeef, v0 // VOPC
|
||||
v_cmp_gt_i32_e32 vcc_lo, -16, v255 // VOPC
|
||||
v_cmp_le_i32_e32 vcc_lo, s105, v0 // VOPC
|
||||
v_cmpx_eq_u32_e32 64, v255 // VOPC
|
||||
v_cmp_eq_i32_sdwa s105, v255, v0 src0_sel:WORD_0 src1_sel:BYTE_3 // VOPC
|
||||
v_cmp_lt_u32_sdwa vcc_lo, v0, v255 src0_sel:BYTE_1 src1_sel:WORD_1 // VOPC
|
||||
v_cmp_class_f32_e32 vcc_lo, v0, v255 // VOPC
|
||||
v_add_f32_e64 v255, -v0, |v255| clamp // VOP3
|
||||
v_add_f32_e64 v0, 0x3f800001, v255 // VOP3
|
||||
v_mul_f32_e64 v255, v0, 0.5 mul:2 // VOP3
|
||||
v_fma_f32 v0, v255, 0x3f800001, v0 // VOP3
|
||||
v_fma_f32 v255, -v0, |v255|, -4.0 // VOP3
|
||||
v_mad_u32_u24 v0, v255, 64, v0 // VOP3
|
||||
v_mad_i32_i24 v255, v0, -16, v255 // VOP3
|
||||
v_min3_f32 v0, v255, v0, 0.5 // VOP3
|
||||
v_max3_i32 v255, v0, v255, -16 // VOP3
|
||||
v_med3_u32 v0, v255, v0, 64 // VOP3
|
||||
v_bfe_u32 v255, v0, 31, 1 // VOP3
|
||||
v_bfe_i32 v0, v255, 0, 32 // VOP3
|
||||
v_bfi_b32 v255, v0, v255, 0x12345678 // VOP3
|
||||
v_alignbit_b32 v0, v255, v0, 31 // VOP3
|
||||
v_cmp_eq_u32_e64 s105, v255, 0xdeadbeef // VOP3
|
||||
v_readlane_b32 s105, v255, 31 // VOP3
|
||||
v_writelane_b32 v255, s105, 31 // VOP3
|
||||
v_add_co_u32 v255, s105, v0, v255 // VOP3SDST
|
||||
v_add_co_u32 v0, vcc_lo, 0xdeadbeef, v255 // VOP3SDST
|
||||
v_sub_co_u32 v255, s0, v0, v255 // VOP3SDST
|
||||
v_subrev_co_u32 v0, s105, v255, v0 // VOP3SDST
|
||||
v_div_scale_f32 v255, s105, v0, v0, v255 // VOP3SDST
|
||||
v_div_scale_f64 v[254:255], vcc_lo, v[0:1], v[0:1], v[2:3] // VOP3SDST
|
||||
v_pk_add_f16 v255, v0, v255 op_sel:[1,0] op_sel_hi:[0,1] // VOP3P
|
||||
v_pk_mul_f16 v0, v255, 0x3c01 // VOP3P
|
||||
v_pk_fma_f16 v255, v0, v255, 0x3c01 // VOP3P
|
||||
v_pk_add_i16 v0, v255, 64 clamp // VOP3P
|
||||
v_pk_sub_i16 v255, v0, -16 // VOP3P
|
||||
v_pk_mul_lo_u16 v0, v255, v0 // VOP3P
|
||||
v_pk_min_i16 v255, v0, v255 // VOP3P
|
||||
v_pk_max_u16 v0, v255, v0 // VOP3P
|
||||
v_pk_lshlrev_b16 v255, 15, v0 // VOP3P
|
||||
v_dot2_f32_f16 v0, v255, v0, 0.5 // VOP3P
|
||||
v_interp_p1_f32 v255, v0, attr32.w // VINTRP
|
||||
v_interp_p2_f32 v0, v255, attr0.x // VINTRP
|
||||
v_interp_mov_f32 v255, p0, attr32.y // VINTRP
|
||||
v_interp_mov_f32 v0, p10, attr1.z // VINTRP
|
||||
v_interp_p1_f32 v0, v255, attr1.y // VINTRP
|
||||
v_interp_p2_f32 v255, v0, attr31.z // VINTRP
|
||||
ds_write_b32 v255, v0 offset:65535 // DS
|
||||
ds_read_b32 v0, v255 offset:65535 // DS
|
||||
ds_write_b8 v0, v255 offset:0 // DS
|
||||
ds_write_b16 v255, v0 offset:32768 // DS
|
||||
ds_read_u8 v0, v255 offset:1 // DS
|
||||
ds_read_i16 v255, v0 offset:65534 // DS
|
||||
ds_write_b64 v255, v[254:255] offset:8 // DS
|
||||
ds_read_b64 v[0:1], v255 offset:16 // DS
|
||||
ds_write2_b32 v0, v255, v0 offset0:255 offset1:0 // DS
|
||||
ds_read2_b32 v[254:255], v0 offset0:0 offset1:255 // DS
|
||||
ds_add_u32 v255, v0 offset:65535 // DS
|
||||
ds_add_rtn_u32 v0, v255, v0 offset:1 // DS
|
||||
ds_cmpst_b32 v0, v255, v0 offset:32 // DS
|
||||
ds_bpermute_b32 v255, v0, v255 // DS
|
||||
ds_permute_b32 v0, v255, v0 // DS
|
||||
buffer_load_dword v255, off, s[100:103], 0 offset:4095 // MUBUF
|
||||
buffer_load_dword v0, v255, s[0:3], s105 offen offset:1 // MUBUF
|
||||
buffer_load_dword v255, v0, s[0:3], 0 idxen // MUBUF
|
||||
buffer_load_dword v0, v[254:255], s[0:3], 0 idxen offen glc slc // MUBUF
|
||||
buffer_load_ubyte v255, off, s[0:3], 0 // MUBUF
|
||||
buffer_load_sshort v0, off, s[0:3], 0 // MUBUF
|
||||
buffer_load_dwordx2 v[254:255], off, s[0:3], 0 offset:4095 // MUBUF
|
||||
buffer_load_dwordx3 v[0:2], off, s[0:3], 0 // MUBUF
|
||||
buffer_store_dwordx4 v[252:255], off, s[100:103], 0 offset:4095 // MUBUF
|
||||
buffer_store_byte v0, v255, s[0:3], s105 offen // MUBUF
|
||||
buffer_atomic_add v255, off, s[0:3], 0 glc // MUBUF
|
||||
buffer_atomic_cmpswap v[254:255], off, s[0:3], 0 glc // MUBUF
|
||||
tbuffer_load_format_x v255, off, s[100:103], 0 format:[BUF_FMT_32_UINT] offset:4095 // MTBUF
|
||||
tbuffer_load_format_xy v[0:1], v255, s[0:3], s105 format:[BUF_FMT_32_32_FLOAT] offen // MTBUF
|
||||
tbuffer_load_format_xyz v[253:255], off, s[0:3], 0 format:[BUF_FMT_32_32_32_FLOAT] // MTBUF
|
||||
tbuffer_load_format_xyzw v[0:3], off, s[0:3], 0 format:[BUF_FMT_32_32_32_32_FLOAT] // MTBUF
|
||||
tbuffer_store_format_x v255, v0, s[100:103], 0 format:[BUF_FMT_32_SINT] idxen // MTBUF
|
||||
tbuffer_store_format_xy v[254:255], off, s[0:3], 0 format:[BUF_FMT_32_32_UINT] // MTBUF
|
||||
tbuffer_store_format_xyz v[0:2], off, s[0:3], 0 format:[BUF_FMT_32_32_32_UINT] // MTBUF
|
||||
tbuffer_store_format_xyzw v[252:255], off, s[0:3], 0 format:[BUF_FMT_32_32_32_32_UINT] offset:4095 // MTBUF
|
||||
tbuffer_load_format_d16_xy v255, off, s[0:3], 0 format:[BUF_FMT_16_16_FLOAT] // MTBUF
|
||||
tbuffer_store_format_d16_xyzw v[254:255], off, s[0:3], 0 format:[BUF_FMT_16_16_16_16_FLOAT] // MTBUF
|
||||
image_load v255, v0, s[96:103] dmask:0x1 dim:SQ_RSRC_IMG_1D unorm // MIMG
|
||||
image_load_mip v[254:255], v[0:2], s[0:7] dmask:0x9 dim:SQ_RSRC_IMG_2D unorm // MIMG
|
||||
image_store v255, v[0:1], s[0:7] dmask:0x8 dim:SQ_RSRC_IMG_2D unorm // MIMG
|
||||
image_sample v[252:255], [v255,v0], s[0:7], s[100:103] dmask:0xf dim:SQ_RSRC_IMG_2D // MIMG
|
||||
image_sample v255, [v0,v128,v255], s[0:7], s[8:11] dmask:0x1 dim:SQ_RSRC_IMG_3D // MIMG
|
||||
image_sample_c v[254:255], [v255,v5,v1,v0], s[0:7], s[8:11] dmask:0x5 dim:SQ_RSRC_IMG_2D_ARRAY // MIMG
|
||||
image_sample_c_l v255, [v0,v2,v4,v6,v255], s[0:7], s[8:11] dmask:0x1 dim:SQ_RSRC_IMG_2D_ARRAY // MIMG
|
||||
image_sample_d v255, [v0,v2,v4,v6,v8,v255], s[0:7], s[8:11] dmask:0x1 dim:SQ_RSRC_IMG_2D // MIMG
|
||||
image_sample_d v0, [v255,v2,v4,v6,v8,v10,v12,v14,v16], s[0:7], s[8:11] dmask:0x1 dim:SQ_RSRC_IMG_3D // MIMG
|
||||
image_gather4 v[252:255], v[0:1], s[0:7], s[8:11] dmask:0x8 dim:SQ_RSRC_IMG_2D // MIMG
|
||||
image_atomic_add v255, v[0:1], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc // MIMG
|
||||
image_sample_d_cl v255, [v0,v2,v4,v6,v8,v10,v12,v14,v16,v18], s[0:7], s[8:11] dmask:0x1 dim:SQ_RSRC_IMG_3D // MIMG
|
||||
image_sample_c_d_cl v0, [v0,v2,v4,v6,v8,v10,v12,v14,v16,v18,v20], s[0:7], s[8:11] dmask:0x1 dim:SQ_RSRC_IMG_3D // MIMG
|
||||
exp mrt0 v255, off, off, v0 done // EXP
|
||||
exp mrt7 off, v255, v0, off // EXP
|
||||
exp pos0 v0, v255, v0, v255 done // EXP
|
||||
exp pos3 v255, v0, v255, v0 // EXP
|
||||
exp param0 v255, off, v0, off // EXP
|
||||
exp param31 v0, v255, off, off // EXP
|
||||
exp null off, off, off, off done // EXP
|
||||
flat_load_dword v255, v[0:1] offset:2047 // FLAT
|
||||
flat_load_dword v0, v[254:255] offset:1024 // FLAT
|
||||
flat_load_ubyte v255, v[0:1] offset:0 // FLAT
|
||||
flat_load_sbyte v0, v[254:255] glc // FLAT
|
||||
flat_load_dwordx2 v[254:255], v[0:1] slc // FLAT
|
||||
flat_load_dwordx4 v[0:3], v[254:255] // FLAT
|
||||
flat_store_dword v[254:255], v0 offset:2047 // FLAT
|
||||
flat_store_short v[0:1], v255 offset:1 // FLAT
|
||||
flat_atomic_add v255, v[0:1], v255 glc // FLAT
|
||||
flat_atomic_swap v[254:255], v0 // FLAT
|
||||
global_load_dword v255, v[0:1], off offset:-2048 // GLOBAL
|
||||
global_load_dword v0, v255, s[104:105] offset:2047 // GLOBAL
|
||||
global_load_ubyte v255, v0, s[0:1] // GLOBAL
|
||||
global_load_dwordx3 v[253:255], v[0:1], off glc // GLOBAL
|
||||
global_store_dword v255, v0, s[104:105] offset:-2048 // GLOBAL
|
||||
global_store_dwordx4 v[254:255], v[0:3], off offset:2047 // GLOBAL
|
||||
global_store_byte v0, v255, s[0:1] // GLOBAL
|
||||
global_atomic_or v255, v0, v255, s[104:105] glc // GLOBAL
|
||||
global_atomic_add v[254:255], v0, off // GLOBAL
|
||||
scratch_load_dword v255, v0, off offset:2047 // SCRATCH
|
||||
scratch_load_dword v0, off, s105 offset:-2048 // SCRATCH
|
||||
scratch_load_ushort v255, v0, off // SCRATCH
|
||||
scratch_load_dwordx2 v[254:255], off, s0 // SCRATCH
|
||||
scratch_load_dwordx4 v[0:3], v255, off // SCRATCH
|
||||
scratch_store_dword v255, v0, off offset:-2048 // SCRATCH
|
||||
scratch_store_dword off, v255, s0 offset:2047 // SCRATCH
|
||||
scratch_store_byte v0, v255, off // SCRATCH
|
||||
scratch_store_dwordx4 off, v[252:255], s105 // SCRATCH
|
||||
// Forms the byte probes could not reach with legal operands (FLAT SADDR, DS GDS, BVH).
|
||||
ds_gws_init v1 offset:65535 gds // DS
|
||||
ds_gws_barrier v1 offset:0 gds // DS
|
||||
ds_gws_sema_v gds // DS
|
||||
ds_gws_sema_br v1 gds // DS
|
||||
ds_gws_sema_p gds // DS
|
||||
ds_gws_sema_release_all gds // DS
|
||||
ds_ordered_count v0, v1 offset:65535 gds // DS
|
||||
flat_load_dwordx3 v[0:2], v[254:255] offset:2047 // FLAT
|
||||
flat_load_sshort v255, v[254:255] offset:2047 // FLAT
|
||||
flat_load_ushort v0, v[254:255] offset:2047 // FLAT
|
||||
flat_load_sbyte_d16 v0, v[254:255] offset:2047 // FLAT
|
||||
flat_load_sbyte_d16_hi v0, v[254:255] offset:2047 // FLAT
|
||||
flat_load_short_d16 v0, v[254:255] offset:2047 // FLAT
|
||||
flat_load_short_d16_hi v0, v[254:255] offset:2047 // FLAT
|
||||
flat_load_ubyte_d16 v0, v[254:255] offset:2047 // FLAT
|
||||
flat_load_ubyte_d16_hi v0, v[254:255] offset:2047 // FLAT
|
||||
flat_store_byte v[0:1], v2 // FLAT
|
||||
flat_store_byte_d16_hi v[0:1], v2 // FLAT
|
||||
flat_store_dwordx2 v[0:1], v[2:3] // FLAT
|
||||
flat_store_dwordx3 v[0:1], v[2:4] // FLAT
|
||||
flat_store_dwordx4 v[0:1], v[2:5] // FLAT
|
||||
flat_store_short_d16_hi v[0:1], v2 // FLAT
|
||||
flat_atomic_add v0, v[0:1], v2 glc // FLAT
|
||||
flat_atomic_add_x2 v[0:1], v[2:3] // FLAT
|
||||
flat_atomic_and v0, v[0:1], v2 glc // FLAT
|
||||
flat_atomic_and_x2 v[0:1], v[2:3] // FLAT
|
||||
flat_atomic_dec v0, v[0:1], v2 glc // FLAT
|
||||
flat_atomic_dec_x2 v[0:1], v[2:3] // FLAT
|
||||
flat_atomic_inc v0, v[0:1], v2 glc // FLAT
|
||||
flat_atomic_inc_x2 v[0:1], v[2:3] // FLAT
|
||||
flat_atomic_or v0, v[0:1], v2 glc // FLAT
|
||||
flat_atomic_or_x2 v[0:1], v[2:3] // FLAT
|
||||
flat_atomic_smax v0, v[0:1], v2 glc // FLAT
|
||||
flat_atomic_smax_x2 v[0:1], v[2:3] // FLAT
|
||||
flat_atomic_smin v0, v[0:1], v2 glc // FLAT
|
||||
flat_atomic_smin_x2 v[0:1], v[2:3] // FLAT
|
||||
flat_atomic_sub v0, v[0:1], v2 glc // FLAT
|
||||
flat_atomic_sub_x2 v[0:1], v[2:3] // FLAT
|
||||
flat_atomic_umax v0, v[0:1], v2 glc // FLAT
|
||||
flat_atomic_umax_x2 v[0:1], v[2:3] // FLAT
|
||||
flat_atomic_umin v0, v[0:1], v2 glc // FLAT
|
||||
flat_atomic_umin_x2 v[0:1], v[2:3] // FLAT
|
||||
flat_atomic_xor v0, v[0:1], v2 glc // FLAT
|
||||
flat_atomic_xor_x2 v[0:1], v[2:3] // FLAT
|
||||
flat_atomic_fmax v0, v[0:1], v2 glc // FLAT
|
||||
flat_atomic_fmax_x2 v[0:1], v[2:3] // FLAT
|
||||
flat_atomic_fmin v0, v[0:1], v2 glc // FLAT
|
||||
flat_atomic_fmin_x2 v[0:1], v[2:3] // FLAT
|
||||
flat_atomic_swap_x2 v[0:1], v[2:3] offset:2047 // FLAT
|
||||
flat_atomic_cmpswap v0, v[0:1], v[2:3] glc // FLAT
|
||||
flat_atomic_cmpswap_x2 v[0:1], v[2:5] // FLAT
|
||||
flat_atomic_fcmpswap v[0:1], v[2:3] // FLAT
|
||||
flat_atomic_fcmpswap_x2 v[0:1], v[2:5] // FLAT
|
||||
image_bvh_intersect_ray v[0:3], v[0:10], s[0:3] // MIMG
|
||||
image_bvh64_intersect_ray v[0:3], v[0:11], s[0:3] // MIMG
|
||||
image_bvh_intersect_ray v[0:3], [v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14], s[0:3] // MIMG
|
||||
v_interp_p1ll_f16 v0, v1, attr0.x // VOP3
|
||||
v_interp_p1lv_f16 v0, v1, attr0.x, v2 // VOP3
|
||||
v_interp_p2_f16 v0, v1, attr0.x, v2 // VOP3
|
||||
v_mqsad_u32_u8 v[0:3], v[2:3], v4, v[4:7] // VOP3
|
||||
v_permlane16_b32 v0, v1, s2, s3 // VOP3
|
||||
v_permlanex16_b32 v255, v1, s105, m0 op_sel:[1,1] // VOP3
|
||||
v_swaprel_b32 v0, v1 // VOP1
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,132 +0,0 @@
|
||||
# Rows of the asm, probe-zero and probe-ext sources where identify and LLVM do not simply agree
|
||||
# (neither `identified` nor `both_reject`), as `class hex`, sorted by hex. Pinned by meta_corpus.rs;
|
||||
# review each change against LLVM.
|
||||
operand_flagged 000000d60000000000000000000000000000000000000000
|
||||
operand_flagged 000000d6ff00000078563412000000000000000000000000
|
||||
metadata_only 000000dd0000000000000000000000000000000000000000
|
||||
operand_flagged 000001d60000000000000000000000000000000000000000
|
||||
operand_flagged 000001d6ff00000078563412000000000000000000000000
|
||||
metadata_only 000008f10000000000000000000000000000000000000000
|
||||
metadata_only 00000cf10000000000000000000000000000000000000000
|
||||
metadata_only 000020dc0000000000000000000000000000000000000000
|
||||
metadata_only 000024dc0000000000000000000000000000000000000000
|
||||
metadata_only 000028dc0000000000000000000000000000000000000000
|
||||
metadata_only 000028f10000000000000000000000000000000000000000
|
||||
metadata_only 00002cdc0000000000000000000000000000000000000000
|
||||
metadata_only 00002cf10000000000000000000000000000000000000000
|
||||
metadata_only 000030dc0000000000000000000000000000000000000000
|
||||
metadata_only 000034dc0000000000000000000000000000000000000000
|
||||
metadata_only 000038dc0000000000000000000000000000000000000000
|
||||
metadata_only 00003cdc0000000000000000000000000000000000000000
|
||||
metadata_only 000040dd0000000000000000000000000000000000000000
|
||||
operand_flagged 000042d70000000000000000000000000000000000000000
|
||||
operand_flagged 000042d7ff00000078563412000000000000000000000000
|
||||
operand_flagged 000043d70000000000000000000000000000000000000000
|
||||
operand_flagged 000043d7ff00000078563412000000000000000000000000
|
||||
metadata_only 000044dd0000000000000000000000000000000000000000
|
||||
metadata_only 000048dd0000000000000000000000000000000000000000
|
||||
metadata_only 000048f10000000000000000000000000000000000000000
|
||||
metadata_only 00004cdd0000000000000000000000000000000000000000
|
||||
metadata_only 00004cf10000000000000000000000000000000000000000
|
||||
metadata_only 000054dd0000000000000000000000000000000000000000
|
||||
metadata_only 000058dd0000000000000000000000000000000000000000
|
||||
operand_flagged 00005ad70000000000000000000000000000000000000000
|
||||
operand_flagged 00005ad7ff00000078563412000000000000000000000000
|
||||
metadata_only 00005cdd0000000000000000000000000000000000000000
|
||||
operand_flagged 000060d70000000000000000000000000000000000000000
|
||||
metadata_only 000060d80000000000000000000000000000000000000000
|
||||
metadata_only 000060dc0000000000000000000000000000000000000000
|
||||
metadata_only 000060dd0000000000000000000000000000000000000000
|
||||
metadata_only 000064d80000000000000000000000000000000000000000
|
||||
metadata_only 000064dc0000000000000000000000000000000000000000
|
||||
metadata_only 000064dd0000000000000000000000000000000000000000
|
||||
metadata_only 000068d80000000000000000000000000000000000000000
|
||||
metadata_only 000068dc0000000000000000000000000000000000000000
|
||||
metadata_only 000068dd0000000000000000000000000000000000000000
|
||||
metadata_only 000068f10000000000000000000000000000000000000000
|
||||
metadata_only 00006cd80000000000000000000000000000000000000000
|
||||
metadata_only 00006cdc0000000000000000000000000000000000000000
|
||||
metadata_only 00006cdd0000000000000000000000000000000000000000
|
||||
metadata_only 00006cf10000000000000000000000000000000000000000
|
||||
metadata_only 000070d80000000000000000000000000000000000000000
|
||||
metadata_only 000070dc0000000000000000000000000000000000000000
|
||||
metadata_only 000070dd0000000000000000000000000000000000000000
|
||||
metadata_only 000074d80000000000000000000000000000000000000000
|
||||
metadata_only 000074dc0000000000000000000000000000000000000000
|
||||
metadata_only 000074dd0000000000000000000000000000000000000000
|
||||
operand_flagged 000075d50000000000000000000000000000000000000000
|
||||
operand_flagged 000075d5ff00000078563412000000000000000000000000
|
||||
operand_flagged 000077d70000000000000000000000000000000000000000
|
||||
operand_flagged 000077d7ff00000078563412000000000000000000000000
|
||||
operand_flagged 000078d70000000000000000000000000000000000000000
|
||||
operand_flagged 000078d7ff00000078563412000000000000000000000000
|
||||
metadata_only 000078dc0000000000000000000000000000000000000000
|
||||
metadata_only 000078dd0000000000000000000000000000000000000000
|
||||
metadata_only 00007cdc0000000000000000000000000000000000000000
|
||||
metadata_only 00007cdd0000000000000000000000000000000000000000
|
||||
oracle_only 000080d5ff00000078563412000000000000000000000000
|
||||
metadata_only 000080dc0000000000000000000000000000000000000000
|
||||
metadata_only 000080dd0000000000000000000000000000000000000000
|
||||
metadata_only 000082d50000000000000000000000000000000000000000
|
||||
metadata_only 000084dc0000000000000000000000000000000000000000
|
||||
metadata_only 000088dc0000000000000000000000000000000000000000
|
||||
metadata_only 000088f10000000000000000000000000000000000000000
|
||||
metadata_only 00008cdc0000000000000000000000000000000000000000
|
||||
metadata_only 00008cf10000000000000000000000000000000000000000
|
||||
metadata_only 000090dc0000000000000000000000000000000000000000
|
||||
metadata_only 000094dc0000000000000000000000000000000000000000
|
||||
oracle_only 00009bd5ff00000078563412000000000000000000000000
|
||||
metadata_only 0000c0dc0000000000000000000000000000000000000000
|
||||
metadata_only 0000c0f10000000000000000000000000000000000000000
|
||||
oracle_only 0000c1d5ff00000078563412000000000000000000000000
|
||||
operand_flagged 0000c3d50000000000000000000000000000000000000000
|
||||
operand_flagged 0000c4d50000000000000000000000000000000000000000
|
||||
metadata_only 0000c4dc0000000000000000000000000000000000000000
|
||||
metadata_only 0000c4f10000000000000000000000000000000000000000
|
||||
operand_flagged 0000c8d50000000000000000000000000000000000000000
|
||||
metadata_only 0000c8dc0000000000000000000000000000000000000000
|
||||
metadata_only 0000ccdc0000000000000000000000000000000000000000
|
||||
metadata_only 0000ccf10000000000000000000000000000000000000000
|
||||
metadata_only 0000d0f10000000000000000000000000000000000000000
|
||||
metadata_only 0000d4dc0000000000000000000000000000000000000000
|
||||
metadata_only 0000d8dc0000000000000000000000000000000000000000
|
||||
metadata_only 0000d8f10000000000000000000000000000000000000000
|
||||
metadata_only 0000dcdc0000000000000000000000000000000000000000
|
||||
metadata_only 0000dcf10000000000000000000000000000000000000000
|
||||
metadata_only 0000e0dc0000000000000000000000000000000000000000
|
||||
metadata_only 0000e4dc0000000000000000000000000000000000000000
|
||||
metadata_only 0000e4f10000000000000000000000000000000000000000
|
||||
metadata_only 0000e8dc0000000000000000000000000000000000000000
|
||||
metadata_only 0000e8f10000000000000000000000000000000000000000
|
||||
metadata_only 0000ecdc0000000000000000000000000000000000000000
|
||||
metadata_only 0000f0dc0000000000000000000000000000000000000000
|
||||
metadata_only 0000f4dc0000000000000000000000000000000000000000
|
||||
metadata_only 0000f8dc0000000000000000000000000000000000000000
|
||||
metadata_only 0000fcd80000000000000000000000000000000000000000
|
||||
metadata_only 0000fcdc0000000000000000000000000000000000000000
|
||||
operand_flagged 0004007e00000000000000000000000000000000
|
||||
operand_flagged 0086007e00000000000000000000000000000000
|
||||
operand_flagged 0088007e00000000000000000000000000000000
|
||||
operand_flagged 0090007e00000000000000000000000000000000
|
||||
operand_flagged 00ca007e00000000000000000000000000000000
|
||||
operand_flagged 00d0007e00000000000000000000000000000000
|
||||
metadata_only 010098f10000000000000000000000000000000000000000
|
||||
metadata_only 01009cf10000000000000000000000000000000000000000
|
||||
oracle_only e900007e0088c6fa000000000000000000000000
|
||||
oracle_only e936007e0088c6fa000000000000000000000000
|
||||
oracle_only e982007e0088c6fa000000000000000000000000
|
||||
oracle_only ea00007e0088c6fa000000000000000000000000
|
||||
oracle_only ea36007e0088c6fa000000000000000000000000
|
||||
oracle_only ea82007e0088c6fa000000000000000000000000
|
||||
oracle_only f900007e00060600000000000000000000000000
|
||||
oracle_only f936007e00060600000000000000000000000000
|
||||
oracle_only f982007e00060600000000000000000000000000
|
||||
oracle_only fa00007e00e400ff000000000000000000000000
|
||||
oracle_only fa36007e00e400ff000000000000000000000000
|
||||
oracle_only fa82007e00e400ff000000000000000000000000
|
||||
oracle_only ff00007e78563412000000000000000000000000
|
||||
oracle_only ff1f80be78563412000000000000000000000000
|
||||
oracle_only ff2180be78563412000000000000000000000000
|
||||
oracle_only ff36007e78563412000000000000000000000000
|
||||
oracle_only ff4980be78563412000000000000000000000000
|
||||
oracle_only ff82007e78563412000000000000000000000000
|
||||
@@ -1,41 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// One instruction per line for each family and extension word; checked against llvm-mc.
|
||||
s_mov_b32 s0, 0x12345678
|
||||
s_add_u32 s0, s1, 0x1234
|
||||
s_cmp_eq_u32 s0, 0xdeadbeef
|
||||
s_movk_i32 s0, 0x1234
|
||||
s_setreg_imm32_b32 hwreg(HW_REG_MODE), 0x0
|
||||
s_load_dwordx4 s[0:3], s[4:5], 0x10
|
||||
s_nop 0
|
||||
s_endpgm
|
||||
v_mov_b32 v0, 0x12345678
|
||||
v_mov_b32_sdwa v0, v1 dst_sel:BYTE_0 dst_unused:UNUSED_PAD src0_sel:DWORD
|
||||
v_mov_b32_dpp v0, v1 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf
|
||||
v_mov_b32_dpp v0, v1 dpp8:[1,0,3,2,5,4,7,6]
|
||||
v_mov_b32_dpp v0, v1 dpp8:[1,0,3,2,5,4,7,6] fi:1
|
||||
v_add_f32_sdwa v0, v1, v2 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_1 src1_sel:DWORD
|
||||
v_add_f32_dpp v0, v1, v2 row_shl:1 row_mask:0xf bank_mask:0xf
|
||||
v_cmp_eq_u32_e32 vcc_lo, 0x1234, v1
|
||||
v_cmp_eq_u32_sdwa s0, v1, v2 src0_sel:DWORD src1_sel:DWORD
|
||||
v_fmamk_f32 v0, v1, 0x40000000, v2
|
||||
v_fmaak_f32 v0, v1, v2, 0x40000000
|
||||
v_fma_f32 v0, v1, v2, 0x3f800001
|
||||
v_add_co_u32 v0, s0, v1, v2
|
||||
v_readlane_b32 s0, v1, 0
|
||||
v_pk_add_f16 v0, v1, v2
|
||||
v_pk_fma_f16 v0, v1, v2, 0x3c01
|
||||
v_interp_p1_f32 v0, v1, attr0.x
|
||||
ds_write_b32 v0, v1
|
||||
ds_read_b32 v0, v1 offset:16
|
||||
buffer_load_dword v0, off, s[0:3], 0
|
||||
tbuffer_load_format_x v0, off, s[0:3], 0 format:[BUF_FMT_32_FLOAT]
|
||||
tbuffer_load_format_d16_x v0, off, s[0:3], 0 format:[BUF_FMT_32_FLOAT]
|
||||
tbuffer_store_format_d16_xyzw v[0:1], off, s[0:3], 0 format:[BUF_FMT_32_FLOAT]
|
||||
image_sample v[0:3], v[0:1], s[0:7], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D
|
||||
image_sample v[0:3], [v0, v2], s[0:7], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D
|
||||
image_sample_c v[0:3], [v0, v2, v4, v6], s[0:7], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D_ARRAY
|
||||
image_msaa_load v[0:3], v[0:2], s[0:7] dmask:0xf dim:SQ_RSRC_IMG_2D_MSAA unorm
|
||||
flat_load_dword v0, v[0:1]
|
||||
global_load_dword v0, v[0:1], off
|
||||
scratch_load_dword v0, v1, off
|
||||
exp mrt0 v0, v0, v0, v0 done
|
||||
@@ -1,230 +0,0 @@
|
||||
//! Instruction identification against LLVM-assembled fixtures and hand-assembled words.
|
||||
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
use xenora_isa::meta::{
|
||||
EncodingFamily, Extensions, FORMS, IdentifyError, VectorControl, identify, inventory, lookup,
|
||||
};
|
||||
|
||||
fn words(values: &[u32]) -> Vec<u8> {
|
||||
values
|
||||
.iter()
|
||||
.flat_map(|value| value.to_le_bytes())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn name_of(values: &[u32]) -> (&'static str, usize) {
|
||||
let found = identify(&words(values)).unwrap();
|
||||
(found.form.name, found.len)
|
||||
}
|
||||
|
||||
/// Mnemonics in a fixture's assembly source, without LLVM's encoding suffixes.
|
||||
fn source_mnemonics(source: &str) -> Vec<String> {
|
||||
source
|
||||
.lines()
|
||||
.map(|line| line.split("//").next().unwrap().trim())
|
||||
.filter(|line| !line.is_empty() && !line.starts_with('.') && !line.ends_with(':'))
|
||||
.map(|line| {
|
||||
let mnemonic = line.split_whitespace().next().unwrap().to_ascii_uppercase();
|
||||
mnemonic
|
||||
.trim_end_matches("_E32")
|
||||
.trim_end_matches("_E64")
|
||||
.to_owned()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn llvm_fixtures_identify_with_exact_boundaries_and_mnemonics() {
|
||||
let directory = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/rdna2");
|
||||
let mut checked = 0;
|
||||
for entry in fs::read_dir(&directory).unwrap() {
|
||||
let path = entry.unwrap().path();
|
||||
if path.extension().is_none_or(|extension| extension != "bin") {
|
||||
continue;
|
||||
}
|
||||
let binary = fs::read(&path).unwrap();
|
||||
let source = fs::read_to_string(path.with_extension("s")).unwrap();
|
||||
let mut offset = 0;
|
||||
let mut identified = Vec::new();
|
||||
while offset < binary.len() {
|
||||
let found = identify(&binary[offset..])
|
||||
.unwrap_or_else(|error| panic!("{} at {offset:#x}: {error}", path.display()));
|
||||
identified.push(found.form.name.to_owned());
|
||||
offset += found.len;
|
||||
}
|
||||
assert_eq!(offset, binary.len(), "{}", path.display());
|
||||
assert_eq!(identified, source_mnemonics(&source), "{}", path.display());
|
||||
checked += 1;
|
||||
}
|
||||
assert!(checked >= 11, "only {checked} fixtures found");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hand_assembled_words_identify() {
|
||||
// SOPP s_endpgm (opcode 1), SOP1 s_mov_b32 s0, s1 (opcode 3).
|
||||
assert_eq!(name_of(&[0xbf81_0000]), ("S_ENDPGM", 4));
|
||||
assert_eq!(name_of(&[0xbe80_0301]), ("S_MOV_B32", 4));
|
||||
// VOP1 v_mov_b32 v0, v1: SRC0 = 256 + 1.
|
||||
assert_eq!(name_of(&[0x7e00_0301]), ("V_MOV_B32", 4));
|
||||
// VOP2 v_add_f32 v0, v1, v2: opcode 3 at bits 30:25, VSRC1 = 2 at bits 16:9.
|
||||
assert_eq!(name_of(&[0x0600_0501]), ("V_ADD_F32", 4));
|
||||
// VOP3 v_add_f32_e64 v0, v1, v2 (LLVM 23 encoding): opcode 259 = 256 + VOP2 opcode 3.
|
||||
assert_eq!(name_of(&[0xd503_0000, 0x0202_0501]), ("V_ADD_F32", 8));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_sdwa_and_dpp_words_extend_the_length() {
|
||||
// v_mov_b32 v0, 0x12345678: SRC0 = 255 selects a literal.
|
||||
let literal = identify(&words(&[0x7e00_02ff, 0x1234_5678])).unwrap();
|
||||
assert_eq!((literal.form.name, literal.len), ("V_MOV_B32", 8));
|
||||
assert!(literal.trailer.literal);
|
||||
// s_add_u32 s0, s1, literal: SSRC1 = 255.
|
||||
assert_eq!(name_of(&[0x8000_ff01, 0x0000_1234]), ("S_ADD_U32", 8));
|
||||
// VOP3 with SRC2 = 255.
|
||||
let fma = identify(&words(&[0xd54b_0000, 0x03fe_0501, 0x3f80_0000]));
|
||||
assert!(matches!(fma, Ok(found) if found.len == 12 && found.trailer.literal));
|
||||
let sdwa = identify(&words(&[0x7e00_02f9, 0x0006_0601])).unwrap();
|
||||
assert_eq!(sdwa.trailer.vector_control, Some(VectorControl::Sdwa));
|
||||
assert_eq!(sdwa.len, 8);
|
||||
let dpp16 = identify(&words(&[0x7e00_02fa, 0x00ff_0001])).unwrap();
|
||||
assert_eq!(dpp16.trailer.vector_control, Some(VectorControl::Dpp16));
|
||||
let dpp8 = identify(&words(&[0x7e00_02ea, 0x00fa_c688])).unwrap();
|
||||
assert_eq!(
|
||||
dpp8.trailer.vector_control,
|
||||
Some(VectorControl::Dpp8 {
|
||||
fetch_inactive: true
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vop3_interpolation_attribute_fields_never_select_a_literal() {
|
||||
// AMD RDNA 2 ISA guide section 10.4.2: in the VOP3 interpolation forms SRC0
|
||||
// holds {attr_word, attr_chan, attr} bit-fields (XML OPR_ATTR), so SRC0 = 255
|
||||
// is attr 63, channel w (and attr_word 0) and the instruction is 8 bytes.
|
||||
// LLVM 23.1.6 agrees (#235).
|
||||
for (first, name) in [
|
||||
(0xd600_0000, "V_INTERP_P1_F32"),
|
||||
(0xd601_0000, "V_INTERP_P2_F32"),
|
||||
(0xd602_0000, "V_INTERP_MOV_F32"),
|
||||
(0xd742_0000, "V_INTERP_P1LL_F16"),
|
||||
(0xd743_0000, "V_INTERP_P1LV_F16"),
|
||||
(0xd75a_0000, "V_INTERP_P2_F16"),
|
||||
] {
|
||||
let found = identify(&words(&[first, 0x0000_00ff, 0x1234_5678])).unwrap();
|
||||
assert_eq!((found.form.name, found.len), (name, 8));
|
||||
assert!(!found.trailer.literal, "{name}");
|
||||
}
|
||||
// A general VOP3 source with the same selector still takes the literal.
|
||||
let add = identify(&words(&[0xd503_0000, 0x0000_00ff, 0x1234_5678])).unwrap();
|
||||
assert_eq!((add.form.name, add.len), ("V_ADD_F32", 12));
|
||||
// So does a VGPR-only source (LLVM reports these 12 bytes with an invalid operand).
|
||||
let permlane = identify(&words(&[0xd777_0000, 0x0000_00ff, 0x1234_5678])).unwrap();
|
||||
assert_eq!((permlane.form.name, permlane.len), ("V_PERMLANE16_B32", 12));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncated_and_unassigned_inputs_are_rejected() {
|
||||
assert_eq!(identify(&[]), Err(IdentifyError::Truncated { needed: 4 }));
|
||||
assert_eq!(
|
||||
identify(&[0x00, 0x00, 0x81]),
|
||||
Err(IdentifyError::Truncated { needed: 4 })
|
||||
);
|
||||
// VOP3 first dword alone.
|
||||
assert_eq!(
|
||||
identify(&words(&[0xd503_0000])),
|
||||
Err(IdentifyError::Truncated { needed: 8 })
|
||||
);
|
||||
// Literal selected but absent.
|
||||
assert_eq!(
|
||||
identify(&words(&[0x7e00_02ff])),
|
||||
Err(IdentifyError::Truncated { needed: 8 })
|
||||
);
|
||||
// SOPP opcodes are 7 bits; this table has no SOPP opcode 127.
|
||||
assert!(lookup(0xbf80_0000 | (127 << 16)).is_none());
|
||||
assert_eq!(
|
||||
identify(&words(&[0xbfff_0000])),
|
||||
Err(IdentifyError::Unassigned)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extensions_outside_a_forms_metadata_are_rejected() {
|
||||
let without_sdwa = FORMS
|
||||
.iter()
|
||||
.find(|form| {
|
||||
form.family == EncodingFamily::Vop1 && !form.extensions.contains(Extensions::SDWA)
|
||||
})
|
||||
.expect("a VOP1 form without SDWA");
|
||||
let word = (without_sdwa.bits as u32) | 0xf9;
|
||||
assert_eq!(
|
||||
identify(&words(&[word, 0])),
|
||||
Err(IdentifyError::InvalidExtension("sdwa"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_form_identifies_as_itself() {
|
||||
for form in &FORMS {
|
||||
assert_eq!(lookup(form.bits).map(|found| found.name), Some(form.name));
|
||||
assert_eq!(
|
||||
lookup(form.bits).unwrap().family,
|
||||
form.family,
|
||||
"{}",
|
||||
form.name
|
||||
);
|
||||
}
|
||||
let total: usize = inventory().iter().map(|(_, count)| count).sum();
|
||||
assert_eq!(total, FORMS.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn documented_form_counts_match_the_generated_table() {
|
||||
let count = FORMS.len();
|
||||
let count = format!("{},{:03}", count / 1000, count % 1000);
|
||||
let families = EncodingFamily::ALL.len();
|
||||
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
|
||||
for (file, claim) in [
|
||||
(
|
||||
"docs/research/rdna2.md",
|
||||
format!("{count} forms in {families} encoding families"),
|
||||
),
|
||||
(
|
||||
"CHANGELOG.md",
|
||||
format!("{count} base forms across {families} encoding families"),
|
||||
),
|
||||
] {
|
||||
let text = fs::read_to_string(root.join(file)).unwrap();
|
||||
assert!(
|
||||
text.split_whitespace()
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ")
|
||||
.contains(&claim),
|
||||
"{file} must state \"{claim}\""
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_word_opcode_table_agrees_with_full_metadata() {
|
||||
use xenora_isa::{BUFFER_LOAD_DWORD, S_ENDPGM, V_ADD_F32, V_ADD_NC_U32, V_MOV_B32};
|
||||
for (opcode, name, family) in [
|
||||
(
|
||||
BUFFER_LOAD_DWORD,
|
||||
"BUFFER_LOAD_DWORD",
|
||||
EncodingFamily::Mubuf,
|
||||
),
|
||||
(S_ENDPGM, "S_ENDPGM", EncodingFamily::Sopp),
|
||||
(V_ADD_F32, "V_ADD_F32", EncodingFamily::Vop2),
|
||||
(V_ADD_NC_U32, "V_ADD_NC_U32", EncodingFamily::Vop3),
|
||||
(V_MOV_B32, "V_MOV_B32", EncodingFamily::Vop1),
|
||||
] {
|
||||
let form = FORMS
|
||||
.iter()
|
||||
.find(|form| form.name == name && form.family == family)
|
||||
.unwrap();
|
||||
assert!(opcode.matches(form.bits as u32), "{name}");
|
||||
}
|
||||
}
|
||||
@@ -1,304 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
//! Independent LLVM corpus check of gfx1030 instruction identification (#209).
|
||||
//!
|
||||
//! `llvm/corpus.tsv` is generated by `llvm/corpus.py` from LLVM 23.1.6 alone:
|
||||
//! llvm-mc assembles the original instructions in `llvm/corpus.s`, and
|
||||
//! llvm-objdump decodes byte probes built from each metadata form's
|
||||
//! identifying bits (one with every other bit zero, two with seeded random
|
||||
//! operand bits). The expected name, consumed length and extension of every
|
||||
//! row are LLVM's. This test compares `identify` with them and pins what it
|
||||
//! measures: per-source class counts, the exact rows where the two disagree
|
||||
//! for assembled and zero-operand inputs, and a digest of the random-probe
|
||||
//! classification.
|
||||
//!
|
||||
//! Identification is not execution support: a row counted as identified only
|
||||
//! means both agree on which instruction the bytes are and how long it is.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use xenora_isa::meta::{FORMS, Identified, IdentifyError, VectorControl, identify};
|
||||
|
||||
const CORPUS: &str = include_str!("llvm/corpus.tsv");
|
||||
|
||||
/// Row classes, in report order.
|
||||
const CLASSES: [&str; 9] = [
|
||||
"identified", // both decode: same name, length and extension
|
||||
"mismatch", // both decode, but name, length or extension differ
|
||||
"oracle_only", // LLVM decodes, identify returns an error
|
||||
"metadata_only", // identify decodes, LLVM cannot
|
||||
"both_reject", // neither decodes
|
||||
"oracle_crash", // llvm-objdump crashed; no oracle answer
|
||||
"truncated", // a proper prefix: identify asks for more bytes
|
||||
"truncation_other",
|
||||
"operand_flagged", // same instruction and length; LLVM flags an operand as invalid
|
||||
];
|
||||
const SOURCES: [&str; 5] = [
|
||||
"asm",
|
||||
"probe-zero",
|
||||
"probe-ext",
|
||||
"probe-random",
|
||||
"truncation",
|
||||
];
|
||||
|
||||
fn base_name(mnemonic: &str) -> String {
|
||||
let upper = mnemonic.to_ascii_uppercase();
|
||||
["_E32", "_E64", "_SDWA", "_DPP"]
|
||||
.into_iter()
|
||||
.find_map(|suffix| upper.strip_suffix(suffix))
|
||||
.unwrap_or(&upper)
|
||||
.to_owned()
|
||||
}
|
||||
|
||||
fn extension(found: &Identified) -> String {
|
||||
let nsa = format!("nsa{}", found.trailer.nsa_dwords);
|
||||
let mut parts = Vec::new();
|
||||
if found.trailer.literal {
|
||||
parts.push("literal");
|
||||
}
|
||||
match found.trailer.vector_control {
|
||||
Some(VectorControl::Sdwa) => parts.push("sdwa"),
|
||||
Some(VectorControl::Dpp8 {
|
||||
fetch_inactive: false,
|
||||
}) => parts.push("dpp8"),
|
||||
Some(VectorControl::Dpp8 {
|
||||
fetch_inactive: true,
|
||||
}) => parts.push("dpp8fi"),
|
||||
Some(VectorControl::Dpp16) => parts.push("dpp16"),
|
||||
None => {}
|
||||
}
|
||||
if found.trailer.nsa_dwords != 0 {
|
||||
parts.push(&nsa);
|
||||
}
|
||||
if parts.is_empty() {
|
||||
"-".into()
|
||||
} else {
|
||||
parts.join("+")
|
||||
}
|
||||
}
|
||||
|
||||
struct Row<'a> {
|
||||
source: usize,
|
||||
form: Option<&'static str>,
|
||||
family: &'a str,
|
||||
hex: &'a str,
|
||||
class: usize,
|
||||
detail: String,
|
||||
}
|
||||
|
||||
fn classify(line: &str) -> Row<'_> {
|
||||
let [source, hex, mnemonic, len, ext, note] = line.split('\t').collect::<Vec<_>>()[..] else {
|
||||
panic!("bad corpus row: {line}");
|
||||
};
|
||||
let source = SOURCES
|
||||
.iter()
|
||||
.position(|s| *s == source)
|
||||
.unwrap_or_else(|| panic!("bad source: {line}"));
|
||||
let (family, text) = note.split_once(' ').unwrap();
|
||||
let bytes: Vec<u8> = (0..hex.len())
|
||||
.step_by(2)
|
||||
.map(|i| u8::from_str_radix(&hex[i..i + 2], 16).unwrap())
|
||||
.collect();
|
||||
let len: usize = len.parse().unwrap();
|
||||
let found = identify(&bytes);
|
||||
let answer = match &found {
|
||||
Ok(found) => format!(
|
||||
"{} ({} bytes, {})",
|
||||
found.form.name,
|
||||
found.len,
|
||||
extension(found)
|
||||
),
|
||||
Err(error) => format!("{error:?}"),
|
||||
};
|
||||
let mut differences = Vec::new();
|
||||
// LLVM decoded the words but flagged an operand the instruction cannot
|
||||
// take. identify does not validate operands; it must still agree on the
|
||||
// instruction and its length, or reject the extension outright.
|
||||
let (flagged, mnemonic) = match mnemonic.strip_prefix("invalid-operand:") {
|
||||
Some(mnemonic) => (true, mnemonic),
|
||||
None => (false, mnemonic),
|
||||
};
|
||||
let class = match (mnemonic, &found) {
|
||||
("truncated", Err(IdentifyError::Truncated { needed })) if *needed > bytes.len() => 6,
|
||||
("truncated", _) => 7,
|
||||
("crashed", _) => 5,
|
||||
("invalid", Err(_)) => 4,
|
||||
("invalid", Ok(_)) => 3,
|
||||
(_, Err(IdentifyError::InvalidExtension(_))) if flagged => 4,
|
||||
(_, Err(_)) => 2,
|
||||
(_, Ok(found)) => {
|
||||
if found.form.name != base_name(mnemonic) {
|
||||
differences.push("name");
|
||||
}
|
||||
if found.len != len {
|
||||
differences.push("length");
|
||||
}
|
||||
if extension(found) != ext {
|
||||
differences.push("extension");
|
||||
}
|
||||
if !differences.is_empty() {
|
||||
1
|
||||
} else if flagged {
|
||||
8
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
};
|
||||
let kind = if differences.is_empty() {
|
||||
CLASSES[class].to_owned()
|
||||
} else {
|
||||
format!("mismatch/{}", differences.join("+"))
|
||||
};
|
||||
Row {
|
||||
source,
|
||||
form: found.ok().map(|found| found.form.name),
|
||||
family,
|
||||
hex,
|
||||
class,
|
||||
detail: format!("{kind}: {hex} | LLVM {text} ({len} bytes, {ext}) | Xenora {answer}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// FNV-1a over the sorted `class hex` lines, to pin thousands of rows compactly.
|
||||
fn digest(lines: &[String]) -> u64 {
|
||||
lines
|
||||
.iter()
|
||||
.flat_map(|l| l.bytes().chain(*b"\n"))
|
||||
.fold(0xcbf2_9ce4_8422_2325, |hash, byte| {
|
||||
(hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3)
|
||||
})
|
||||
}
|
||||
|
||||
// Measured against LLVM 23.1.6 on 2026-11-24. Any change needs the affected
|
||||
// rows reviewed against LLVM, not an update of these numbers alone.
|
||||
// Rows: one per source, columns in CLASSES order.
|
||||
const COUNTS: [[usize; 9]; 5] = [
|
||||
[317, 0, 0, 0, 0, 0, 0, 0, 0], // asm
|
||||
[1365, 0, 0, 82, 0, 0, 0, 0, 18], // probe-zero
|
||||
[1398, 0, 21, 0, 752, 0, 0, 0, 8], // probe-ext
|
||||
[1236, 0, 0, 1678, 3, 2, 0, 0, 11], // probe-random
|
||||
[0, 0, 0, 0, 0, 0, 87, 0, 0], // truncation
|
||||
];
|
||||
/// Every assembled, zero-operand or extension-probe row where the two disagree
|
||||
/// (neither `identified` nor `both_reject`), as `class hex`, sorted by hex.
|
||||
const DISAGREEMENTS: &str = include_str!("llvm/corpus_disagreements.txt");
|
||||
/// Digest of the sorted `class hex` lines of the random probes.
|
||||
const RANDOM_DIGEST: u64 = 0x32fb_5d7d_0826_ce14;
|
||||
|
||||
#[test]
|
||||
fn identification_agrees_with_the_llvm_corpus() {
|
||||
let mut lines = CORPUS.lines();
|
||||
assert_eq!(
|
||||
lines.next(),
|
||||
Some("source\thex\tllvm_mnemonic\tllvm_len\tllvm_ext\tnote")
|
||||
);
|
||||
let rows: Vec<_> = lines.map(classify).collect();
|
||||
let mut counts = [[0usize; 9]; 5];
|
||||
let mut by_family = BTreeMap::<&str, [usize; 9]>::new();
|
||||
for row in &rows {
|
||||
counts[row.source][row.class] += 1;
|
||||
by_family.entry(row.family).or_default()[row.class] += 1;
|
||||
}
|
||||
println!("{:9} {}", "family", CLASSES.join(" "));
|
||||
for (family, c) in &by_family {
|
||||
print!("{family:9}");
|
||||
for (name, n) in CLASSES.iter().zip(c) {
|
||||
print!(" {n:>w$}", w = name.len());
|
||||
}
|
||||
println!();
|
||||
}
|
||||
for (source, c) in SOURCES.iter().zip(&counts) {
|
||||
println!("{source:13} {c:?}");
|
||||
}
|
||||
let mut disagreements: Vec<_> = rows
|
||||
.iter()
|
||||
.filter(|r| r.source < 3 && !matches!(r.class, 0 | 4))
|
||||
.collect();
|
||||
disagreements.sort_unstable_by_key(|r| r.hex);
|
||||
for r in &disagreements {
|
||||
println!("{}", r.detail);
|
||||
}
|
||||
let disagreements: Vec<_> = disagreements
|
||||
.iter()
|
||||
.map(|r| format!("{} {}", CLASSES[r.class], r.hex))
|
||||
.collect();
|
||||
let mut random: Vec<_> = rows
|
||||
.iter()
|
||||
.filter(|r| r.source == 3)
|
||||
.map(|r| format!("{} {}", CLASSES[r.class], r.hex))
|
||||
.collect();
|
||||
random.sort_unstable();
|
||||
let random_digest = digest(&random);
|
||||
println!("random digest {random_digest:#018x}");
|
||||
for r in rows
|
||||
.iter()
|
||||
.filter(|r| r.source == 3 && r.class == 1)
|
||||
.take(5)
|
||||
{
|
||||
println!("random example {}", r.detail);
|
||||
}
|
||||
|
||||
// Distinct metadata forms: agreed by LLVM on at least one row, or only
|
||||
// ever decoded by Xenora (LLVM rejected every probe of that form).
|
||||
let mut forms = BTreeMap::<&str, (usize, usize)>::new();
|
||||
for row in &rows {
|
||||
if let Some(form) = row.form {
|
||||
let entry = forms.entry(form).or_default();
|
||||
match row.class {
|
||||
0 | 8 => entry.0 += 1,
|
||||
3 => entry.1 += 1,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
let agreed = forms.values().filter(|(a, _)| *a > 0).count();
|
||||
let never: Vec<_> = forms
|
||||
.iter()
|
||||
.filter(|(_, (a, m))| *a == 0 && *m > 0)
|
||||
.map(|(name, _)| *name)
|
||||
.collect();
|
||||
println!(
|
||||
"distinct forms seen {}: agreed {agreed}, metadata-only on every row {}",
|
||||
forms.len(),
|
||||
never.len()
|
||||
);
|
||||
println!("never decoded by LLVM: {}", never.join(" "));
|
||||
let mut all_names: Vec<_> = FORMS.iter().map(|form| form.name).collect();
|
||||
all_names.sort_unstable();
|
||||
all_names.dedup();
|
||||
let unseen: Vec<_> = all_names
|
||||
.iter()
|
||||
.filter(|name| !forms.contains_key(*name))
|
||||
.collect();
|
||||
println!(
|
||||
"metadata: {} forms, {} distinct names, {} names with no corpus row: {unseen:?}",
|
||||
FORMS.len(),
|
||||
all_names.len(),
|
||||
unseen.len()
|
||||
);
|
||||
assert_eq!(counts, COUNTS, "class counts per source changed");
|
||||
let pinned: Vec<_> = DISAGREEMENTS
|
||||
.lines()
|
||||
.filter(|line| !line.starts_with('#'))
|
||||
.collect();
|
||||
assert_eq!(disagreements, pinned, "disagreeing rows changed");
|
||||
assert_eq!(
|
||||
random_digest, RANDOM_DIGEST,
|
||||
"random-probe classification changed"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires LLVM with the gfx1030 AMDGPU target (set LLVM_BIN)"]
|
||||
fn llvm_corpus_is_fresh() {
|
||||
let bin = std::env::var("LLVM_BIN").expect("LLVM_BIN");
|
||||
let status = std::process::Command::new("python3")
|
||||
.arg(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/llvm/corpus.py"))
|
||||
.args(["--llvm-bin", &bin, "--check"])
|
||||
.status()
|
||||
.expect("run corpus.py");
|
||||
assert!(
|
||||
status.success(),
|
||||
"corpus.tsv differs from LLVM's current output"
|
||||
);
|
||||
}
|
||||
@@ -1,87 +0,0 @@
|
||||
//! LLVM oracle for instruction identification: names and lengths from llvm-mc encodings.
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
use xenora_isa::meta::identify;
|
||||
|
||||
const SOURCE: &str = include_str!("llvm/identify.s");
|
||||
|
||||
fn encodings() -> Vec<(String, Vec<u8>)> {
|
||||
let executable = std::env::var_os("LLVM_BIN").map_or_else(
|
||||
|| "llvm-mc".into(),
|
||||
|directory| std::path::PathBuf::from(directory).join("llvm-mc"),
|
||||
);
|
||||
let path = std::env::temp_dir().join(format!("xenora-identify-{}.s", std::process::id()));
|
||||
std::fs::write(&path, SOURCE).unwrap();
|
||||
let output = Command::new(executable)
|
||||
.args([
|
||||
"-triple=amdgcn-amd-amdhsa",
|
||||
"-mcpu=gfx1030",
|
||||
"-mattr=+wavefrontsize32",
|
||||
"-show-encoding",
|
||||
])
|
||||
.arg(&path)
|
||||
.output()
|
||||
.expect("launch llvm-mc (provide its directory in LLVM_BIN or put it on PATH)");
|
||||
std::fs::remove_file(&path).ok();
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
String::from_utf8(output.stdout)
|
||||
.unwrap()
|
||||
.lines()
|
||||
.filter_map(|line| {
|
||||
let (text, encoding) = line.split_once("; encoding: [")?;
|
||||
let mnemonic = text.split_whitespace().next()?.to_ascii_uppercase();
|
||||
let bytes = encoding
|
||||
.trim_end_matches(']')
|
||||
.split(',')
|
||||
.map(|byte| u8::from_str_radix(byte.trim().trim_start_matches("0x"), 16).unwrap())
|
||||
.collect();
|
||||
Some((mnemonic, bytes))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn base_name(mnemonic: &str) -> &str {
|
||||
["_E32", "_E64", "_SDWA", "_DPP"]
|
||||
.iter()
|
||||
.fold(mnemonic, |name, suffix| name.trim_end_matches(suffix))
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires LLVM with the gfx1030 AMDGPU target"]
|
||||
fn identification_matches_llvm_names_and_lengths() {
|
||||
let encodings = encodings();
|
||||
let expected_lines = SOURCE
|
||||
.lines()
|
||||
.filter(|line| !line.is_empty() && !line.starts_with("//"))
|
||||
.count();
|
||||
assert_eq!(encodings.len(), expected_lines);
|
||||
// The VOP3 and VOP3P literal probes must really carry a literal trailer:
|
||||
// 1.0 in either width would be an inline constant and only eight bytes.
|
||||
for (probe, literal) in [("V_FMA_F32", 0x3f80_0001_u32), ("V_PK_FMA_F16", 0x3c01)] {
|
||||
let (_, bytes) = encodings
|
||||
.iter()
|
||||
.find(|(mnemonic, _)| mnemonic == probe)
|
||||
.unwrap_or_else(|| panic!("{probe} probe missing"));
|
||||
assert_eq!(bytes.len(), 12, "{probe}");
|
||||
assert_eq!(bytes[8..], literal.to_le_bytes(), "{probe}");
|
||||
}
|
||||
let mut stream = Vec::new();
|
||||
for (mnemonic, bytes) in &encodings {
|
||||
let found = identify(bytes).unwrap_or_else(|error| panic!("{mnemonic}: {error}"));
|
||||
assert_eq!(found.form.name, base_name(mnemonic), "{mnemonic}");
|
||||
assert_eq!(found.len, bytes.len(), "{mnemonic}");
|
||||
stream.extend_from_slice(bytes);
|
||||
}
|
||||
let mut offset = 0;
|
||||
for (mnemonic, bytes) in &encodings {
|
||||
let found = identify(&stream[offset..]).unwrap();
|
||||
assert_eq!(found.len, bytes.len(), "{mnemonic} in stream");
|
||||
offset += found.len;
|
||||
}
|
||||
assert_eq!(offset, stream.len());
|
||||
}
|
||||
@@ -1,317 +0,0 @@
|
||||
//! Ties the generated semantic registry tables to the independent XML metadata table.
|
||||
|
||||
use xenora_isa::meta::{EncodingFamily, FORMS as META_FORMS};
|
||||
use xenora_isa::semantics::{
|
||||
CarryIn, FORM_IDS, FORMS, GENERATED_SCHEMA, MaskEffect, OperandRule, SCHEMA, SccEffect,
|
||||
Signedness, Wave,
|
||||
};
|
||||
use xenora_isa::{
|
||||
CompareRelation, ScalarAluOp, ScalarCompareOp, ScalarImmediateCompareOp, ScalarImmediateOp,
|
||||
ScalarUnaryOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp, VectorCompareVop3Op,
|
||||
};
|
||||
|
||||
#[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);
|
||||
}
|
||||
}
|
||||
|
||||
/// Every word of `family` that the XML metadata identifies selects an operation
|
||||
/// exactly when the registry declares that form, and no 32-bit word of another
|
||||
/// family selects one.
|
||||
fn dispatch_selects_exactly(family: EncodingFamily, select: impl Fn(u32) -> Option<&'static str>) {
|
||||
let declared: Vec<_> = FORMS.iter().filter(|row| row.family == family).collect();
|
||||
let mut selected = 0;
|
||||
for meta in META_FORMS.iter().filter(|form| form.family == family) {
|
||||
match select(meta.bits as u32) {
|
||||
Some(name) => {
|
||||
assert_eq!(name, meta.name);
|
||||
selected += 1;
|
||||
}
|
||||
None => assert!(
|
||||
declared.iter().all(|row| row.name != meta.name),
|
||||
"{} is declared but not dispatched",
|
||||
meta.name
|
||||
),
|
||||
}
|
||||
}
|
||||
assert_eq!(selected, declared.len());
|
||||
for meta in META_FORMS
|
||||
.iter()
|
||||
.filter(|form| form.family != family && form.bytes == 4)
|
||||
{
|
||||
assert_eq!(select(meta.bits as u32), None, "{}", meta.name);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_alu_dispatch_selects_exactly_the_registry_sop2_forms() {
|
||||
for op in ScalarAluOp::ALL {
|
||||
let row = op.semantics();
|
||||
assert_eq!(row.family, EncodingFamily::Sop2);
|
||||
assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic());
|
||||
assert_eq!(op.reads_scc(), row.carry_in == CarryIn::Scc);
|
||||
assert_eq!(op.writes_scc(), row.scc != SccEffect::Unchanged);
|
||||
}
|
||||
dispatch_selects_exactly(EncodingFamily::Sop2, |word| {
|
||||
ScalarAluOp::from_word(word).map(|op| op.semantics().name)
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_compare_dispatch_selects_exactly_the_registry_sopc_forms() {
|
||||
for op in ScalarCompareOp::ALL {
|
||||
let row = op.semantics();
|
||||
assert_eq!(row.family, EncodingFamily::Sopc);
|
||||
assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic());
|
||||
assert_eq!(row.relation, Some(op.relation()));
|
||||
}
|
||||
dispatch_selects_exactly(EncodingFamily::Sopc, |word| {
|
||||
ScalarCompareOp::from_word(word).map(|op| op.semantics().name)
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_immediate_dispatch_selects_exactly_the_registry_sopk_forms() {
|
||||
for op in ScalarImmediateOp::ALL {
|
||||
let row = op.semantics();
|
||||
assert_eq!(row.family, EncodingFamily::Sopk);
|
||||
assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic());
|
||||
assert_eq!(op.reads_scc(), row.carry_in == CarryIn::Scc);
|
||||
assert_eq!(op.writes_scc(), row.scc != SccEffect::Unchanged);
|
||||
}
|
||||
for op in ScalarImmediateCompareOp::ALL {
|
||||
let row = op.semantics();
|
||||
assert_eq!(row.family, EncodingFamily::Sopk);
|
||||
assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic());
|
||||
assert_eq!(row.relation, Some(op.relation()));
|
||||
}
|
||||
// The two enums together are the registry's SOPK forms; the fixed
|
||||
// s_waitcnt_vscnt word (opcode 23) stays hand-written and is in neither.
|
||||
dispatch_selects_exactly(EncodingFamily::Sopk, |word| {
|
||||
ScalarImmediateOp::from_word(word)
|
||||
.map(|op| op.semantics().name)
|
||||
.or_else(|| ScalarImmediateCompareOp::from_word(word).map(|op| op.semantics().name))
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_immediate_evaluation_extends_simm16_as_the_form_declares() {
|
||||
// SIMM16 = 0x8000 is -32768 signed and 32768 unsigned.
|
||||
let d = 0xffff_8000;
|
||||
assert_eq!(
|
||||
ScalarImmediateOp::MovkI32.evaluate(0, 0x8000, false),
|
||||
(Some(d), None)
|
||||
);
|
||||
assert_eq!(
|
||||
ScalarImmediateOp::CmovkI32.evaluate(7, 0x8000, true),
|
||||
(Some(d), None)
|
||||
);
|
||||
assert_eq!(
|
||||
ScalarImmediateOp::CmovkI32.evaluate(7, 0x8000, false),
|
||||
(None, None)
|
||||
);
|
||||
assert_eq!(
|
||||
ScalarImmediateOp::AddkI32.evaluate(0x7fff_ffff, 1, false),
|
||||
(Some(0x8000_0000), Some(true))
|
||||
);
|
||||
assert_eq!(
|
||||
ScalarImmediateOp::AddkI32.evaluate(5, 0xffff, false),
|
||||
(Some(4), Some(false))
|
||||
);
|
||||
assert_eq!(
|
||||
ScalarImmediateOp::MulkI32.evaluate(3, 0xffff, true),
|
||||
(Some(0xffff_fffd), None)
|
||||
);
|
||||
assert!(ScalarImmediateCompareOp::CmpkEqI32.test(d, 0x8000));
|
||||
assert!(!ScalarImmediateCompareOp::CmpkEqU32.test(d, 0x8000));
|
||||
assert!(ScalarImmediateCompareOp::CmpkGtU32.test(d, 0xffff));
|
||||
assert!(!ScalarImmediateCompareOp::CmpkGtI32.test(d, 0xffff));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_unary_dispatch_selects_exactly_the_registry_sop1_forms() {
|
||||
for op in ScalarUnaryOp::ALL {
|
||||
let row = op.semantics();
|
||||
assert_eq!(row.family, EncodingFamily::Sop1);
|
||||
assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic());
|
||||
assert_eq!(op.writes_scc(), row.scc != SccEffect::Unchanged);
|
||||
}
|
||||
dispatch_selects_exactly(EncodingFamily::Sop1, |word| {
|
||||
ScalarUnaryOp::from_word(word).map(|op| op.semantics().name)
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vector_alu_dispatch_selects_exactly_the_registry_vop2_forms() {
|
||||
for op in VectorAluOp::ALL {
|
||||
let row = op.semantics();
|
||||
assert_eq!(row.family, EncodingFamily::Vop2);
|
||||
assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic());
|
||||
assert_eq!(op.assembly_name(), format!("{}_e32", op.mnemonic()));
|
||||
assert_eq!(op.swaps_sources(), row.swap_sources);
|
||||
assert_eq!(row.scc, SccEffect::Unchanged);
|
||||
}
|
||||
// Exactly the registry VOP2 forms are dispatched here; the hand-written
|
||||
// ones (v_add_f32, v_mul_f32) must not be.
|
||||
dispatch_selects_exactly(EncodingFamily::Vop2, |word| {
|
||||
VectorAluOp::from_word(word).map(|op| op.semantics().name)
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vector_compare_dispatch_selects_exactly_the_registry_vopc_forms() {
|
||||
const OPERANDS16: [u64; 6] = [
|
||||
0xaaaa_0000,
|
||||
0x5555_0001,
|
||||
0xdead_7fff,
|
||||
0x8000,
|
||||
0xfffe,
|
||||
0xffff,
|
||||
];
|
||||
const OPERANDS32: [u64; 6] = [0, 1, 0x7fff_ffff, 0x8000_0000, 0xffff_fffe, 0xffff_ffff];
|
||||
const OPERANDS64: [u64; 6] = [0, 1, u64::MAX >> 1, 1 << 63, u64::MAX - 1, u64::MAX];
|
||||
for op in VectorCompareOp::ALL {
|
||||
let row = op.semantics();
|
||||
assert_eq!(row.family, EncodingFamily::Vopc);
|
||||
assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic());
|
||||
assert_eq!(op.assembly_name(), format!("{}_e32", op.mnemonic()));
|
||||
assert_eq!(row.relation, Some(op.relation()));
|
||||
assert_eq!(op.signed(), row.signedness == Signedness::Signed);
|
||||
assert_eq!(
|
||||
(row.scc, row.vcc, row.exec, row.wave),
|
||||
(
|
||||
SccEffect::Unchanged,
|
||||
MaskEffect::LaneMask,
|
||||
MaskEffect::Unchanged,
|
||||
Wave::Wave32
|
||||
)
|
||||
);
|
||||
// The per-lane test is the declared relation over the declared
|
||||
// signedness, with SRC0 on the left.
|
||||
let operands = match row.width {
|
||||
16 => OPERANDS16,
|
||||
64 => OPERANDS64,
|
||||
_ => OPERANDS32,
|
||||
};
|
||||
for src0 in operands {
|
||||
for src1 in operands {
|
||||
let ordering = if row.width == 16 {
|
||||
if op.signed() {
|
||||
(src0 as i16).cmp(&(src1 as i16))
|
||||
} else {
|
||||
(src0 as u16).cmp(&(src1 as u16))
|
||||
}
|
||||
} else if op.signed() && row.width == 64 {
|
||||
(src0 as i64).cmp(&(src1 as i64))
|
||||
} else if op.signed() {
|
||||
(src0 as i32).cmp(&(src1 as i32))
|
||||
} else {
|
||||
src0.cmp(&src1)
|
||||
};
|
||||
let expected = match op.relation() {
|
||||
CompareRelation::Less => ordering.is_lt(),
|
||||
CompareRelation::Equal => ordering.is_eq(),
|
||||
CompareRelation::LessOrEqual => ordering.is_le(),
|
||||
CompareRelation::Greater => ordering.is_gt(),
|
||||
CompareRelation::NotEqual => ordering.is_ne(),
|
||||
CompareRelation::GreaterOrEqual => ordering.is_ge(),
|
||||
CompareRelation::False => false,
|
||||
CompareRelation::True => true,
|
||||
};
|
||||
assert_eq!(
|
||||
op.test_bits(src0, src1),
|
||||
expected,
|
||||
"{} {src0:#x} {src1:#x}",
|
||||
row.name
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
// v_cmpx and the float compares must not be dispatched.
|
||||
dispatch_selects_exactly(EncodingFamily::Vopc, |word| {
|
||||
VectorCompareOp::from_word(word).map(|op| op.semantics().name)
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vop3_variant_dispatch_selects_exactly_the_registry_vop3_rows() {
|
||||
for op in VectorAluVop3Op::ALL {
|
||||
let (row, base) = (op.semantics(), op.base().semantics());
|
||||
assert_eq!((row.name, row.family), (base.name, EncodingFamily::Vop3));
|
||||
// The variant inherits the base declaration; only identity and the
|
||||
// operand rule differ.
|
||||
assert_eq!(
|
||||
(
|
||||
base.operation,
|
||||
base.signedness,
|
||||
base.scc,
|
||||
base.vcc,
|
||||
base.exec
|
||||
),
|
||||
(row.operation, row.signedness, row.scc, row.vcc, row.exec)
|
||||
);
|
||||
assert_eq!(row.swap_sources, base.swap_sources);
|
||||
assert_eq!(op.assembly_name(), format!("{}_e64", op.base().mnemonic()));
|
||||
}
|
||||
for base_op in VectorCompareOp::ALL {
|
||||
let base = base_op.semantics();
|
||||
let mut variants = VectorCompareVop3Op::ALL
|
||||
.into_iter()
|
||||
.filter(|op| op.base() == base_op);
|
||||
if base.width != 32 {
|
||||
assert_eq!(variants.next(), None, "{}", base.name);
|
||||
continue;
|
||||
}
|
||||
let op = variants
|
||||
.next()
|
||||
.expect("32-bit VOPC form must have a VOP3A encoding");
|
||||
assert_eq!(variants.next(), None);
|
||||
let row = op.semantics();
|
||||
assert_eq!((row.name, row.family), (base.name, EncodingFamily::Vop3));
|
||||
assert_eq!(row.operation, base.operation);
|
||||
assert_eq!(row.signedness, base.signedness);
|
||||
assert_eq!(row.relation, base.relation);
|
||||
assert_eq!(row.scc, SccEffect::Unchanged);
|
||||
assert_eq!(row.exec, MaskEffect::Unchanged);
|
||||
assert_eq!(row.wave, Wave::Wave32);
|
||||
assert_eq!(row.width, 32);
|
||||
assert_eq!(row.vcc, MaskEffect::SdstLaneMask);
|
||||
assert_eq!(row.operands, OperandRule::Vop3CmpVgpr2);
|
||||
assert_eq!(op.assembly_name(), format!("{}_e64", base_op.mnemonic()));
|
||||
}
|
||||
dispatch_selects_exactly(EncodingFamily::Vop3, |word| {
|
||||
let alu = VectorAluVop3Op::from_word(word);
|
||||
let compare = VectorCompareVop3Op::from_word(word);
|
||||
assert!(alu.is_none() || compare.is_none(), "{word:#x}");
|
||||
alu.map(|op| op.semantics().name)
|
||||
.or_else(|| compare.map(|op| op.semantics().name))
|
||||
});
|
||||
// No first word of the other 64-bit families (VOP3B shares VOP3's
|
||||
// encoding bits) selects a variant.
|
||||
for meta in META_FORMS
|
||||
.iter()
|
||||
.filter(|form| form.family != EncodingFamily::Vop3 && form.bytes == 8)
|
||||
{
|
||||
assert_eq!(
|
||||
VectorAluVop3Op::from_word(meta.bits as u32),
|
||||
None,
|
||||
"{}",
|
||||
meta.name
|
||||
);
|
||||
assert_eq!(
|
||||
VectorCompareVop3Op::from_word(meta.bits as u32),
|
||||
None,
|
||||
"{}",
|
||||
meta.name
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -15,8 +15,6 @@ gpu-tests = []
|
||||
|
||||
[dependencies]
|
||||
libc = "0.2"
|
||||
sha2 = "0.10"
|
||||
xenora-texture = { path = "../texture" }
|
||||
|
||||
[dev-dependencies]
|
||||
xenora-metal = { path = "../metal" }
|
||||
@@ -25,7 +23,3 @@ xenora-shader = { path = "../shader" }
|
||||
[[bench]]
|
||||
name = "dbt_bench"
|
||||
harness = false
|
||||
|
||||
[[bench]]
|
||||
name = "service_dispatch"
|
||||
harness = false
|
||||
+49
-1273
File diff suppressed because it is too large.
Load diff
@@ -1,225 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Guest-to-host service dispatch cost, measured with original guest loops
|
||||
//! that call standard services through a bound import table under the DBT.
|
||||
//!
|
||||
//! Every workload checks its result before timing. Each reported figure is
|
||||
//! the per-iteration time of a loop of `ITERATIONS` calls: one warm-up batch,
|
||||
//! then `BATCHES` measured batches. The empty loop is reported separately so
|
||||
//! readers can subtract the loop and translation overhead themselves.
|
||||
//!
|
||||
//! Run with `cargo bench --locked -p xenora-loader --bench service_dispatch`.
|
||||
|
||||
#[path = "../tests/support/mod.rs"]
|
||||
mod support;
|
||||
|
||||
use std::time::Instant;
|
||||
use support::*;
|
||||
use xenora_loader::cpu::{ExitReason, Register};
|
||||
use xenora_loader::services::sysinfo::HostCapabilities;
|
||||
|
||||
const IMPORTS: &[(&str, &str)] = &[
|
||||
("kernel32.dll", "GetLastError"),
|
||||
("kernel32.dll", "CreateEventW"),
|
||||
("kernel32.dll", "WaitForSingleObject"),
|
||||
("ucrtbase.dll", "strlen"),
|
||||
("kernel32.dll", "GetProcessHeap"),
|
||||
("kernel32.dll", "HeapAlloc"),
|
||||
("kernel32.dll", "HeapFree"),
|
||||
("ucrtbase.dll", "qsort"),
|
||||
];
|
||||
|
||||
const ITERATIONS: u32 = 10_000;
|
||||
const BATCHES: usize = 10;
|
||||
const CELL_EVENT: u64 = SCRATCH + 0x10;
|
||||
const CELL_HEAP: u64 = SCRATCH + 0x18;
|
||||
const STRING: u64 = SCRATCH + 0x100;
|
||||
const ARRAY: u64 = SCRATCH + 0x200;
|
||||
const ARRAY_LEN: u32 = 16;
|
||||
|
||||
const EMPTY: usize = 0;
|
||||
const LAST_ERROR: usize = 1;
|
||||
const WAIT: usize = 2;
|
||||
const STRLEN: usize = 3;
|
||||
const HEAP: usize = 4;
|
||||
const QSORT: usize = 5;
|
||||
const COMPARE: usize = 6;
|
||||
|
||||
/// A tiny x86-64 assembler for the routines below.
|
||||
struct Asm {
|
||||
base: u64,
|
||||
code: Vec<u8>,
|
||||
}
|
||||
|
||||
impl Asm {
|
||||
fn new(routine_index: usize) -> Self {
|
||||
Self {
|
||||
base: routine(routine_index),
|
||||
code: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn bytes(&mut self, bytes: &[u8]) -> &mut Self {
|
||||
self.code.extend_from_slice(bytes);
|
||||
self
|
||||
}
|
||||
|
||||
fn imm64(&mut self, opcode: &[u8], value: u64) -> &mut Self {
|
||||
self.bytes(opcode).bytes(&value.to_le_bytes())
|
||||
}
|
||||
|
||||
fn imm32(&mut self, opcode: &[u8], value: u32) -> &mut Self {
|
||||
self.bytes(opcode).bytes(&value.to_le_bytes())
|
||||
}
|
||||
|
||||
/// `call qword ptr [rip + displacement]` through an import slot.
|
||||
fn call_import(&mut self, symbol: &str) -> &mut Self {
|
||||
let index = IMPORTS
|
||||
.iter()
|
||||
.position(|(_, name)| *name == symbol)
|
||||
.unwrap();
|
||||
let next = self.base + self.code.len() as u64 + 6;
|
||||
let displacement = import_slot(IMPORTS, index).wrapping_sub(next) as u32;
|
||||
self.imm32(&[0xFF, 0x15], displacement)
|
||||
}
|
||||
|
||||
/// `mov ebx, ITERATIONS`, the loop body, `dec ebx; jnz body; hlt`.
|
||||
fn counted(routine_index: usize, body: impl FnOnce(&mut Self)) -> Vec<u8> {
|
||||
let mut asm = Self::new(routine_index);
|
||||
asm.imm32(&[0xBB], ITERATIONS);
|
||||
let start = asm.code.len();
|
||||
body(&mut asm);
|
||||
asm.bytes(&[0xFF, 0xCB]); // dec ebx
|
||||
let back = start as i64 - (asm.code.len() as i64 + 2);
|
||||
asm.bytes(&[0x75, i8::try_from(back).unwrap() as u8, 0xF4]);
|
||||
asm.code
|
||||
}
|
||||
}
|
||||
|
||||
fn routines() -> Vec<Vec<u8>> {
|
||||
let mut routines = vec![Vec::new(); 7];
|
||||
routines[EMPTY] = Asm::counted(EMPTY, |_| {});
|
||||
routines[LAST_ERROR] = Asm::counted(LAST_ERROR, |asm| {
|
||||
asm.call_import("GetLastError");
|
||||
});
|
||||
routines[WAIT] = Asm::counted(WAIT, |asm| {
|
||||
asm.imm64(&[0x48, 0xB8], CELL_EVENT) // mov rax, cell
|
||||
.bytes(&[0x48, 0x8B, 0x08]) // mov rcx, [rax]
|
||||
.bytes(&[0x31, 0xD2]) // xor edx, edx
|
||||
.call_import("WaitForSingleObject");
|
||||
});
|
||||
routines[STRLEN] = Asm::counted(STRLEN, |asm| {
|
||||
asm.imm64(&[0x48, 0xB9], STRING).call_import("strlen");
|
||||
});
|
||||
routines[HEAP] = Asm::counted(HEAP, |asm| {
|
||||
asm.imm64(&[0x48, 0xB8], CELL_HEAP)
|
||||
.bytes(&[0x48, 0x8B, 0x08]) // mov rcx, [rax]
|
||||
.bytes(&[0x31, 0xD2])
|
||||
.imm32(&[0x41, 0xB8], 64) // mov r8d, 64
|
||||
.call_import("HeapAlloc")
|
||||
.bytes(&[0x49, 0x89, 0xC0]) // mov r8, rax
|
||||
.imm64(&[0x48, 0xB8], CELL_HEAP)
|
||||
.bytes(&[0x48, 0x8B, 0x08])
|
||||
.bytes(&[0x31, 0xD2])
|
||||
.call_import("HeapFree");
|
||||
});
|
||||
routines[QSORT] = Asm::counted(QSORT, |asm| {
|
||||
asm.imm64(&[0x48, 0xB9], ARRAY)
|
||||
.imm32(&[0xBA], ARRAY_LEN) // mov edx, count
|
||||
.imm32(&[0x41, 0xB8], 4) // mov r8d, width
|
||||
.imm64(&[0x49, 0xB9], routine(COMPARE))
|
||||
.call_import("qsort");
|
||||
});
|
||||
// int compare(const int *a, const int *b) { return *a - *b; }
|
||||
routines[COMPARE] = vec![0x8B, 0x01, 0x2B, 0x02, 0xC3];
|
||||
routines
|
||||
}
|
||||
|
||||
fn median(samples: &mut [f64]) -> f64 {
|
||||
samples.sort_by(f64::total_cmp);
|
||||
samples[samples.len() / 2]
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let mut guest = Guest::new(IMPORTS, &routines());
|
||||
let event = guest.call("CreateEventW", &[0, 1, 1, 0]);
|
||||
assert_ne!(event, 0);
|
||||
guest.memory.write_u64(CELL_EVENT, event).unwrap();
|
||||
let heap = guest.call("GetProcessHeap", &[]);
|
||||
guest.memory.write_u64(CELL_HEAP, heap).unwrap();
|
||||
guest.memory.write_bytes(STRING, &[b'a'; 63]).unwrap();
|
||||
guest.memory.write_u8(STRING + 63, 0).unwrap();
|
||||
let unsorted: Vec<i32> = (0..ARRAY_LEN as i32)
|
||||
.map(|i| (i * 7919) % 31 - 15)
|
||||
.collect();
|
||||
|
||||
let reset_array = |guest: &mut Guest| {
|
||||
for (index, value) in unsorted.iter().enumerate() {
|
||||
guest
|
||||
.memory
|
||||
.write_u32(ARRAY + 4 * index as u64, *value as u32)
|
||||
.unwrap();
|
||||
}
|
||||
};
|
||||
|
||||
let host = HostCapabilities::detect();
|
||||
let brand = std::process::Command::new("sysctl")
|
||||
.args(["-n", "machdep.cpu.brand_string"])
|
||||
.output()
|
||||
.map(|output| String::from_utf8_lossy(&output.stdout).trim().to_owned())
|
||||
.unwrap_or_default();
|
||||
println!(
|
||||
"host: {brand}, {} logical processors; profile: {}",
|
||||
host.logical_processors.unwrap_or(0),
|
||||
if cfg!(debug_assertions) {
|
||||
"debug"
|
||||
} else {
|
||||
"release"
|
||||
},
|
||||
);
|
||||
println!("{ITERATIONS} iterations per batch, 1 warm-up and {BATCHES} measured batches");
|
||||
println!("workload,median_ns_per_iteration,min_ns,max_ns");
|
||||
|
||||
for (name, index, check) in [
|
||||
("empty loop", EMPTY, None),
|
||||
("GetLastError", LAST_ERROR, Some(0)),
|
||||
(
|
||||
"WaitForSingleObject (signaled manual-reset event)",
|
||||
WAIT,
|
||||
Some(0),
|
||||
),
|
||||
("strlen (63 bytes)", STRLEN, Some(63)),
|
||||
("HeapAlloc + HeapFree (64 bytes)", HEAP, Some(1)),
|
||||
("qsort (16 ints, guest comparator)", QSORT, Some(0)),
|
||||
] {
|
||||
let mut samples = Vec::with_capacity(BATCHES);
|
||||
for batch in 0..=BATCHES {
|
||||
if index == QSORT {
|
||||
reset_array(&mut guest);
|
||||
}
|
||||
let start = Instant::now();
|
||||
let (cpu, exit) = guest.execute(routine(index), usize::MAX);
|
||||
let elapsed = start.elapsed();
|
||||
assert_eq!(exit, ExitReason::Halt, "{name}");
|
||||
assert_eq!(cpu.get(Register::Rbx), 0, "{name} loop count");
|
||||
if let Some(expected) = check {
|
||||
assert_eq!(cpu.get(Register::Rax), expected, "{name} result");
|
||||
}
|
||||
if index == QSORT {
|
||||
let mut expected = unsorted.clone();
|
||||
expected.sort();
|
||||
let sorted: Vec<i32> = (0..ARRAY_LEN as u64)
|
||||
.map(|i| guest.u32_at(ARRAY + 4 * i) as i32)
|
||||
.collect();
|
||||
assert_eq!(sorted, expected, "{name} ordering");
|
||||
}
|
||||
if batch > 0 {
|
||||
samples.push(elapsed.as_nanos() as f64 / f64::from(ITERATIONS));
|
||||
}
|
||||
}
|
||||
let (min, max) = samples.iter().fold((f64::MAX, 0f64), |(low, high), &s| {
|
||||
(low.min(s), high.max(s))
|
||||
});
|
||||
println!("{name},{:.1},{min:.1},{max:.1}", median(&mut samples));
|
||||
}
|
||||
}
|
||||
@@ -1,332 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Validate the x86-64 instruction registry and generate its Rust tables.
|
||||
|
||||
validate check crates/loader/x86/instructions.toml
|
||||
generate validate, then write crates/loader/src/x86_table.rs
|
||||
--check validate and regenerate in memory; exit 1 if the committed file
|
||||
differs. Never writes.
|
||||
|
||||
Rejects unknown keys and vocabulary, overlapping encodings, digit and plain
|
||||
forms sharing an opcode, operand constraints that contradict each other, a
|
||||
fixed r/m field on a form that could take memory, LOCK on a form that cannot
|
||||
write memory, and flags declared both written and undefined. Standard library only (Python 3.11+).
|
||||
"""
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
try:
|
||||
import tomllib
|
||||
except ModuleNotFoundError:
|
||||
sys.exit("generate_x86.py needs Python 3.11 or newer (tomllib)")
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
REGISTRY = HERE / "x86/instructions.toml"
|
||||
RUST = HERE / "src/x86_table.rs"
|
||||
|
||||
TOP_KEYS = {"schema", "architecture", "documents", "operation", "alu", "form", "group"}
|
||||
OPERATION_KEYS = {"reads", "writes", "undefined", "conditional", "terminator", "faults", "ref"}
|
||||
FORM_KEYS = {"op", "map", "prefix", "opcode", "count", "digit", "enc", "size", "imm", "src",
|
||||
"memory_only", "register_only", "rm", "no_rex_b", "unaligned", "lock"}
|
||||
GROUP_KEYS = {"map", "opcodes", "digits"}
|
||||
FLAGS = ["cf", "zf", "sf", "of", "pf", "af"]
|
||||
MAPS = {"1": "ONE_BYTE", "0f": "TWO_BYTE"}
|
||||
# Two-byte opcode table per mandatory prefix.
|
||||
PREFIXES = {"": "TWO_BYTE", "66": "TWO_BYTE_66", "f3": "TWO_BYTE_F3", "f2": "TWO_BYTE_F2"}
|
||||
SIZES = {"b": "Byte", "v": "Variable", "q": "Quad", "y": "Wide", "n": "None", "x": "Xmm"}
|
||||
IMMS = {"": "None", "ib": "SignedByte", "iz": "SignedFull", "iv": "Full", "iw": "Word", "ub": "Byte",
|
||||
"rel8": "SignedByte", "rel32": "Signed32"}
|
||||
SRCS = {"": 0, "b": 1, "w": 2, "d": 4, "q": 8, "x": 16}
|
||||
# encoding -> (Rust variant, has ModRM, required immediates)
|
||||
ENCS = {
|
||||
"none": ("None", False, {""}),
|
||||
"string": ("String", False, {""}),
|
||||
"rm_reg": ("RmReg", True, {""}),
|
||||
"reg_rm": ("RegRm", True, {""}),
|
||||
"reg_rm_imm": ("RegRmImm", True, {"ib", "iz"}),
|
||||
"rm": ("Rm", True, {""}),
|
||||
"rm_only": ("Rm", True, {""}),
|
||||
"rm_unread": ("RmUnread", True, {""}),
|
||||
"rm_imm": ("RmImm", True, {"ib", "iz"}),
|
||||
"rm_one": ("RmOne", True, {""}),
|
||||
"rm_cl": ("RmCl", True, {""}),
|
||||
"rm_reg_imm": ("RmRegImm", True, {"ub"}),
|
||||
"rm_reg_cl": ("RmRegCl", True, {""}),
|
||||
"acc_imm": ("AccImm", False, {"ib", "iz"}),
|
||||
"op_reg": ("OpReg", False, {""}),
|
||||
"op_reg_imm": ("OpRegImm", False, {"ib", "iv"}),
|
||||
"imm": ("Imm", False, {"ib", "iz", "iw"}),
|
||||
"rel": ("Rel", False, {"rel8", "rel32"}),
|
||||
"xmm_rm": ("XmmRm", True, {""}),
|
||||
"rm_xmm": ("RmXmm", True, {""}),
|
||||
"xmm_rm_imm": ("XmmRmImm", True, {"ub"}),
|
||||
"rm_imm_xmm": ("RmImmXmm", True, {"ub"}),
|
||||
"xmm_gpr": ("XmmGpr", True, {""}),
|
||||
"gpr_xmm": ("GprXmm", True, {""}),
|
||||
"xmm_gpr_imm": ("XmmGprImm", True, {"ub"}),
|
||||
"reg_xmm": ("RegXmm", True, {""}),
|
||||
"reg_xmm_imm": ("RegXmmImm", True, {"ub"}),
|
||||
}
|
||||
# Encodings whose ModRM operand is the destination, so LOCK can apply to it.
|
||||
RM_DESTINATIONS = {"rm_reg", "rm", "rm_imm", "rm_one", "rm_cl", "rm_reg_imm", "rm_reg_cl"}
|
||||
# Encodings whose ModRM operand is an XMM register or memory of the source width.
|
||||
XMM_RM = {"xmm_rm", "rm_xmm", "xmm_rm_imm", "rm_imm_xmm", "reg_xmm", "reg_xmm_imm"}
|
||||
# One-byte opcodes that are prefixes or the two-byte escape, never instructions.
|
||||
RESERVED = {0x0F, 0x26, 0x2E, 0x36, 0x3E, 0x64, 0x65, 0x66, 0x67, 0xF0, 0xF2, 0xF3,
|
||||
*range(0x40, 0x50)}
|
||||
|
||||
|
||||
class RegistryError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def fail(message):
|
||||
raise RegistryError(message)
|
||||
|
||||
|
||||
def check_keys(where, table, allowed):
|
||||
unknown = set(table) - allowed
|
||||
if unknown:
|
||||
fail(f"{where}: unknown keys {sorted(unknown)}")
|
||||
|
||||
|
||||
def flag_set(where, text):
|
||||
names = text.split()
|
||||
for name in names:
|
||||
if name not in FLAGS:
|
||||
fail(f"{where}: unknown flag {name!r}")
|
||||
if len(set(names)) != len(names):
|
||||
fail(f"{where}: repeated flag")
|
||||
return set(names)
|
||||
|
||||
|
||||
def load(text):
|
||||
"""Parse and validate the registry text, returning (operations, forms)."""
|
||||
data = tomllib.loads(text)
|
||||
check_keys("registry", data, TOP_KEYS)
|
||||
if data.get("schema") != 1 or data.get("architecture") != "x86-64":
|
||||
fail("registry: unsupported schema or architecture")
|
||||
documents = data["documents"]
|
||||
|
||||
operations = {}
|
||||
for name, entry in data["operation"].items():
|
||||
where = f"operation {name}"
|
||||
check_keys(where, entry, OPERATION_KEYS)
|
||||
reads, writes, undefined = (
|
||||
flag_set(where, entry.get(key, "")) for key in ("reads", "writes", "undefined"))
|
||||
if writes & undefined:
|
||||
fail(f"{where}: flags both written and undefined: {sorted(writes & undefined)}")
|
||||
if entry.get("ref", " ").split()[0:1] == [] or entry.get("ref", "").split()[0] not in documents:
|
||||
fail(f"{where}: reference must name a listed document")
|
||||
operations[name] = {
|
||||
"reads": reads, "writes": writes, "undefined": undefined,
|
||||
"conditional": entry.get("conditional", False),
|
||||
"terminator": entry.get("terminator", False),
|
||||
"faults": entry.get("faults", False),
|
||||
}
|
||||
|
||||
forms = [dict(form) for form in data["form"]]
|
||||
for form in forms:
|
||||
check_keys(f"form {form.get('op')}", form, FORM_KEYS)
|
||||
for index, op in enumerate(data["alu"]["operations"]):
|
||||
base = index * 8
|
||||
for offset, (enc, size, imm) in enumerate([
|
||||
("rm_reg", "b", ""), ("rm_reg", "v", ""), ("reg_rm", "b", ""),
|
||||
("reg_rm", "v", ""), ("acc_imm", "b", "ib"), ("acc_imm", "v", "iz")]):
|
||||
forms.append({"op": op, "opcode": base + offset, "enc": enc, "size": size, "imm": imm})
|
||||
for opcode, size, imm in ((0x80, "b", "ib"), (0x81, "v", "iz"), (0x83, "v", "ib")):
|
||||
forms.append({"op": op, "opcode": opcode, "digit": index, "enc": "rm_imm",
|
||||
"size": size, "imm": imm})
|
||||
for group in data["group"]:
|
||||
check_keys("group", group, GROUP_KEYS)
|
||||
for opcode, size, imm, enc in group["opcodes"]:
|
||||
for digit, op in sorted(group["digits"].items()):
|
||||
forms.append({"op": op, "map": group.get("map", "1"), "opcode": opcode,
|
||||
"digit": int(digit), "enc": enc, "size": size, "imm": imm})
|
||||
|
||||
claimed = {}
|
||||
used = set()
|
||||
for form in forms:
|
||||
form.setdefault("map", "1")
|
||||
for key in ("prefix", "imm", "src"):
|
||||
form.setdefault(key, "")
|
||||
form.setdefault("count", 1)
|
||||
form.setdefault("digit", None)
|
||||
where = f"form {form['op']} {form['map']}:{form['opcode']:02x}"
|
||||
for key, allowed in (("op", operations), ("map", MAPS), ("prefix", PREFIXES),
|
||||
("enc", ENCS), ("size", SIZES), ("imm", IMMS), ("src", SRCS)):
|
||||
if form[key] not in allowed:
|
||||
fail(f"{where}: unknown {key} {form[key]!r}")
|
||||
used.add(form["op"])
|
||||
_, modrm, imms = ENCS[form["enc"]]
|
||||
if form["imm"] not in imms:
|
||||
fail(f"{where}: immediate {form['imm']!r} is not valid for {form['enc']}")
|
||||
if form["imm"] == "ib" and form["size"] == "n":
|
||||
fail(f"{where}: a sized immediate needs an operand size")
|
||||
if form["digit"] is not None and (not modrm or not 0 <= form["digit"] <= 7):
|
||||
fail(f"{where}: a digit needs a ModRM encoding and a value 0-7")
|
||||
if form.get("memory_only") and form.get("register_only"):
|
||||
fail(f"{where}: memory_only and register_only contradict")
|
||||
if (form.get("memory_only") or form.get("register_only")) and not modrm:
|
||||
fail(f"{where}: operand restriction without ModRM")
|
||||
form.setdefault("rm", None)
|
||||
if form["rm"] is not None:
|
||||
# bool is an int in Python; `rm = true` is not a field value.
|
||||
if type(form["rm"]) is not int or not 0 <= form["rm"] <= 7:
|
||||
fail(f"{where}: rm must be a ModRM r/m field value 0-7")
|
||||
if not form.get("register_only") or form["digit"] is None:
|
||||
fail(f"{where}: a fixed r/m field needs register_only and a digit")
|
||||
sourced = form["enc"] in XMM_RM or form["enc"] == "xmm_gpr_imm"
|
||||
if sourced != bool(form["src"]) and form["enc"] not in ("reg_rm", "rm"):
|
||||
fail(f"{where}: source size does not match the encoding")
|
||||
if form["src"] and not sourced and form["enc"] == "rm" and form["size"] != "n":
|
||||
fail(f"{where}: source size does not match the encoding")
|
||||
if (form["size"] == "x") != (form["enc"] in XMM_RM - {"reg_xmm", "reg_xmm_imm"}
|
||||
or form["enc"] == "xmm_gpr_imm"):
|
||||
fail(f"{where}: XMM size does not match the encoding")
|
||||
if form.get("lock") and (form["enc"] not in RM_DESTINATIONS or form.get("register_only")):
|
||||
fail(f"{where}: LOCK needs a memory destination")
|
||||
if form.get("unaligned") and form["src"] != "x":
|
||||
fail(f"{where}: alignment applies only to 16-byte operands")
|
||||
if form["prefix"] and form["map"] != "0f":
|
||||
fail(f"{where}: mandatory prefixes are only supported in map 0f")
|
||||
if form["count"] not in (1, 8, 16) or form["opcode"] % form["count"]:
|
||||
fail(f"{where}: count must be 1, 8 or 16 and aligned")
|
||||
if form["count"] == 8 and form["enc"] not in ("op_reg", "op_reg_imm"):
|
||||
fail(f"{where}: count 8 encodes a register")
|
||||
if form["count"] == 16 and form["op"] not in ("jcc", "cmov", "setcc"):
|
||||
fail(f"{where}: count 16 encodes a condition")
|
||||
for opcode in range(form["opcode"], form["opcode"] + form["count"]):
|
||||
if not 0 <= opcode <= 0xFF:
|
||||
fail(f"{where}: opcode out of range")
|
||||
if form["map"] == "1" and opcode in RESERVED:
|
||||
fail(f"{where}: {opcode:02x} is a prefix or escape")
|
||||
slots = claimed.setdefault((form["map"], form["prefix"], opcode), {})
|
||||
if form["digit"] in slots or (slots and (None in slots or form["digit"] is None)):
|
||||
fail(f"{where}: overlapping encoding")
|
||||
slots[form["digit"]] = form
|
||||
# 0x66 selects a 16-bit operand for an unprefixed integer form, so a
|
||||
# 66-prefixed form at the same opcode would be ambiguous.
|
||||
for other, sized in (("66", form), ("", None)):
|
||||
if form["map"] == "0f" and form["prefix"] == ("" if other == "66" else "66"):
|
||||
for rival in claimed.get(("0f", other, opcode), {}).values():
|
||||
plain = sized or rival
|
||||
if plain["size"] in ("b", "v"):
|
||||
fail(f"{where}: 0x66 is both an operand size and a mandatory prefix")
|
||||
if form["digit"] is not None:
|
||||
first = next(iter(slots.values()))
|
||||
if (first["size"] in "bn") != (form["size"] in "bn"):
|
||||
fail(f"{where}: group mixes byte and wider operands")
|
||||
unused = set(operations) - used
|
||||
if unused:
|
||||
fail(f"operations without forms: {sorted(unused)}")
|
||||
return operations, forms
|
||||
|
||||
|
||||
def camel(name):
|
||||
return name[0].upper() + name[1:]
|
||||
|
||||
|
||||
def mask(flags):
|
||||
return sum(1 << FLAGS.index(flag) for flag in flags)
|
||||
|
||||
|
||||
def generate(operations, forms):
|
||||
out = ["// SPDX-License-Identifier: GPL-3.0-or-later",
|
||||
"",
|
||||
"// Generated by crates/loader/generate_x86.py from crates/loader/x86/instructions.toml.",
|
||||
"// Do not edit.",
|
||||
"",
|
||||
"use crate::x86_decode::{Encoding, Entry, Form, Immediate, OperandSize};",
|
||||
"",
|
||||
"/// Operations with decodable forms.",
|
||||
"#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]",
|
||||
"pub enum Op {"]
|
||||
out += [f" {camel(name)}," for name in operations]
|
||||
out += ["}", "", "impl Op {",
|
||||
" pub const ALL: &[Op] = &["
|
||||
+ ", ".join(f"Op::{camel(n)}" for n in operations) + "];", ""]
|
||||
|
||||
def method(doc, name, kind, value):
|
||||
out.append(f" /// {doc}")
|
||||
out.append(f" pub const fn {name}(self) -> {kind} {{")
|
||||
out.append(" match self {")
|
||||
for op, entry in operations.items():
|
||||
out.append(f" Op::{camel(op)} => {value(op, entry)},")
|
||||
out.extend([" }", " }", ""])
|
||||
|
||||
method("Lower-case mnemonic stem.", "name", "&'static str", lambda op, e: f'"{op}"')
|
||||
bits = "Flag bits: 1 CF, 2 ZF, 4 SF, 8 OF, 16 PF, 32 AF."
|
||||
method(f"Flags read. {bits}", "flags_read", "u8", lambda op, e: mask(e["reads"]))
|
||||
method(f"Flags always written. {bits}", "flags_written", "u8",
|
||||
lambda op, e: 0 if e["conditional"] else mask(e["writes"]))
|
||||
method(f"Flags this operation may change. {bits}", "flags_touched", "u8",
|
||||
lambda op, e: mask(e["writes"]))
|
||||
method(f"Architecturally undefined flags. {bits}", "flags_undefined", "u8",
|
||||
lambda op, e: mask(e["undefined"]))
|
||||
method("Ends a translated block.", "is_terminator", "bool",
|
||||
lambda op, e: str(e["terminator"]).lower())
|
||||
method("Can raise an arithmetic fault.", "can_fault", "bool",
|
||||
lambda op, e: str(e["faults"]).lower())
|
||||
vector = {form["op"] for form in forms if form["size"] == "x" or "xmm" in form["enc"]}
|
||||
method("Uses an XMM register.", "is_vector", "bool", lambda op, e: str(op in vector).lower())
|
||||
out[-1:] = ["}", ""]
|
||||
|
||||
out.append(f"pub static FORMS: [Form; {len(forms)}] = [")
|
||||
for form in forms:
|
||||
out.append(
|
||||
f" Form {{ op: Op::{camel(form['op'])}, encoding: Encoding::{ENCS[form['enc']][0]}, "
|
||||
f"size: OperandSize::{SIZES[form['size']]}, immediate: Immediate::{IMMS[form['imm']]}, "
|
||||
f"source: {SRCS[form['src']]}, has_modrm: {str(ENCS[form['enc']][1]).lower()}, "
|
||||
f"memory_only: {str(bool(form.get('memory_only'))).lower()}, "
|
||||
f"register_only: {str(bool(form.get('register_only'))).lower()}, "
|
||||
f"fixed_rm: {'None' if form['rm'] is None else 'Some(%d)' % form['rm']}, "
|
||||
f"no_rex_b: {str(bool(form.get('no_rex_b'))).lower()}, "
|
||||
f"unaligned: {str(bool(form.get('unaligned'))).lower()}, "
|
||||
f"lockable: {str(bool(form.get('lock'))).lower()} }},")
|
||||
out += ["];", ""]
|
||||
|
||||
groups = []
|
||||
tables = {name: ["Entry::Unsupported"] * 256 for name in ("ONE_BYTE", *PREFIXES.values())}
|
||||
slots = {}
|
||||
for index, form in enumerate(forms):
|
||||
table = MAPS[form["map"]] if form["map"] == "1" else PREFIXES[form["prefix"]]
|
||||
for opcode in range(form["opcode"], form["opcode"] + form["count"]):
|
||||
slots.setdefault((table, opcode), {})[form["digit"]] = index
|
||||
for (table, opcode), digits in sorted(slots.items()):
|
||||
if None in digits:
|
||||
tables[table][opcode] = f"Entry::Form({digits[None]})"
|
||||
else:
|
||||
row = [str(digits.get(d, 65535)) for d in range(8)]
|
||||
tables[table][opcode] = f"Entry::Group({len(groups)})"
|
||||
groups.append("[" + ", ".join(row) + "]")
|
||||
out.append("/// Form per ModRM digit; 65535 marks an unsupported digit.")
|
||||
out.append(f"pub static GROUPS: [[u16; 8]; {len(groups)}] = [")
|
||||
out += [f" {row}," for row in groups]
|
||||
out += ["];", ""]
|
||||
for name, entries in tables.items():
|
||||
out.append(f"pub static {name}: [Entry; 256] = [")
|
||||
for start in range(0, 256, 4):
|
||||
out.append(" " + ", ".join(entries[start:start + 4]) + ",")
|
||||
out += ["];", ""]
|
||||
return "\n".join(out[:-1]) + "\n"
|
||||
|
||||
|
||||
def main(argv):
|
||||
if len(argv) != 2 or argv[1] not in ("validate", "generate", "--check"):
|
||||
sys.exit("usage: generate_x86.py validate|generate|--check")
|
||||
try:
|
||||
operations, forms = load(REGISTRY.read_text())
|
||||
except (RegistryError, KeyError, tomllib.TOMLDecodeError) as error:
|
||||
sys.exit(f"instructions.toml: {error}")
|
||||
rust = generate(operations, forms)
|
||||
if argv[1] == "generate":
|
||||
RUST.write_text(rust)
|
||||
elif argv[1] == "--check" and (not RUST.exists() or RUST.read_text() != rust):
|
||||
sys.exit("x86_table.rs is out of date; run generate_x86.py generate")
|
||||
encodings = sum(form["count"] for form in forms)
|
||||
print(f"{len(operations)} operations, {len(forms)} forms, {encodings} opcode slots")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main(sys.argv)
|
||||
@@ -1,416 +0,0 @@
|
||||
# Typed runtime service registry.
|
||||
#
|
||||
# Data only. `cargo run -p xenora-import-gen --bin xenora-runtime-gen` validates
|
||||
# it and writes crates/loader/src/runtime_table.rs (typed Win64 adapters and
|
||||
# static metadata) and docs/runtime/services.md (coverage counts).
|
||||
#
|
||||
# service <library> <symbol>(<name>: <type>, ...) -> <type>
|
||||
# handler <Rust function in crates/loader/src/services.rs or crt.rs>
|
||||
# status implemented | partial | stub
|
||||
# alias <documented API set that forwards this symbol>
|
||||
# fails <failure contract>
|
||||
# ref <public header or document>
|
||||
# test <test function in crates/loader/tests/runtime_services.rs>
|
||||
#
|
||||
# Types: u32 i32 u64 bool32 handle ptr out<N> f32 f64, and void as a result.
|
||||
# A bool32 argument is true when nonzero. out<N> is a guest pointer to N bytes
|
||||
# the service writes. Arguments are assigned by position (Microsoft x64 calling
|
||||
# convention): RCX, RDX, R8, R9 or XMM0-XMM3 for floats, then the stack.
|
||||
#
|
||||
# "status" describes behaviour against the documented contract. A service needs
|
||||
# at least one test before it may be implemented or partial.
|
||||
|
||||
service kernel32.dll SetProcessPriorityBoost(process: handle, disable: bool32) -> bool32
|
||||
handler set_process_priority_boost
|
||||
status partial
|
||||
alias api-ms-win-core-processthreads-l1-1-2.dll
|
||||
fails 0 with ERROR_INVALID_HANDLE
|
||||
ref processthreadsapi.h SetProcessPriorityBoost
|
||||
test priority_boost_round_trips_and_checks_its_handle
|
||||
|
||||
service kernel32.dll GetProcessPriorityBoost(process: handle, disabled: out<4>) -> bool32
|
||||
handler get_process_priority_boost
|
||||
status partial
|
||||
alias api-ms-win-core-processthreads-l1-1-2.dll
|
||||
fails 0 with ERROR_INVALID_HANDLE or ERROR_NOACCESS
|
||||
ref processthreadsapi.h GetProcessPriorityBoost
|
||||
test priority_boost_round_trips_and_checks_its_handle
|
||||
|
||||
service kernel32.dll GetCurrentProcess() -> handle
|
||||
handler get_current_process
|
||||
status implemented
|
||||
alias api-ms-win-core-processthreads-l1-1-0.dll
|
||||
fails never
|
||||
ref processthreadsapi.h GetCurrentProcess
|
||||
test identity_services_return_documented_pseudo_handles_and_ids
|
||||
|
||||
service kernel32.dll GetProcessId(process: handle) -> u32
|
||||
handler get_process_id
|
||||
status partial
|
||||
alias api-ms-win-core-processthreads-l1-1-0.dll
|
||||
fails 0 with ERROR_INVALID_HANDLE
|
||||
ref processthreadsapi.h GetProcessId
|
||||
test identity_services_return_documented_pseudo_handles_and_ids
|
||||
|
||||
service kernel32.dll GetCurrentThread() -> handle
|
||||
handler get_current_thread
|
||||
status implemented
|
||||
alias api-ms-win-core-processthreads-l1-1-0.dll
|
||||
fails never
|
||||
ref processthreadsapi.h GetCurrentThread
|
||||
test identity_services_return_documented_pseudo_handles_and_ids
|
||||
|
||||
service kernel32.dll GetCurrentProcessId() -> u32
|
||||
handler get_current_process_id
|
||||
status implemented
|
||||
alias api-ms-win-core-processthreads-l1-1-0.dll
|
||||
fails never
|
||||
ref processthreadsapi.h GetCurrentProcessId
|
||||
test identity_services_return_documented_pseudo_handles_and_ids
|
||||
|
||||
service kernel32.dll GetCurrentThreadId() -> u32
|
||||
handler get_current_thread_id
|
||||
status implemented
|
||||
alias api-ms-win-core-processthreads-l1-1-0.dll
|
||||
fails never
|
||||
ref processthreadsapi.h GetCurrentThreadId
|
||||
test identity_services_return_documented_pseudo_handles_and_ids
|
||||
|
||||
service kernel32.dll OpenThread(access: u32, inherit: bool32, thread: u32) -> handle
|
||||
handler open_thread
|
||||
status partial
|
||||
alias api-ms-win-core-processthreads-l1-1-0.dll
|
||||
fails 0 with ERROR_INVALID_PARAMETER, ERROR_NOT_SUPPORTED or ERROR_NOT_ENOUGH_MEMORY
|
||||
ref processthreadsapi.h OpenThread
|
||||
test thread_handles_check_access_and_are_rejected_once_closed
|
||||
|
||||
service kernel32.dll GetThreadPriority(thread: handle) -> i32
|
||||
handler get_thread_priority
|
||||
status partial
|
||||
alias api-ms-win-core-processthreads-l1-1-0.dll
|
||||
fails THREAD_PRIORITY_ERROR_RETURN with ERROR_INVALID_HANDLE or ERROR_ACCESS_DENIED
|
||||
ref processthreadsapi.h GetThreadPriority
|
||||
test thread_handles_check_access_and_are_rejected_once_closed
|
||||
|
||||
service kernel32.dll SetThreadPriority(thread: handle, priority: i32) -> bool32
|
||||
handler set_thread_priority
|
||||
status partial
|
||||
alias api-ms-win-core-processthreads-l1-1-0.dll
|
||||
fails 0 with ERROR_INVALID_HANDLE, ERROR_ACCESS_DENIED, ERROR_NOT_SUPPORTED or ERROR_INVALID_PARAMETER
|
||||
ref processthreadsapi.h SetThreadPriority
|
||||
test thread_handles_check_access_and_are_rejected_once_closed
|
||||
|
||||
service kernel32.dll CloseHandle(object: handle) -> bool32
|
||||
handler close_handle
|
||||
status partial
|
||||
alias api-ms-win-core-handle-l1-1-0.dll
|
||||
fails 0 with ERROR_INVALID_HANDLE
|
||||
ref handleapi.h CloseHandle
|
||||
test thread_handles_check_access_and_are_rejected_once_closed
|
||||
|
||||
service kernel32.dll GetSystemTimeAsFileTime(time: out<8>) -> void
|
||||
handler get_system_time_as_file_time
|
||||
status implemented
|
||||
alias api-ms-win-core-sysinfo-l1-1-0.dll
|
||||
fails guest fault on an invalid pointer
|
||||
ref sysinfoapi.h GetSystemTimeAsFileTime
|
||||
test system_time_comes_from_the_injected_clock
|
||||
|
||||
# Standard streams and formatted output for a hosted C program. Output to
|
||||
# stdout and stderr is captured, and a stream from fopen is a file. A pointer
|
||||
# that is no stream, reading stdin, and floating-point and wide conversions
|
||||
# stop the guest with the runtime-limit fault.
|
||||
|
||||
service ucrtbase.dll __acrt_iob_func(index: u32) -> ptr
|
||||
handler standard_stream
|
||||
status partial
|
||||
alias api-ms-win-crt-stdio-l1-1-0.dll
|
||||
fails stops the guest for an index above 2 or when the streams cannot be allocated
|
||||
ref corecrt_wstdio.h __acrt_iob_func
|
||||
test standard_streams_are_three_stable_file_objects
|
||||
|
||||
service ucrtbase.dll __stdio_common_vfprintf(options: u64, stream: ptr, format: ptr, locale: ptr, arguments: ptr) -> i32
|
||||
handler vfprintf
|
||||
status partial
|
||||
alias api-ms-win-crt-stdio-l1-1-0.dll
|
||||
fails -1 with errno EINVAL for a null stream or format or an invalid format; stops the guest for what is not modelled
|
||||
ref corecrt_stdio_config.h __stdio_common_vfprintf; Microsoft Learn, vfprintf and format specification syntax
|
||||
test formatted_output_reaches_the_captured_standard_streams
|
||||
|
||||
service ucrtbase.dll fwrite(buffer: ptr, size: u64, count: u64, stream: ptr) -> u64
|
||||
handler fwrite
|
||||
status partial
|
||||
alias api-ms-win-crt-stdio-l1-1-0.dll
|
||||
fails 0 with errno EINVAL for a null buffer or stream, or EBADF or ENOSPC for a file; stops the guest for stdin or a pointer that is no stream
|
||||
ref stdio.h fwrite
|
||||
test fwrite_and_fputs_write_to_the_captured_standard_streams
|
||||
|
||||
service ucrtbase.dll fputs(text: ptr, stream: ptr) -> i32
|
||||
handler fputs
|
||||
status partial
|
||||
alias api-ms-win-crt-stdio-l1-1-0.dll
|
||||
fails EOF with errno EINVAL for a null string or stream, or EBADF or ENOSPC for a file; stops the guest for stdin or a pointer that is no stream
|
||||
ref stdio.h fputs
|
||||
test fwrite_and_fputs_write_to_the_captured_standard_streams
|
||||
|
||||
service ucrtbase.dll fflush(stream: ptr) -> i32
|
||||
handler fflush
|
||||
status partial
|
||||
alias api-ms-win-crt-stdio-l1-1-0.dll
|
||||
fails stops the guest for a pointer that is no stream
|
||||
ref stdio.h fflush
|
||||
test fflush_and_setvbuf_return_their_documented_results
|
||||
|
||||
service ucrtbase.dll setvbuf(stream: ptr, buffer: ptr, mode: i32, size: u64) -> i32
|
||||
handler setvbuf
|
||||
status partial
|
||||
alias api-ms-win-crt-stdio-l1-1-0.dll
|
||||
fails -1 with errno EINVAL for a null stream, an unknown mode or a size outside 2 to INT_MAX; stops the guest for a pointer that is no stream
|
||||
ref stdio.h setvbuf
|
||||
test fflush_and_setvbuf_return_their_documented_results
|
||||
|
||||
# Files for a hosted C program, on the in-memory drive the handle services use.
|
||||
|
||||
service ucrtbase.dll fopen(name: ptr, mode: ptr) -> ptr
|
||||
handler fopen
|
||||
status partial
|
||||
alias api-ms-win-crt-stdio-l1-1-0.dll
|
||||
fails null with errno EINVAL, ENOENT, EACCES, EMFILE, ENOSPC or ENOMEM
|
||||
ref stdio.h fopen
|
||||
test a_file_written_through_a_stream_reads_back_line_by_line
|
||||
|
||||
service ucrtbase.dll fclose(stream: ptr) -> i32
|
||||
handler fclose
|
||||
status partial
|
||||
alias api-ms-win-crt-stdio-l1-1-0.dll
|
||||
fails EOF with errno EINVAL for a null stream; stops the guest for a standard stream or a pointer that is no stream
|
||||
ref stdio.h fclose
|
||||
test a_file_written_through_a_stream_reads_back_line_by_line
|
||||
|
||||
service ucrtbase.dll fgets(buffer: ptr, count: i32, stream: ptr) -> ptr
|
||||
handler fgets
|
||||
status partial
|
||||
alias api-ms-win-crt-stdio-l1-1-0.dll
|
||||
fails null at end of file; null with errno EINVAL or EBADF; stops the guest for stdin or a pointer that is no stream
|
||||
ref stdio.h fgets
|
||||
test fgets_reads_lines_within_its_count
|
||||
|
||||
service ucrtbase.dll perror(message: ptr) -> void
|
||||
handler perror
|
||||
status partial
|
||||
alias api-ms-win-crt-runtime-l1-1-0.dll
|
||||
fails never
|
||||
ref stdio.h perror
|
||||
test perror_writes_the_message_and_the_error_text_to_stderr
|
||||
|
||||
service kernel32.dll GetLastError() -> u32
|
||||
handler get_last_error
|
||||
status partial
|
||||
alias api-ms-win-core-errorhandling-l1-1-0.dll
|
||||
fails never
|
||||
ref errhandlingapi.h GetLastError
|
||||
test last_error_is_set_by_failures_and_by_the_guest
|
||||
|
||||
service kernel32.dll SetLastError(code: u32) -> void
|
||||
handler set_last_error
|
||||
status partial
|
||||
alias api-ms-win-core-errorhandling-l1-1-0.dll
|
||||
fails never
|
||||
ref errhandlingapi.h SetLastError
|
||||
test last_error_is_set_by_failures_and_by_the_guest
|
||||
|
||||
# What a hosted C program's startup code hands to `main`. The three pointer
|
||||
# functions and the two initialization functions are listed by Microsoft only
|
||||
# by name; crates/loader/src/services/crt_arguments.rs says what is documented,
|
||||
# inferred and Xenora's choice.
|
||||
|
||||
service ucrtbase.dll __p___argc() -> ptr
|
||||
handler argc_pointer
|
||||
status partial
|
||||
alias api-ms-win-crt-runtime-l1-1-0.dll
|
||||
fails stops the guest when the variable cannot be allocated
|
||||
ref Microsoft Learn, C runtime library reference, __argc, __argv, __wargv
|
||||
test program_arguments_reach_the_guest_as_argc_and_argv
|
||||
|
||||
service ucrtbase.dll __p___argv() -> ptr
|
||||
handler argv_pointer
|
||||
status partial
|
||||
alias api-ms-win-crt-runtime-l1-1-0.dll
|
||||
fails stops the guest when the variable cannot be allocated
|
||||
ref Microsoft Learn, C runtime library reference, __argc, __argv, __wargv
|
||||
test program_arguments_reach_the_guest_as_argc_and_argv
|
||||
|
||||
service ucrtbase.dll __p__environ() -> ptr
|
||||
handler environ_pointer
|
||||
status partial
|
||||
alias api-ms-win-crt-environment-l1-1-0.dll
|
||||
fails stops the guest when the variable cannot be allocated
|
||||
ref Microsoft Learn, C runtime library reference, _environ, _wenviron
|
||||
test the_environment_table_is_empty_and_ends_with_a_null_pointer
|
||||
|
||||
service ucrtbase.dll _configure_narrow_argv(mode: i32) -> i32
|
||||
handler configure_narrow_argv
|
||||
status partial
|
||||
alias api-ms-win-crt-runtime-l1-1-0.dll
|
||||
fails EINVAL for a mode other than 0, 1 or 2; stops the guest when the table cannot be allocated
|
||||
ref corecrt_startup.h _configure_narrow_argv
|
||||
test program_arguments_reach_the_guest_as_argc_and_argv
|
||||
|
||||
service ucrtbase.dll _initialize_narrow_environment() -> i32
|
||||
handler initialize_narrow_environment
|
||||
status partial
|
||||
alias api-ms-win-crt-runtime-l1-1-0.dll
|
||||
fails stops the guest when the table cannot be allocated
|
||||
ref corecrt_startup.h _initialize_narrow_environment
|
||||
test the_environment_table_is_empty_and_ends_with_a_null_pointer
|
||||
|
||||
service kernel32.dll VirtualAlloc(address: ptr, size: u64, kind: u32, protect: u32) -> ptr
|
||||
handler virtual_alloc
|
||||
status partial
|
||||
alias api-ms-win-core-memory-l1-1-0.dll
|
||||
fails 0 with ERROR_INVALID_PARAMETER, ERROR_NOT_SUPPORTED, ERROR_INVALID_ADDRESS or ERROR_NOT_ENOUGH_MEMORY
|
||||
ref memoryapi.h VirtualAlloc
|
||||
test virtual_memory_is_mapped_released_and_bounded
|
||||
|
||||
service kernel32.dll VirtualFree(address: ptr, size: u64, kind: u32) -> bool32
|
||||
handler virtual_free
|
||||
status partial
|
||||
alias api-ms-win-core-memory-l1-1-0.dll
|
||||
fails 0 with ERROR_NOT_SUPPORTED, ERROR_INVALID_PARAMETER or ERROR_INVALID_ADDRESS
|
||||
ref memoryapi.h VirtualFree
|
||||
test virtual_memory_is_mapped_released_and_bounded
|
||||
|
||||
# Stubs. A program built with the mingw-w64 runtime imports these three and
|
||||
# does not call them on a normal run. They exist so that its imports bind. A
|
||||
# call stops the guest with the runtime-limit fault and changes nothing.
|
||||
|
||||
service kernel32.dll VirtualProtect(address: ptr, size: u64, protect: u32, old: out<4>) -> bool32
|
||||
handler virtual_protect
|
||||
status stub
|
||||
alias api-ms-win-core-memory-l1-1-0.dll
|
||||
fails always: stops the guest with the runtime-limit fault; no protection changes
|
||||
ref memoryapi.h VirtualProtect
|
||||
test memory_and_exception_stubs_stop_the_guest_and_change_nothing
|
||||
|
||||
service kernel32.dll VirtualQuery(address: ptr, information: out<48>, length: u64) -> u64
|
||||
handler virtual_query
|
||||
status stub
|
||||
alias api-ms-win-core-memory-l1-1-0.dll
|
||||
fails always: stops the guest with the runtime-limit fault; nothing is written
|
||||
ref memoryapi.h VirtualQuery
|
||||
test memory_and_exception_stubs_stop_the_guest_and_change_nothing
|
||||
|
||||
service ucrtbase.dll __C_specific_handler(record: ptr, frame: ptr, context: ptr, dispatcher: ptr) -> i32
|
||||
handler c_specific_handler
|
||||
status stub
|
||||
alias api-ms-win-crt-private-l1-1-0.dll
|
||||
fails always: stops the guest with the runtime-limit fault; no exception is dispatched
|
||||
ref Microsoft Learn, x64 exception handling, language-specific handler
|
||||
test memory_and_exception_stubs_stop_the_guest_and_change_nothing
|
||||
|
||||
service ucrtbase.dll sqrt(x: f64) -> f64
|
||||
handler sqrt
|
||||
status partial
|
||||
alias api-ms-win-crt-math-l1-1-0.dll
|
||||
fails NaN for a negative argument; errno is not set
|
||||
ref math.h sqrt (ISO C, IEC 60559 squareRoot)
|
||||
test floating_arguments_and_results_use_xmm_registers
|
||||
|
||||
service ucrtbase.dll sqrtf(x: f32) -> f32
|
||||
handler sqrtf
|
||||
status partial
|
||||
alias api-ms-win-crt-math-l1-1-0.dll
|
||||
fails NaN for a negative argument; errno is not set
|
||||
ref math.h sqrtf (ISO C, IEC 60559 squareRoot)
|
||||
test floating_arguments_and_results_use_xmm_registers
|
||||
|
||||
service ucrtbase.dll fabs(x: f64) -> f64
|
||||
handler fabs
|
||||
status implemented
|
||||
alias api-ms-win-crt-math-l1-1-0.dll
|
||||
fails never
|
||||
ref math.h fabs (ISO C, IEC 60559 abs)
|
||||
test floating_arguments_and_results_use_xmm_registers
|
||||
|
||||
service ucrtbase.dll fabsf(x: f32) -> f32
|
||||
handler fabsf
|
||||
status implemented
|
||||
alias api-ms-win-crt-math-l1-1-0.dll
|
||||
fails never
|
||||
ref math.h fabsf (ISO C, IEC 60559 abs)
|
||||
test floating_arguments_and_results_use_xmm_registers
|
||||
|
||||
# What a C program's startup code configures before `main`. Each value is
|
||||
# recorded and returned as documented; nothing in the runtime acts on it.
|
||||
|
||||
service ucrtbase.dll _set_app_type(kind: i32) -> void
|
||||
handler set_app_type
|
||||
status partial
|
||||
alias api-ms-win-crt-runtime-l1-1-0.dll
|
||||
fails never
|
||||
ref corecrt_startup.h _set_app_type
|
||||
test crt_app_type_and_math_error_handler_are_recorded
|
||||
|
||||
service ucrtbase.dll _set_new_mode(mode: i32) -> i32
|
||||
handler set_new_mode
|
||||
status partial
|
||||
alias api-ms-win-crt-heap-l1-1-0.dll
|
||||
fails -1 with errno EINVAL for a mode other than 0 or 1
|
||||
ref new.h _set_new_mode
|
||||
test crt_startup_modes_return_the_previous_setting
|
||||
|
||||
service ucrtbase.dll _configthreadlocale(request: i32) -> i32
|
||||
handler configure_thread_locale
|
||||
status partial
|
||||
alias api-ms-win-crt-locale-l1-1-0.dll
|
||||
fails -1 with errno EINVAL for a request other than 0, 1 or 2
|
||||
ref locale.h _configthreadlocale
|
||||
test crt_startup_modes_return_the_previous_setting
|
||||
|
||||
service ucrtbase.dll __setusermatherr(handler: ptr) -> void
|
||||
handler set_user_math_error
|
||||
status partial
|
||||
alias api-ms-win-crt-math-l1-1-0.dll
|
||||
fails never
|
||||
ref corecrt_startup.h __setusermatherr
|
||||
test crt_app_type_and_math_error_handler_are_recorded
|
||||
|
||||
service ucrtbase.dll _set_invalid_parameter_handler(handler: ptr) -> ptr
|
||||
handler set_invalid_parameter_handler
|
||||
status partial
|
||||
alias api-ms-win-crt-runtime-l1-1-0.dll
|
||||
fails never
|
||||
ref stdlib.h _set_invalid_parameter_handler
|
||||
test crt_startup_handlers_return_the_previous_handler
|
||||
|
||||
service ucrtbase.dll __p__fmode() -> ptr
|
||||
handler file_mode_pointer
|
||||
status partial
|
||||
alias api-ms-win-crt-stdio-l1-1-0.dll
|
||||
fails stops the guest when the variable cannot be allocated
|
||||
ref Microsoft Learn, C runtime library reference, __p__fmode
|
||||
test crt_file_mode_variables_are_guest_memory
|
||||
|
||||
service ucrtbase.dll __p__commode() -> ptr
|
||||
handler commit_mode_pointer
|
||||
status partial
|
||||
alias api-ms-win-crt-stdio-l1-1-0.dll
|
||||
fails stops the guest when the variable cannot be allocated
|
||||
ref Microsoft Learn, C runtime library reference, __p__commode
|
||||
test crt_file_mode_variables_are_guest_memory
|
||||
|
||||
service ucrtbase.dll signal(signal: i32, handler: ptr) -> ptr
|
||||
handler signal
|
||||
status partial
|
||||
alias api-ms-win-crt-runtime-l1-1-0.dll
|
||||
fails SIG_ERR with errno EINVAL for a signal the documentation does not list
|
||||
ref signal.h signal
|
||||
test crt_startup_handlers_return_the_previous_handler
|
||||
|
||||
service kernel32.dll SetUnhandledExceptionFilter(filter: ptr) -> ptr
|
||||
handler set_unhandled_exception_filter
|
||||
status partial
|
||||
alias api-ms-win-core-errorhandling-l1-1-0.dll
|
||||
fails never
|
||||
ref errhandlingapi.h SetUnhandledExceptionFilter
|
||||
test crt_startup_handlers_return_the_previous_handler
|
||||
Loaded 100 of 477 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user