mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-27 17:40:28 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2713c9e049 | ||
|
|
bd13b17f30 | ||
|
|
5b99b6bd63 | ||
|
|
b23e6fd6e5 | ||
|
|
d2ca4c3995 | ||
|
|
59b6c4db5e | ||
|
|
ca2fe15d3e | ||
|
|
8fbef1e31f | ||
|
|
6fd254825d | ||
|
|
db3bdb5a5c | ||
|
|
9b20f78a06 | ||
|
|
77cec214c0 | ||
|
|
953254a435 | ||
|
|
39b628d60d | ||
|
|
1d70633958 | ||
|
|
a9f55b51f7 | ||
|
|
722388a46d | ||
|
|
e7ff293eba | ||
|
|
dfaaa07df4 | ||
|
|
962b83c731 | ||
|
|
7fff77c801 | ||
|
|
c3684a1ae8 | ||
|
|
d561595599 | ||
|
|
8cab0b1de8 | ||
|
|
d2367dca30 | ||
|
|
60ad6c779e | ||
|
|
ffc7056d26 | ||
|
|
9923e59114 | ||
|
|
feba95fe39 | ||
|
|
a275de6e2e | ||
|
|
25986845da | ||
|
|
df9652740b | ||
|
|
1ca491d8d0 | ||
|
|
964a8296f2 | ||
|
|
d8a8c96408 | ||
|
|
50321b3f14 | ||
|
|
1fe07f45ee | ||
|
|
d486d21813 | ||
|
|
4c92c88b29 | ||
|
|
478e9218ac | ||
|
|
8d2662dcd7 | ||
|
|
fe1bf568c8 | ||
|
|
873652d685 | ||
|
|
84f561b12b | ||
|
|
2b113a2e5e | ||
|
|
9a26e1ee36 | ||
|
|
c84b80b24f | ||
|
|
ae804f0530 | ||
|
|
64e7b16983 | ||
|
|
1ea898b4bf | ||
|
|
7946968cc4 | ||
|
|
67b8cff9df | ||
|
|
51c23a2f38 | ||
|
|
7d97e67448 | ||
|
|
d9261db887 | ||
|
|
5c0c82b3f9 | ||
|
|
b71db3c25a | ||
|
|
566f803111 | ||
|
|
857c16fcf7 | ||
|
|
4f5c6913f5 | ||
|
|
e4ddb05a1a | ||
|
|
d33a7c6941 | ||
|
|
4e838207fe | ||
|
|
b40bbae1da | ||
|
|
b04b41f26a | ||
|
|
3dd3ef06e2 | ||
|
|
b2654e93a4 | ||
|
|
fee956293d |
No files matched your search
@@ -7,8 +7,9 @@ body:
|
||||
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."
|
||||
description: "hybrid: CrossOver integration, configuration, diagnostics, benchmarks (active). The areas below are preserved native research unless hybrid work requires them. 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:
|
||||
- hybrid
|
||||
- cpu
|
||||
- gpu
|
||||
- runtime
|
||||
@@ -43,7 +44,7 @@ body:
|
||||
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.
|
||||
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
|
||||
|
||||
@@ -1,42 +1,57 @@
|
||||
name: Bug report
|
||||
description: Report a reproducible defect in Xenora or XenoMetal.
|
||||
description: A reproducible defect.
|
||||
title: "bug: "
|
||||
labels: [bug]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
Use synthetic or authorized inputs only. For vulnerabilities, follow SECURITY.md. Remove personal paths, credentials and private data from logs.
|
||||
value: 'Active work is the CrossOver-based hybrid architecture (docs/roadmap.md). Use independently authored or authorized workloads only; never link leaked builds, confidential SDKs or private documentation. Claim by replying on the issue. For vulnerabilities follow SECURITY.md.'
|
||||
- type: textarea
|
||||
id: description
|
||||
attributes:
|
||||
label: Description
|
||||
description: What went wrong? Identify the affected subsystem and expected behavior.
|
||||
description: 'What went wrong and what you expected.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: steps
|
||||
attributes:
|
||||
label: Reproduction steps
|
||||
description: Include exact commands and a minimal, legally distributable input if applicable.
|
||||
description: 'Exact commands and a minimal, legally distributable input.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: environment
|
||||
attributes:
|
||||
label: Environment
|
||||
description: Commit, macOS, Apple GPU, RAM, Rust, Xcode and relevant tool versions. Include sanitized doctor output if available.
|
||||
description: 'Commit, macOS, chip, memory, CrossOver and Rosetta 2 versions, graphics backend. Remove personal paths and credentials.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: output
|
||||
id: scope
|
||||
attributes:
|
||||
label: Actual output and diagnostics
|
||||
description: Include expected versus actual results, validation-layer messages and relevant logs.
|
||||
- type: checkboxes
|
||||
id: confirmation
|
||||
label: Scope and dependencies
|
||||
description: 'Affected area; related issues.'
|
||||
validations:
|
||||
required: false
|
||||
- type: textarea
|
||||
id: acceptance
|
||||
attributes:
|
||||
label: Confirmation
|
||||
options:
|
||||
- label: I searched for existing reports and have not included sensitive or unauthorized material.
|
||||
required: true
|
||||
label: Acceptance criteria
|
||||
description: 'When is this fixed?'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: validation
|
||||
attributes:
|
||||
label: Validation requirements
|
||||
description: 'How to confirm the fix independently.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: licensing
|
||||
attributes:
|
||||
label: Licensing and provenance
|
||||
description: 'Only if third-party code or a dependency is involved.'
|
||||
validations:
|
||||
required: false
|
||||
@@ -0,0 +1,50 @@
|
||||
name: Documentation
|
||||
description: Fix, add or restructure documentation.
|
||||
title: "docs: "
|
||||
labels: [documentation]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: 'Active work is the CrossOver-based hybrid architecture (docs/roadmap.md). Use independently authored or authorized workloads only; never link leaked builds, confidential SDKs or private documentation. Claim by replying on the issue.'
|
||||
- type: textarea
|
||||
id: problem
|
||||
attributes:
|
||||
label: Problem
|
||||
description: 'What is unclear, wrong or missing.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: context
|
||||
attributes:
|
||||
label: Technical context
|
||||
description: 'Pages and sources involved.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: scope
|
||||
attributes:
|
||||
label: Scope
|
||||
description: 'Files to change; update docs/README.md if pages are added or moved.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: dependencies
|
||||
attributes:
|
||||
label: Dependencies
|
||||
description: 'None if none.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: acceptance
|
||||
attributes:
|
||||
label: Acceptance criteria
|
||||
description: 'Claims are scoped to their evidence; links work.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: validation
|
||||
attributes:
|
||||
label: Validation requirements
|
||||
description: 'scripts/audit/docs_hygiene.py and claims audit pass.'
|
||||
validations:
|
||||
required: true
|
||||
@@ -1,31 +0,0 @@
|
||||
name: Feature proposal
|
||||
description: Propose a compiler, graphics, tooling or other project enhancement.
|
||||
title: "feat: "
|
||||
labels: [enhancement]
|
||||
body:
|
||||
- type: textarea
|
||||
id: problem
|
||||
attributes:
|
||||
label: Problem or gap
|
||||
description: Which limitation does this feature address?
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: proposal
|
||||
attributes:
|
||||
label: Proposed approach
|
||||
description: Explain the intended behavior and affected components. Link relevant public specifications when available.
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: criteria
|
||||
attributes:
|
||||
label: Acceptance criteria
|
||||
description: What observable results and tests would demonstrate completion?
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: alternatives
|
||||
attributes:
|
||||
label: Alternatives and trade-offs
|
||||
description: Include limitations, dependency costs or impacts on native ARM64 and Metal if relevant.
|
||||
@@ -1,31 +0,0 @@
|
||||
name: Hardware verification report
|
||||
description: Submit real hardware test results for Xenora.
|
||||
title: "hardware: "
|
||||
labels: [needs-verification]
|
||||
body:
|
||||
- type: textarea
|
||||
id: environment
|
||||
attributes:
|
||||
label: Test environment
|
||||
description: Commit, Apple chip/GPU, RAM, macOS, Xcode/Metal version, Rust version, validation settings. Do not include serial numbers or registry IDs.
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: commands
|
||||
attributes:
|
||||
label: Commands and inputs
|
||||
description: Include exact commands and synthetic or authorized fixture identifiers.
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: results
|
||||
attributes:
|
||||
label: Results
|
||||
description: Report actual output, pass/fail/skip counts, and limitations. Compilation alone does not prove execution.
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: performance
|
||||
attributes:
|
||||
label: Performance data (optional)
|
||||
description: Include repetitions, warm-up, timing method, validation state and variability if reporting measurements.
|
||||
@@ -0,0 +1,57 @@
|
||||
name: Hybrid engineering task
|
||||
description: Integration, configuration, diagnostics or tooling around CrossOver.
|
||||
title: "task: "
|
||||
labels: [track: hybrid]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: 'Active work is the CrossOver-based hybrid architecture (docs/roadmap.md). Use independently authored or authorized workloads only; never link leaked builds, confidential SDKs or private documentation. Claim by replying on the issue.'
|
||||
- type: textarea
|
||||
id: problem
|
||||
attributes:
|
||||
label: Problem
|
||||
description: 'What is missing or wrong, and why it matters for the hybrid architecture.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: context
|
||||
attributes:
|
||||
label: Technical context
|
||||
description: 'Versions (macOS, chip, CrossOver, Rosetta 2, graphics backend), related issues, upstream references.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: scope
|
||||
attributes:
|
||||
label: Scope
|
||||
description: 'What is in and out. Avoid duplicating what CrossOver already provides.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: dependencies
|
||||
attributes:
|
||||
label: Dependencies
|
||||
description: "Blocking issues or decisions; write 'none' if none."
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: acceptance
|
||||
attributes:
|
||||
label: Acceptance criteria
|
||||
description: 'Observable, checkable results.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: validation
|
||||
attributes:
|
||||
label: Validation requirements
|
||||
description: 'How an independent contributor verifies it; commands, workloads, evidence class.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: licensing
|
||||
attributes:
|
||||
label: Licensing and provenance
|
||||
description: "Licenses of any component involved, source and version, and whether anything would be bundled or copied. Write 'not applicable' if none."
|
||||
validations:
|
||||
required: true
|
||||
@@ -0,0 +1,57 @@
|
||||
name: Performance investigation
|
||||
description: Measure or improve performance with evidence.
|
||||
title: "perf: "
|
||||
labels: [performance,track: hybrid]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: 'Active work is the CrossOver-based hybrid architecture (docs/roadmap.md). Use independently authored or authorized workloads only; never link leaked builds, confidential SDKs or private documentation. Claim by replying on the issue. Do not promise gains before measuring.'
|
||||
- type: textarea
|
||||
id: problem
|
||||
attributes:
|
||||
label: Problem and metric
|
||||
description: 'Which metric (average FPS, 1% low, frame-time percentiles, CPU or GPU use, memory, startup, shader compile latency) and why.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: context
|
||||
attributes:
|
||||
label: Technical context
|
||||
description: 'Workload, hardware (reference: M4, 24 GB), software versions, settings.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: scope
|
||||
attributes:
|
||||
label: Scope
|
||||
description: 'Measurement only, or change as well.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: dependencies
|
||||
attributes:
|
||||
label: Dependencies
|
||||
description: 'Measurement protocol (#353) and baseline (#355).'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: acceptance
|
||||
attributes:
|
||||
label: Acceptance criteria
|
||||
description: 'Measured before-and-after under equivalent conditions, with variance.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: validation
|
||||
attributes:
|
||||
label: Validation requirements
|
||||
description: 'Correctness and rendering equivalence verified before the result counts.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: licensing
|
||||
attributes:
|
||||
label: Licensing and provenance
|
||||
description: "Licenses of any component involved, source and version, and whether anything would be bundled or copied. Write 'not applicable' if none."
|
||||
validations:
|
||||
required: true
|
||||
@@ -1,42 +1,57 @@
|
||||
name: Technical research
|
||||
description: Record an ISA, Metal or publicly documented graphics research finding.
|
||||
name: Upstream research or dependency evaluation
|
||||
description: Assess a project, component or license from public sources.
|
||||
title: "research: "
|
||||
labels: [research]
|
||||
labels: [research,track: hybrid]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: Use only public, authorized sources. Do not link to leaked SDKs, private documentation or unauthorized game content.
|
||||
value: 'Active work is the CrossOver-based hybrid architecture (docs/roadmap.md). Use independently authored or authorized workloads only; never link leaked builds, confidential SDKs or private documentation. Claim by replying on the issue.'
|
||||
- type: textarea
|
||||
id: question
|
||||
id: problem
|
||||
attributes:
|
||||
label: Research question or finding
|
||||
label: Question
|
||||
description: 'The decision this research informs.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: sources
|
||||
id: context
|
||||
attributes:
|
||||
label: Sources and applicability
|
||||
description: URLs, specification sections or revision, exact architecture and license/provenance if relevant.
|
||||
label: Technical context
|
||||
description: 'What is already known; link docs/research/upstream-registry.md entries.'
|
||||
validations:
|
||||
required: true
|
||||
- type: dropdown
|
||||
id: evidence
|
||||
- type: textarea
|
||||
id: scope
|
||||
attributes:
|
||||
label: Evidence class (highest applicable)
|
||||
options:
|
||||
- A - Measured on named hardware
|
||||
- B - Normative source for exact target
|
||||
- C - Normative source for related target
|
||||
- D - Non-normative official material
|
||||
- E - Independent software behavior
|
||||
- F - Uncorroborated community claim
|
||||
- U - Unknown or assumption
|
||||
label: Scope
|
||||
description: 'Which versions or components; desk research or execution.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: dependencies
|
||||
attributes:
|
||||
label: Dependencies
|
||||
description: 'Other issues or decisions; execution may need a maintainer-approved environment.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: acceptance
|
||||
attributes:
|
||||
label: Acceptance criteria
|
||||
description: 'Each claim cites vendor or upstream documentation, or a recorded observation of a stated version; unknowns stay marked unknown.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: validation
|
||||
attributes:
|
||||
label: Validation, limitations and proposed next steps
|
||||
description: Distinguish Apple or desktop RDNA observations from Xbox behavior.
|
||||
label: Validation requirements
|
||||
description: 'Independent re-derivation and evidence class (A to U).'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: licensing
|
||||
attributes:
|
||||
label: Licensing and provenance
|
||||
description: "Licenses of any component involved, source and version, and whether anything would be bundled or copied. Write 'not applicable' if none."
|
||||
validations:
|
||||
required: true
|
||||
@@ -0,0 +1,57 @@
|
||||
name: Testing and validation
|
||||
description: Add or run a validation for a workload or behaviour.
|
||||
title: "validate: "
|
||||
labels: [needs-verification,track: hybrid]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: 'Active work is the CrossOver-based hybrid architecture (docs/roadmap.md). Use independently authored or authorized workloads only; never link leaked builds, confidential SDKs or private documentation. Claim by replying on the issue.'
|
||||
- type: textarea
|
||||
id: problem
|
||||
attributes:
|
||||
label: Problem
|
||||
description: 'What is missing or wrong, and why it matters for the hybrid architecture.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: context
|
||||
attributes:
|
||||
label: Technical context
|
||||
description: 'Versions (macOS, chip, CrossOver, Rosetta 2, graphics backend), related issues, upstream references.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: scope
|
||||
attributes:
|
||||
label: Scope
|
||||
description: 'What is in and out. Avoid duplicating what CrossOver already provides.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: dependencies
|
||||
attributes:
|
||||
label: Dependencies
|
||||
description: "Blocking issues or decisions; write 'none' if none."
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: acceptance
|
||||
attributes:
|
||||
label: Acceptance criteria
|
||||
description: 'Observable, checkable results.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: validation
|
||||
attributes:
|
||||
label: Validation requirements
|
||||
description: 'How an independent contributor verifies it; commands, workloads, evidence class.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: licensing
|
||||
attributes:
|
||||
label: Licensing and provenance
|
||||
description: "Licenses of any component involved, source and version, and whether anything would be bundled or copied. Write 'not applicable' if none."
|
||||
validations:
|
||||
required: true
|
||||
@@ -1,40 +0,0 @@
|
||||
## Summary
|
||||
|
||||
<!-- What changes, and why? -->
|
||||
|
||||
Closes #<!-- the issue you claimed -->
|
||||
|
||||
## Implementation and evidence
|
||||
|
||||
<!-- Describe affected subsystems, architecture assumptions, specification sections and upstream provenance where applicable. -->
|
||||
|
||||
## Verification
|
||||
|
||||
<!-- List actual commands and outcomes. Include hardware, validation-layer state and pass/fail/skip counts for GPU tests. Mark unrun checks explicitly. -->
|
||||
|
||||
| Check | Result / evidence |
|
||||
| --- | --- |
|
||||
| Formatting and lint | |
|
||||
| Unit / integration tests | |
|
||||
| GPU / differential tests | |
|
||||
| Fuzzing / mutation / benchmarks, if relevant | |
|
||||
|
||||
## Compatibility and limitations
|
||||
|
||||
<!-- Note unsupported behavior, regressions, interface changes, performance effects and remaining uncertainty. -->
|
||||
|
||||
## 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.
|
||||
- [ ] I did not report skipped or unrun tests as passing.
|
||||
- [ ] I updated applicable documentation, claims and status records.
|
||||
- [ ] Third-party code and fixtures have verified licenses and provenance, or none were added.
|
||||
- [ ] No restricted materials, credentials or private data are included.
|
||||
- [ ] My commits are signed off under the DCO.
|
||||
|
||||
## AI assistance
|
||||
|
||||
<!-- Describe material assistance and the checks you personally performed, or state none. -->
|
||||
@@ -0,0 +1,29 @@
|
||||
## Related issue
|
||||
|
||||
Closes #
|
||||
|
||||
## Summary
|
||||
|
||||
## Technical changes
|
||||
|
||||
## Tests performed
|
||||
|
||||
Commands, versions, pass/fail/skip counts and hardware. A skipped test is not a pass.
|
||||
|
||||
## Performance impact
|
||||
|
||||
Measured before and after under equivalent conditions, or "none expected" with reason.
|
||||
|
||||
## Compatibility impact
|
||||
|
||||
Workloads, macOS or CrossOver versions and hardware affected. Do not claim support that was not tested.
|
||||
|
||||
## Known limitations
|
||||
|
||||
## Third-party code attribution
|
||||
|
||||
Source repository, exact commit, license, modifications. "None" if none.
|
||||
|
||||
## Dependency and licensing considerations
|
||||
|
||||
New or changed dependencies, license compatibility with GPL-3.0-or-later, redistribution limits (proprietary components are never bundled). DCO: commits are signed off.
|
||||
@@ -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
|
||||
@@ -63,8 +63,6 @@ jobs:
|
||||
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
|
||||
@@ -90,3 +88,33 @@ jobs:
|
||||
file "$binary"
|
||||
test "$(lipo -archs "$binary")" = arm64
|
||||
otool -L "$binary"
|
||||
|
||||
native-app:
|
||||
name: Native app build and smoke
|
||||
runs-on: macos-26
|
||||
timeout-minutes: 20
|
||||
env:
|
||||
CARGO_BUILD_JOBS: 3
|
||||
RUSTUP_TOOLCHAIN: 1.100.0-aarch64-apple-darwin
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Verify runner architecture
|
||||
run: |
|
||||
uname -m
|
||||
test "$(uname -m)" = arm64
|
||||
test "$(sysctl -n sysctl.proc_translated)" = 0
|
||||
- name: Install native Rust
|
||||
run: |
|
||||
rustup toolchain install "$RUSTUP_TOOLCHAIN" --profile minimal
|
||||
rustc -vV
|
||||
- name: Show Swift and Xcode
|
||||
run: |
|
||||
xcodebuild -version
|
||||
swift --version
|
||||
# Builds the locked C ABI library and the Swift app together, checks the
|
||||
# executable is arm64-only and links only system libraries, and runs
|
||||
# `--smoke`. This is an app build and smoke result, not GPU verification.
|
||||
- name: Build BetterXen.app and run its smoke check
|
||||
run: scripts/build-app.sh
|
||||
@@ -0,0 +1,43 @@
|
||||
name: Repository hygiene
|
||||
|
||||
# Fast checks on tracked files that need no Rust toolchain and no network:
|
||||
# merge-conflict markers, broken relative Markdown links and invalid workflow
|
||||
# YAML (scripts/audit/docs_hygiene.py). A second, advisory step warns when
|
||||
# source or script changes arrive without a CHANGELOG.md update; it never fails.
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: hygiene-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
hygiene:
|
||||
name: Repository hygiene
|
||||
runs-on: ubuntu-24.04-arm
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
fetch-depth: 0
|
||||
- name: Install PyYAML
|
||||
run: python3 -c 'import yaml' 2>/dev/null || python3 -m pip install --user --break-system-packages pyyaml
|
||||
- name: Check documentation and workflow files
|
||||
run: python3 scripts/audit/docs_hygiene.py --require-yaml
|
||||
- name: Remind about the changelog (advisory)
|
||||
if: github.event_name == 'pull_request'
|
||||
env:
|
||||
BASE_SHA: ${{ github.event.pull_request.base.sha }}
|
||||
run: |
|
||||
changed="$(git diff --name-only "$BASE_SHA"...HEAD || true)"
|
||||
if printf '%s\n' "$changed" | grep -Eq '^(crates|scripts|shaders|fixtures)/' \
|
||||
&& ! printf '%s\n' "$changed" | grep -qx 'CHANGELOG.md'; then
|
||||
echo "::warning title=Changelog::Source or script files changed without a CHANGELOG.md update."
|
||||
fi
|
||||
@@ -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"
|
||||
+2
-2
@@ -36,8 +36,8 @@
|
||||
__pycache__/
|
||||
*.pyc
|
||||
/diagnostics/probe/
|
||||
/diagnostics/gta6-candidate-*/
|
||||
/diagnostics/gta6-check/
|
||||
/diagnostics/title-candidate-*/
|
||||
/diagnostics/title-check/
|
||||
|
||||
# Native application build output
|
||||
/app/.build/
|
||||
@@ -1,40 +1,60 @@
|
||||
# BetterXen engineering rules
|
||||
|
||||
### Native Apple Silicon
|
||||
These rules apply to every contributor and coding agent. They were rewritten on the `planning/hybrid-first-transition` branch when BetterXen moved from native-first to CrossOver-based hybrid development. `CLAUDE.md` is a symlink to this file. The decision is recorded in `docs/adr/0005-crossover-hybrid-direction.md`; the plan is `docs/roadmap.md`.
|
||||
|
||||
Never introduce Rosetta 2, x86-64 host executables, MoltenVK, Vulkan runtime dependencies, Wine, CrossOver, Windows compatibility layers, OpenGL fallback rendering, or unnecessary graphics abstraction layers.
|
||||
### Direction
|
||||
|
||||
- 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.
|
||||
- BetterXen is hybrid-first Apple Silicon compatibility research. **CrossOver is the primary compatibility foundation and hybrid is the only active development direction.** CrossOver is an externally installed dependency unless its license explicitly permits another distribution model.
|
||||
- BetterXen's own work is the layer around it: integration, configuration, environment management, diagnostics, reproducible testing, benchmarking and measured optimization. Reuse established infrastructure before writing an independent replacement; write one only for a demonstrated limitation.
|
||||
- The independent native implementation (x86-64 decoder, ARM64 translator, runtime, gfx1030 shader compiler, Metal backend) is **preserved and paused**. Do not delete it, expand its roadmap, create speculative native issues or assign contributors to it by default. Native work is allowed only when hybrid development directly requires it, or after an explicit maintainer decision to resume (`docs/research/native-roadmap.md`). Keep its tests passing.
|
||||
- This is the intended architecture, not a verified Xbox compatibility stack. Do not assume CrossOver, Rosetta 2 or D3DMetal provide Xbox runtime compatibility; verify the actual capabilities and integration boundaries of the installed versions.
|
||||
|
||||
### Planning
|
||||
|
||||
- Planning is progressive. Only the current phase has a milestone and open issues; the roadmap outlines later phases provisionally and `Parked ideas` holds future items. Do not create speculative issues, trackers or milestones for distant phases; promote an idea when its prerequisites are met.
|
||||
- Every new issue states a specific problem, the evidence it is needed, a deliverable, upstream references, a reuse assessment, dependencies, acceptance criteria and a validation method. Do not create administrative issues to manage planning.
|
||||
- Do not open native-only issues. If hybrid work needs a native component, file a focused hybrid issue.
|
||||
|
||||
### Dependencies and reuse
|
||||
|
||||
- Wine-based compatibility infrastructure, CrossOver, Rosetta 2 where supported and technically appropriate, and D3DMetal (subject to its license terms) are permitted. DXMT, DXVK, VKD3D-Proton, MoltenVK, FEX and similar projects may be evaluated and used where appropriate. Legitimate external dependencies and open-source implementations are encouraged.
|
||||
- Before integrating or copying anything: verify the exact license of the component (the file for copied source, not just the repository), check compatibility with GPL-3.0-or-later and with every other selected component, preserve copyright notices, record the source repository and exact commit or version, document modifications, and add the entry to `docs/research/upstream-registry.md` and `docs/research/component-reuse-matrix.md`. If licensing is uncertain, do not use it until resolved. Never remove upstream notices.
|
||||
- Do not bundle, modify or redistribute proprietary components (CrossOver binaries, D3DMetal, Rosetta 2, Apple tools) unless their license explicitly allows it. Do not assume a proprietary component can be incorporated into GPL-licensed source. Distinguish open-source parts from proprietary parts in every assessment.
|
||||
- Do not bypass licensing or activation requirements of any dependency.
|
||||
- Provenance first: exclude anything derived from leaked proprietary material or unauthorized software. A project's license being GPL does not clear material it was built from or for. Projects whose stated purpose depends on leaked or unauthorized builds, including VIctory, its forks and similar efforts, are discovery references at documentation level; adopt nothing from them without a per-file provenance and license review recorded in the registry. Game-specific, asset-specific and decryption-related code is never adopted.
|
||||
|
||||
### Native Apple Silicon host
|
||||
|
||||
- BetterXen's own host executables, libraries and tools must support ARM64 natively; verify with file, lipo -archs and otool -L. Do not add x86-64 host executables that BetterXen itself builds or ships.
|
||||
- Rosetta 2 may be used where Apple supports it and CrossOver or another selected component relies on it for x86-64 guest code. Record versions and its support status; do not depend on it for BetterXen's own code.
|
||||
- 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.
|
||||
- Use aarch64-apple-darwin as the Rust target. Metal is the host graphics API. Do not add graphics abstraction layers beyond what a selected component or a measured need justifies.
|
||||
- SPIR-V remains permitted as a compiler intermediate representation.
|
||||
|
||||
### Honesty and evidence
|
||||
|
||||
- Never report a test as passed unless it ran and passed. Never count a skipped test as GPU verification.
|
||||
- Never invent benchmark results, hardware compatibility, API names, instruction encodings, hardware capabilities or implementation status.
|
||||
- Never invent benchmark results, hardware compatibility, API names, instruction encodings, hardware capabilities, interface details, product capabilities or implementation status. Never promise a performance improvement before measuring it.
|
||||
- Never claim a clean build unless the commands actually succeeded.
|
||||
- Never present planned features as working. State clearly that game execution is not supported unless demonstrated.
|
||||
- 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.
|
||||
- Unknown information is classified as unknown and becomes a documented research task. Facts about CrossOver, Rosetta 2, D3DMetal and other upstreams must cite vendor or upstream documentation, or a recorded observation of a stated version.
|
||||
- Every hardware claim carries an evidence class (see docs/claims.toml). 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.
|
||||
- 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.
|
||||
- A phase is complete only with the evidence its exit conditions name. Do not derive progress from commits, lines of code, closed issues or isolated passing fixtures.
|
||||
|
||||
### Independence of verification
|
||||
|
||||
- The agent that writes a component does not certify it. The two independent reviewers (section 5) re-derive expectations from primary sources and are not told the implementers' conclusions as ground truth.
|
||||
- The agent that writes a component does not certify it. Independent reviewers re-derive expectations from primary sources and are not told the implementers' conclusions as ground truth.
|
||||
- The same faulty code must never produce both the expected and the actual values in a test.
|
||||
|
||||
### Legal and clean-room
|
||||
|
||||
- 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.
|
||||
- Use only publicly accessible documentation, publicly licensed software and authorized materials. All validation uses independently authored or authorized workloads. Never obtain or use leaked executables or SDKs, confidential Xbox documentation, restricted console tools, firmware, encryption keys, unauthorized assets or source code, or proprietary game builds 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.
|
||||
- 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.
|
||||
- docs/legal.md states: BetterXen does not circumvent console security or DRM, does not load encrypted or protected content, and is a research project built from public documentation. This is not legal advice; contributors should know their local laws, including anti-circumvention provisions such as DMCA section 1201.
|
||||
- Keep BetterXen's own implementation original where it is original. Never copy, port, translate or adapt source from emulator projects built for leaked or unauthorized material (for example PE-Vulkan, KyTx, AnyPS5 and similar).
|
||||
- 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.
|
||||
@@ -43,7 +63,7 @@ Never introduce Rosetta 2, x86-64 host executables, MoltenVK, Vulkan runtime dep
|
||||
|
||||
No AI slop (section 29).
|
||||
|
||||
Read docs/interfaces.md and docs/progress.md before implementation.
|
||||
Read docs/roadmap.md, docs/interfaces.md and docs/progress.md before implementation.
|
||||
|
||||
## Claiming work before you start
|
||||
|
||||
@@ -84,7 +104,7 @@ A coding agent claims in the name of the person it works for and follows the sam
|
||||
- Lint: `cargo clippy --workspace --all-targets -- -D warnings`
|
||||
- Test: `cargo test --workspace`
|
||||
- Verify the synthetic fixtures: `scripts/assemble-fixture.sh --check`
|
||||
- Run native GPU correctness: `scripts/test-gpu.sh`
|
||||
- Run native GPU correctness (preserved native research): `scripts/test-gpu.sh`
|
||||
- Run the three RDNA-to-Metal fixtures: `scripts/demo.sh`
|
||||
- Run independent CPU validation: `cargo test --locked -p xenora-semantic-review`
|
||||
- Run the correctness-gated benchmark suite: `scripts/benchmark.sh` (idle machine, release, validation off)
|
||||
@@ -101,4 +121,4 @@ 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.
|
||||
These are responsibility areas, not personal assignments; do not assign people without their agreement. Hybrid integration owns the CrossOver assessment, integration boundary, configuration, diagnostics and benchmarks. 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.
|
||||
@@ -9,7 +9,29 @@ exact revision and known limitations.
|
||||
Guest execution uses original, purpose-built test programs. Commercial Xbox game execution
|
||||
remains unsupported.
|
||||
|
||||
### Added
|
||||
- Review follow-up on the proposed `victory-shader` import (#394): `translate_native` now reports immediate samplers as static samplers (a sampled texel read 0 on the GPU before), BetterXen's GPU tests use a host that `VICTORY_WARP` cannot redirect, the double-precision probes take run-time operands and were rerun (same result), and a per-file provenance review records that the crate was developed against one commercial title's shaders. **The import is not approved; a maintainer decision is required** (`docs/research/victory-shader-provenance.md`). Earlier statements that the crate had nothing game-specific are withdrawn.
|
||||
- Fixed the two wave-operation failures the vendored victory-shader tests showed under D3DMetal (`docs/research/shader-wave-semantics.md`). Device capabilities were measured with a new original D3D12 host (`workloads/d3d12-wave-probe`): shader model 6.6, wave operations, waves exactly 32 lanes, no double-precision shader operations. One failure was a wrong test precondition (a 64-lane lowering run on the 32-lane device); the test now checks the device width and asserts the recompiler's refusal. The other was unsupported double-precision operations: shaders compiled from original HLSL by Microsoft's DXC that use a `double` ran without writing anything, while float wave operations worked. The recompiler's one native-double site (`active_f64_sum`) now builds the console's balanced sum tree with its existing integer fp64 add and no longer declares doubles. Local results on one Apple M4 under CrossOver 26.3, not independently reproduced: the whole suite passes (229 passed, 3 ignored; the vendored original had 2 failures); 24 new GPU cases compare full 64-bit sums with a CPU model of the tree; both regression tests fail against the original lowering. Cost not measured; tree-order fidelity relies on the recompiler's own recognizer.
|
||||
- Added `scripts/hybrid/run-shader-gpu-tests.sh`, which cross-builds the vendored `victory-shader` test executable for Windows and runs it under CrossOver through `betterxen-hybrid run` (supervision, memory guard, stall detection, JSON record), either BetterXen's ten tests or the whole upstream suite. It takes both the runner and the test executable from the messages of the cargo invocations that built them, and stops if a build fails (review fix: an earlier version piped cargo into the parser, so a failed build exited 0 and ran a stale executable, and it assumed the runner was under `target/`). `scripts/hybrid/test-run-shader-gpu-tests.sh` is a stubbed regression test for both. It needs the runner from #384 and #388. Verified on the Apple M4 with CrossOver 26.3: fixtures pass; the whole suite shows the known failures; there is no fallback to a guessed path. Not independently reviewed.
|
||||
- Integrated skakwy's `victory-shader` (GFX10/RDNA 2 machine code to DXIL SM 6.6 recompiler, about 43,500 lines of Rust) as `crates/victory-shader`, with provenance in its `UPSTREAM.md`, the Mesa notice preserved and 19 lines of lint-only edits to upstream files. Added `translate_native` and tests that translate BetterXen's own gfx1030 fixtures to DXIL and, on Windows targets, run them on the GPU through D3D12. Local results on one Apple M4 with CrossOver 26.3 (D3DMetal), not independently reproduced: 177 upstream CPU-side tests pass on macOS; all 6 fixtures with expected words matched the manifest on the GPU, with a negative control; the GPU tests fail without D3D12 instead of skipping; the full upstream suite under CrossOver has 224 passed, 2 failed, 3 ignored. DXIL validation by `dxil.dll` was not run. The native RDNA-to-Metal compiler is unchanged. See `docs/research/victory-shader-integration.md`.
|
||||
- Added the upstream research registry and component reuse matrix (`docs/research/`), a public-documentation review (evidence class D, nothing executed) of CrossOver, Wine, DXMT, DXVK, VKD3D-Proton, MoltenVK, FEX, VIctory, VIctory-macOS and PortWatch. VIctory-family projects are excluded from reuse on provenance grounds. The GitHub project board is not yet configured because the token lacks the `project` scope (#346).
|
||||
- Added hybrid research records: `docs/research/hybrid-backlog-research-2026-11-25.md` (findings and registry candidates, from search summaries) and `docs/research/primary-source-verification-2026-11-25.md` (re-check against CodeWeavers, Apple, DXMT and Wine primary pages). It confirms CrossOver's backend list, finds no public documentation of `CX_GRAPHICS_BACKEND`, and records that two Apple notices on Rosetta's end disagree; D3DMetal's license text and CrossOver's Rosetta and ARM64 plans remain unverified. Eleven issues created from the research were reviewed the same day: #364 and #365 stay in Phase 1, the others are parked and recorded under "Parked ideas" in the roadmap. Rust 1.100.0 (already installed) is the required toolchain; the default `stable` was 1.94.1. Planning only; nothing was installed or run.
|
||||
- Added File > Open Executable… with Command-O to the app (#252). It opens the focused window's read-only file importer, the same one as that window's button, and is disabled when no window can present it; each window keeps its own importer, so with several windows only the focused one shows the picker. The chosen file goes through the same inspection path as the button, drag and drop and Finder Open With; nothing is executed. A file-importer failure is now shown in red with the system's description instead of being ignored, a cancelled picker shows nothing, and the message clears on the next selection. `BetterXen --smoke-import-result`, run by `scripts/build-app.sh`, checks cancellation, a shown failure and its clearing; it fails on the previous importer handling. Checked locally on Apple Silicon in the running app (Command-O and the menu item open the picker, cancel shows no error, a second Command-O opens it again, with two windows only the focused one presents it, and with every window closed the menu item is disabled); not yet independently reviewed.
|
||||
- Added `docs/research/texture-formats.md`, an inventory of the texture formats and layouts BetterXen handles (#260). For BC1–BC7, RGBA8 and Depth32Float it separates container recognition, CPU decoding, layout conversion, native Metal upload and readback, translated sampling, the host-side D3D12-shaped API (called from Rust, not wired to guest imports) and guest reachability through imported services, and links each cell's implementing files and tests and each format's exact public specification sections, including the packed BC footprints from #241. It cross-references #208 and #209 instead of opening duplicate tasks, lists console layouts, console descriptors and asset or audio containers as unknowns, and ranks three proposed follow-ups with fixture recipes and owners. Research only; no implementation changed.
|
||||
- Rewrote the README around the six development phases and the first-launchable-application target (#311), with colour-coded Mermaid diagrams (system flow, milestone roadmap, CPU, runtime-service and shader-form charts built from the generated registries), badges, a repository overview, a contributing section and corrected texture-sampling wording. The older X1–X25 capability map is kept in a collapsible section. The diagrams were not render-tested locally.
|
||||
- Added a fast "Repository hygiene" check (`.github/workflows/hygiene.yml`, `scripts/audit/docs_hygiene.py`). It runs on Ubuntu without a Rust toolchain or network access and fails only on merge-conflict markers, broken relative Markdown links and invalid workflow YAML in tracked files. A separate advisory step warns, without failing, when source or script changes have no changelog entry. A local run over the 626 tracked files found no problems, and planted failures of each kind were caught; it has not yet run on GitHub.
|
||||
- Documented the proposed guest AVX/AVX2 state and decoding contract and specified an original integer fixture with known results and fault controls (#299).
|
||||
|
||||
### Removed
|
||||
- Removed the "Agent PR checks" workflow (`.github/workflows/agent-pr-checks.yml`), its section in `docs/coordination/agent-tasks.md` and the four workflow tests in `tests/agent_queue/test_workflows_cli.py` that only exercised it. Pull requests are no longer checked for `Closes #N`, task file patterns or `/verified` comments; the claims workflow and its tests are unchanged. The agent queue Python tests pass locally (85 tests).
|
||||
- Removed the "PR template" check (`.github/workflows/pr-template.yml`, `scripts/pr_template_check.py` and its tests) and its CI test step. Also removed `.github/PULL_REQUEST_TEMPLATE.md`. Pull request descriptions are no longer validated or pre-filled; CONTRIBUTING.md still asks for the same information and the claim-first rule still applies.
|
||||
|
||||
### Changed
|
||||
- Replaced the native-first development plan with a CrossOver-based hybrid roadmap (`docs/roadmap.md`: five provisional phases, only Phase 1 active; the earlier H0 to H7 breakdown is archived) and an accepted-direction ADR 0005. No hybrid component exists yet and no Xbox title is shown to run; this is planning and research scheduling only, and no phase is verified complete.
|
||||
- Rewrote the engineering rules in `AGENTS.md` (`CLAUDE.md` is a symlink to it) to permit CrossOver, Wine-based infrastructure, Rosetta 2 and D3DMetal subject to licensing, while keeping the honesty, independent-verification, provenance and clean-room rules and adding dependency and reuse rules. Resolves #345.
|
||||
- Native work is preserved and paused: tag `native-first-final` marks the last `main` commit before this change, `docs/research/native-roadmap.md`, and archived native-first plan and milestones under `docs/archive/`. GitHub backlog: all native issues except four with assigned contributors and open pull requests were closed as not planned and indexed in `docs/research/native-issue-archive.md`; future-phase issues were parked in the roadmap; only the Phase 1 milestone is open.
|
||||
- Replaced the issue templates with hybrid task, bug, research, performance, validation and documentation forms and added a pull request template. Fixed invalid YAML in the agent-task template. README, CONTRIBUTING and the docs index now describe the hybrid direction.
|
||||
- Replaced our own references to a specific commercial game title (README non-affiliation line, research and integration notes, ignored diagnostics folder names) with generic "commercial title" wording. The ignored folder names are now `diagnostics/title-candidate-*` and `diagnostics/title-check`. Third-party repository names, URLs and code-span paths in research notes are unchanged so their provenance stays accurate. Our own prose references to the upstream project formerly named in the research notes now read "PE-Vulkan project". Added the PortWatch native-macOS research notes. No behavior change.
|
||||
- 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.
|
||||
@@ -20,6 +42,7 @@ remains unsupported.
|
||||
- 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 uses one 32-bit `MOVN` for zero-extended constants such as `0xFFFF1234` that previously took two wide moves (#89). On an Apple M1 Pro, a synthetic workload with 4,096 affected loads emitted 163,920 native bytes, down from 180,304 (9.1%). The native tests verify the encoding and the full 64-bit register result.
|
||||
- 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`.
|
||||
@@ -33,6 +56,8 @@ remains unsupported.
|
||||
- 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
|
||||
- Fixed the app's executable inspector so a late result from an earlier selection can no longer replace a newer one (#251). Each selection from the file picker, drag and drop or Finder Open With now takes a request number, and only the latest request may publish its report and status or clear the busy state. The previous report is cleared when a new file is chosen, and a failed inspection of the latest file is shown in red above its report. The read itself is unchanged: size checked before reading, balanced security-scoped access, nothing executed. `BetterXen --smoke-inspection-order`, run by `scripts/build-app.sh`, drives the model with an injected reader that blocks until the check releases each file, so the check (not timing) decides which read finishes first; it checks a stale success, a stale failure and a busy state held for the newer request, and all four checks fail without the change. Checked locally on Apple Silicon; not yet independently reviewed.
|
||||
- Startup reports now reject existing destinations before guest execution, surface journal write failures, and preserve late errors alongside signal termination.
|
||||
- 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.
|
||||
@@ -42,6 +67,9 @@ remains unsupported.
|
||||
- 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
|
||||
- Added opt-in `betterxen run --startup-report <path>` JSON diagnostics with the last observed startup stage, fixture verification outcome and preserved failure or termination detail (#255).
|
||||
- Added a `Native app build and smoke` CI job (#248). On the same native `macos-26` runner image and pinned Rust toolchain as the Rust checks, it runs `scripts/build-app.sh`, which builds the locked C ABI library and the Swift app together, bundles and ad-hoc signs `BetterXen.app`, and runs its `--smoke` check, so a Swift compile, link or smoke failure is designed to fail CI (implemented and verified locally; not yet shown on a CI run). `scripts/build-app.sh` also prints `file` and a single `otool -L` listing for the executable, fails if that listing fails or is empty, and fails if the executable links any library outside `/System/Library/` and `/usr/lib/`, naming bundle-relative (`@rpath`, `@executable_path`, `@loader_path`) entries separately (checked locally against stubbed failing, empty, bundle-relative and non-system listings). The job is an app build and smoke result; it runs no Metal fixture and is not GPU verification.
|
||||
- Added a CPU and loader coverage map (#154) with decoder inventory, native and shared execution paths, and test counts from a pinned Apple M5 run.
|
||||
- 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,
|
||||
|
||||
+6
-2
@@ -1,6 +1,10 @@
|
||||
# Contributing to BetterXen
|
||||
|
||||
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.
|
||||
BetterXen is hybrid-first Apple Silicon compatibility research built around an externally installed CrossOver, with a preserved but paused independent native implementation. Contributions should improve verified behavior rather than expand untested claims.
|
||||
|
||||
## Which work is active
|
||||
|
||||
The only active development track is the CrossOver-based hybrid architecture in [docs/roadmap.md](docs/roadmap.md). Planning is progressive: only the current milestone (Phase 1) has open issues; ideas for later phases are parked in the roadmap. Native research is paused, its backlog is closed and indexed in [docs/research/native-issue-archive.md](docs/research/native-issue-archive.md), and the few native issues still open only have assigned contributors with open pull requests. Do not start native work; if hybrid development needs a native component, file a focused hybrid issue. Pick an open issue in the current milestone and check its dependencies first. The engineering rules in `AGENTS.md` permit CrossOver, Wine-based infrastructure, Rosetta 2 and D3DMetal (subject to licensing) and allow evaluating DXMT, DXVK, VKD3D-Proton and MoltenVK. CrossOver is proprietary: do not bundle or redistribute any of it, and record the exact versions you test. Before adopting or copying any upstream code, verify its license and provenance and add it to the [upstream registry](docs/research/upstream-registry.md); projects built around leaked or unauthorized game builds are not a source of code. Use the issue templates (hybrid task, bug, research, performance, validation, documentation) and fill in the licensing and provenance section.
|
||||
|
||||
## Getting started
|
||||
|
||||
@@ -44,7 +48,7 @@ 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.
|
||||
- Describe what changes and why, link the issue you claimed with `Closes #<number>`, state which checks you actually ran, and disclose material AI assistance. Separate unverified work from supported behavior.
|
||||
- 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
+209
-8
@@ -2,6 +2,19 @@
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "betterxen"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"xenora-decoder",
|
||||
"xenora-import-gen",
|
||||
"xenora-isa",
|
||||
"xenora-loader",
|
||||
"xenora-metal",
|
||||
"xenora-ref",
|
||||
"xenora-shader",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.13.2"
|
||||
@@ -126,6 +139,24 @@ dependencies = [
|
||||
"objc2-foundation",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.107"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sha2"
|
||||
version = "0.10.9"
|
||||
@@ -137,12 +168,60 @@ dependencies = [
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "2.0.119"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "3.0.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thiserror"
|
||||
version = "2.0.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"
|
||||
dependencies = [
|
||||
"thiserror-impl",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thiserror-impl"
|
||||
version = "2.0.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "typenum"
|
||||
version = "1.20.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
|
||||
|
||||
[[package]]
|
||||
name = "version_check"
|
||||
version = "0.9.5"
|
||||
@@ -150,16 +229,132 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
|
||||
|
||||
[[package]]
|
||||
name = "betterxen"
|
||||
name = "victory-shader"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"xenora-decoder",
|
||||
"xenora-import-gen",
|
||||
"xenora-isa",
|
||||
"xenora-loader",
|
||||
"xenora-metal",
|
||||
"xenora-ref",
|
||||
"xenora-shader",
|
||||
"thiserror",
|
||||
"windows",
|
||||
"windows-sys",
|
||||
"zlib-rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows"
|
||||
version = "0.62.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"
|
||||
dependencies = [
|
||||
"windows-collections",
|
||||
"windows-core",
|
||||
"windows-future",
|
||||
"windows-numerics",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-collections"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"
|
||||
dependencies = [
|
||||
"windows-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-core"
|
||||
version = "0.62.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
|
||||
dependencies = [
|
||||
"windows-implement",
|
||||
"windows-interface",
|
||||
"windows-link",
|
||||
"windows-result",
|
||||
"windows-strings",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-future"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"
|
||||
dependencies = [
|
||||
"windows-core",
|
||||
"windows-link",
|
||||
"windows-threading",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-implement"
|
||||
version = "0.60.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-interface"
|
||||
version = "0.59.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-link"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
|
||||
|
||||
[[package]]
|
||||
name = "windows-numerics"
|
||||
version = "0.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26"
|
||||
dependencies = [
|
||||
"windows-core",
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-result"
|
||||
version = "0.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-strings"
|
||||
version = "0.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.61.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-threading"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -243,3 +438,9 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "xenora-texture"
|
||||
version = "0.1.0"
|
||||
|
||||
[[package]]
|
||||
name = "zlib-rs"
|
||||
version = "0.6.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "aa76918995d776d9dd34d371030be228d021137449771493d56e29f77e4148ac"
|
||||
@@ -1,62 +1,119 @@
|
||||
<div align="center">
|
||||
|
||||
# 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.
|
||||
**Hybrid-first Apple Silicon compatibility research built around CrossOver, with preserved independent native ARM64 and Metal research (paused).**
|
||||
|
||||
**Experimental Xbox Series X|S emulation research for Apple Silicon Macs.**
|
||||
[](https://github.com/MacosPorters/betterxen/actions/workflows/ci.yml)
|
||||
-1f6feb?logo=apple&logoColor=white)
|
||||

|
||||

|
||||

|
||||

|
||||
|
||||
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.
|
||||
**The paused native implementation described below uses no Wine, CrossOver, Rosetta or Vulkan runtime. The active hybrid direction intends to use CrossOver and Rosetta 2, subject to research and licensing review.**
|
||||
|
||||
**No Wine. No CrossOver. No Rosetta. No Vulkan runtime.**
|
||||
> [!IMPORTANT]
|
||||
> **Current direction.** BetterXen's only active development track is a CrossOver-based hybrid architecture: CrossOver (installed externally) as the compatibility foundation, with BetterXen providing whatever integration, configuration, diagnostics, benchmarking and optimization research shows is missing. This is the *intended* architecture, **not a verified Xbox compatibility stack**: no Xbox title has been shown to run through it, and CrossOver is not assumed to provide Xbox runtime compatibility. Work is at the research stage (Phase 1). Planning is progressive: only the current phase has open issues. The independent native implementation described below is **preserved but paused indefinitely**. See the [roadmap](docs/roadmap.md), [ADR 0005](docs/adr/0005-crossover-hybrid-direction.md), the [upstream research registry](docs/research/upstream-registry.md) and the [deferred native roadmap](docs/research/native-roadmap.md). The rewritten engineering rules are in [AGENTS.md](AGENTS.md).
|
||||
|
||||
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).
|
||||
</div>
|
||||
|
||||
BetterXen is a community-maintained, open-source project written primarily in Rust. Its native research implementation (paused) 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. The host runs as ARM64 code; the x86-64 code being emulated is guest data.
|
||||
|
||||
> [!IMPORTANT]
|
||||
> **BetterXen is experimental.** Verified work is restricted to independently authored synthetic programs and shaders. Authentic Xbox executable loading, system-service compatibility and commercial game execution are **not supported**. Progress is measured by reproducible tests, not by estimated game compatibility percentages. See the [current limitations](#current-limitations).
|
||||
|
||||
> [!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)
|
||||
---
|
||||
|
||||
## How it fits together
|
||||
|
||||
One guest program travels through three native subsystems. Every stage is checked against an independently derived expectation.
|
||||
|
||||
```mermaid
|
||||
%%{init: {'theme':'base','themeVariables':{'fontFamily':'system-ui, sans-serif','lineColor':'#6e7781'}}}%%
|
||||
flowchart LR
|
||||
A["Original PE32+<br/>test program"]:::guest --> B["Loader<br/>relocations, TLS, imports"]:::guest
|
||||
B --> C["x86-64 interpreter<br/>+ ARM64 translator"]:::cpu
|
||||
C --> D["Typed runtime<br/>services"]:::cpu
|
||||
D --> E["Guest graphics<br/>commands"]:::gpu
|
||||
S["Original gfx1030<br/>shader bytes"]:::shader --> T["RDNA 2 decoder<br/>+ validated IR"]:::shader --> U["Metal Shading<br/>Language"]:::shader
|
||||
E --> M["Native Metal<br/>pipelines"]:::gpu
|
||||
U --> M
|
||||
M --> G["Apple Silicon GPU<br/>+ readback"]:::gpu
|
||||
G --> V{"Matches the<br/>independent<br/>CPU reference?"}:::check
|
||||
S -.-> R["Independent<br/>CPU reference"]:::check -.-> V
|
||||
|
||||
classDef guest fill:#ddf4ff,stroke:#0969da,color:#0a3069
|
||||
classDef cpu fill:#dafbe1,stroke:#1a7f37,color:#0f5323
|
||||
classDef shader fill:#fbefff,stroke:#8250df,color:#512a97
|
||||
classDef gpu fill:#fff8c5,stroke:#9a6700,color:#4d2d00
|
||||
classDef check fill:#ffebe9,stroke:#cf222e,color:#82071e
|
||||
```
|
||||
|
||||
Legend: 🟦 guest loading · 🟩 guest CPU and services · 🟪 shader translation · 🟨 native Metal · 🟥 independent verification.
|
||||
|
||||
---
|
||||
|
||||
## What works today?
|
||||
## Roadmap
|
||||
|
||||
BetterXen has progressed from executing individual x86-64 instructions to running original PE32+ guest programs that interact with translated GPU workloads on Apple Silicon.
|
||||
The active plan is the [roadmap](docs/roadmap.md): **Phase 1 — CrossOver Research, Feasibility and Baseline** is the only active phase, and later phases are provisional and will be defined from its findings. The current issues are in the [Phase 1 milestone](https://github.com/MacosPorters/betterxen/milestone/9). The native implementation's six phases and the X1 to X25 capability map are archived in [docs/archive/readme-native-milestones.md](docs/archive/readme-native-milestones.md) and the [native-first plan](docs/archive/development-phases-native-first.md). Native work is paused indefinitely and resumes only after an explicit maintainer decision.
|
||||
|
||||
The latest verified milestones include **translated gfx1030 vertex and pixel shaders executing through native Apple Metal**, the native Metal **blend pass** (`NativeCompute::render_blend`) and **indexed triangle draws** (`NativeCompute::render_indexed`) into offscreen targets, with rendered pixels compared against independently calculated reference results.
|
||||
|
||||
### Development milestones
|
||||
|
||||
| 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 | Translated image instructions are still planned; upload, readback and decode of BC compressed formats is implemented (see [Texture support](#texture-support)) | Planned |
|
||||
| X11 — Graphics pipeline | Bounded multi-draw passes into offscreen RGBA8 targets: translated vertex and pixel stages, indexed triangle draws, colour write masks and blend state | Implemented |
|
||||
| X12 — Wave execution | Expand Wave32/Wave64 semantics, divergent control flow, cross-lane operations, LDS and barriers | Planned |
|
||||
| X13 — Advanced shaders | Mesh, geometry and additional compute shader capabilities with verified Metal execution | Planned |
|
||||
| X14 — CPU recompilation | Native ARM64 dynamic recompilation of supported x86-64 instructions in synthetic fixtures | Implemented subset |
|
||||
| X15 — Executable compatibility | Static PE inspection reports sections, relocations, thread-local storage (TLS) callbacks, imports and entry-point instructions | Static probe implemented |
|
||||
| X16 — Guest memory and threading | Virtual memory mapping, thread scheduling, synchronization primitives and atomic operations | Implemented subset |
|
||||
| X17 — System services | Implement a tested subset of Xbox-compatible runtime APIs, memory services, filesystem access and application lifecycle | Implemented subset |
|
||||
| X18 — Graphics API translation | Translate supported Xbox graphics commands, resource descriptors, command queues, barriers and fences into Metal operations | Planned |
|
||||
| X19 — Advanced GPU features | Indirect rendering, asynchronous compute, additional texture formats and ray-tracing compatibility research | Planned |
|
||||
| X20 — Integrated guest runtime | Connect CPU recompilation, executable loading, system services and graphics translation into one persistent runtime | Planned |
|
||||
| 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 |
|
||||
|
||||
**Roadmap note:** X10–X25 are proposed engineering milestones, not completed implementations or a guaranteed sequence. Follow the [BetterXen development phases](docs/development-phases.md) for the current work order and existing issue/PR dependencies. 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.
|
||||
|
||||
---
|
||||
|
||||
## Repository at a glance
|
||||
|
||||
Counts below come from the generated registries and were read from the repository, not measured on new runs. They describe synthetic fixtures only.
|
||||
|
||||
| Area | Where | What exists today |
|
||||
| --- | --- | --- |
|
||||
| Guest CPU | `crates/loader` | A generated x86-64 decoder and interpreter, plus a native ARM64 dynamic binary translator (DBT) for a bounded subset. The instruction registry declares 213 operations, 403 forms and 498 opcode slots; 93 operations have at least one form lowered to ARM64 and the rest run through shared interpreter semantics. See the [instruction registry](docs/cpu/instruction-registry.md). |
|
||||
| Executable loading | `crates/loader` | PE32+ loading, relocations, thread-local storage, import binding and a static inspection report. |
|
||||
| Runtime services | `crates/loader`, `crates/import-gen` | A typed service registry: 47 declared services (7 implemented, 37 partial, 3 stubs), all exercised through guest dispatch, none independently accepted. See the [registry](docs/runtime/registry.md) and [generated coverage](docs/runtime/services.md). Guest threads run on a deterministic scheduler on one host thread. |
|
||||
| Shader ISA | `crates/isa`, `crates/decoder`, `crates/shader`, `crates/ref` | The RDNA 2 (gfx1030) instruction snapshot lists 1,465 forms; 189 are decoder-supported, 185 are lowered to Metal Shading Language, and 18 are Metal-verified on fixtures. See the [semantic coverage](docs/shaders/semantic-coverage.md). An independent CPU reference checks GPU output. |
|
||||
| Metal backend | `crates/metal` | Native compute, blend, indexed-draw, depth and sampled-texture passes, with Metal API and shader validation. |
|
||||
| Textures | `crates/texture` | Upload, readback, BC1 to BC7 decoding and sampler code. |
|
||||
| Application | `app`, `crates/ffi` | A Swift macOS app over a versioned C interface: frame loop, interactive input, persistent resources, audio and a sandboxed virtual filesystem, all against synthetic guests. |
|
||||
| Test and tooling | `tests`, `fuzz`, `benchmarks`, `scripts` | Original guest programs, independent validation, fuzz targets (CPU decode, PE parse, instruction streams, fixtures, reference, runtime services), mutation testing, correctness-gated benchmarks, and audit scripts for claims, status tables and dependency direction. |
|
||||
|
||||
The `betterxen` command-line tool provides `info`, `demo`, `inspect <pe>`, `probe --pe <path> --mode static`, `run`, `imports` and `shaders`. Run `cargo run -p betterxen` with no arguments to see its usage.
|
||||
|
||||
|
||||
### Where the numbers stand
|
||||
|
||||
Counts come from the repository's generated registries at this revision. They describe synthetic fixtures only and are not compatibility percentages.
|
||||
|
||||
```mermaid
|
||||
%%{init: {'theme':'base','themeVariables':{'pie1':'#1a7f37','pie2':'#d0d7de','pieTitleTextSize':'16px','pieStrokeColor':'#ffffff','pieOuterStrokeColor':'#ffffff','fontFamily':'system-ui, sans-serif'}}}%%
|
||||
pie showData title Guest CPU — 213 declared x86-64 operations
|
||||
"Lowered to ARM64 (at least one native form)" : 93
|
||||
"Shared interpreter semantics only" : 120
|
||||
```
|
||||
|
||||
```mermaid
|
||||
%%{init: {'theme':'base','themeVariables':{'pie1':'#1a7f37','pie2':'#d4a72c','pie3':'#cf222e','pieStrokeColor':'#ffffff','pieOuterStrokeColor':'#ffffff','fontFamily':'system-ui, sans-serif'}}}%%
|
||||
pie showData title Runtime services — 47 declared, none independently accepted
|
||||
"Implemented" : 7
|
||||
"Partial" : 37
|
||||
"Stub" : 3
|
||||
```
|
||||
|
||||
```mermaid
|
||||
%%{init: {'theme':'base','themeVariables':{'xyChart':{'plotColorPalette':'#8250df'}}}}%%
|
||||
xychart-beta
|
||||
title "gfx1030 instruction forms by stage (1,465 identified)"
|
||||
x-axis ["Decoder-supported", "Lowered to MSL", "Metal-verified"]
|
||||
y-axis "Forms" 0 --> 200
|
||||
bar [189, 185, 18]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Native graphics translation
|
||||
|
||||
BetterXen's graphics pipeline translates a supported subset of AMD RDNA 2 instructions into Metal Shading Language.
|
||||
@@ -177,9 +234,9 @@ Implemented and tested functionality includes:
|
||||
- Edge-block and transparency tests.
|
||||
- Invalid descriptor and bounds rejection.
|
||||
|
||||
**Translated texture-sampling instructions are not yet implemented.**
|
||||
**Translated texture sampling covers one instruction and one sampler mode.** A guest draw with the translated `image_sample_lz` pixel stage and a point/clamp sampler matched the software reference and hand-derived images on a local Apple M5 Pro run (one-level RGBA8 and an 8×8 BC1 texture). Other image instructions, filtering modes and formats are not implemented, and this is local verification, not independent acceptance.
|
||||
|
||||
The existing texture readback path uses authored Metal kernels. It should not be confused with executing arbitrary RDNA2 texture-fetch instructions.
|
||||
The texture upload and readback paths use authored Metal kernels. They should not be confused with executing arbitrary RDNA2 texture-fetch instructions.
|
||||
|
||||
Xbox-specific texture layouts and additional compression formats require further research and validation.
|
||||
|
||||
@@ -230,13 +287,22 @@ flowchart TD
|
||||
L --> M
|
||||
K --> M
|
||||
end
|
||||
|
||||
classDef guestNode fill:#dafbe1,stroke:#1a7f37,color:#0f5323
|
||||
classDef shaderNode fill:#fbefff,stroke:#8250df,color:#512a97
|
||||
classDef metalNode fill:#fff8c5,stroke:#9a6700,color:#4d2d00
|
||||
classDef checkNode fill:#ffebe9,stroke:#cf222e,color:#82071e
|
||||
class A,B,C,D guestNode
|
||||
class E,F,G,H shaderNode
|
||||
class I,J,K metalNode
|
||||
class L,M checkNode
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
The project does not currently provide a general-purpose x86-64 dynamic recompiler or a complete Xbox operating-system implementation.
|
||||
The native ARM64 dynamic recompiler covers a bounded subset of x86-64 instructions; the rest run through the shared interpreter semantics (see the [CPU coverage map](docs/testing/cpu-coverage.md) once it lands). The project does not provide a complete Xbox operating-system implementation.
|
||||
|
||||
See [Interface Contracts](docs/interfaces.md) for the documented execution and resource boundaries.
|
||||
|
||||
@@ -254,8 +320,8 @@ The following remain unsupported or incomplete:
|
||||
| Executable loader | General relocations, TLS, DLL initialization and authentic Xbox startup |
|
||||
| Xbox runtime | Console-specific services, system APIs, filesystem and application lifecycle |
|
||||
| RDNA2 shaders | General control flow, broader instructions, Wave64, cross-lane operations and mesh stages |
|
||||
| Graphics | Translated texture sampling and broader resource binding |
|
||||
| Textures | Authentic Xbox memory layouts and translated sampling |
|
||||
| Graphics | Broader translated texture sampling (one instruction and sampler mode exist) and broader resource binding |
|
||||
| Textures | Authentic Xbox memory layouts and broader translated sampling |
|
||||
| Performance | Production-scale workloads, CPU/GPU profiling and optimized execution |
|
||||
| Game compatibility | No demonstrated execution of commercial Xbox titles |
|
||||
|
||||
@@ -351,9 +417,21 @@ Testing distinguishes between:
|
||||
|
||||
Compiling a shader is not equivalent to proving its GPU output is correct.
|
||||
|
||||
### Contributing
|
||||
|
||||
Contributions are welcome, and several people and coding agents work in this repository at once. To avoid duplicated work:
|
||||
|
||||
1. Read every comment on an issue and check for open pull requests that link it.
|
||||
2. Claim the issue with a plain reply (for example "I'm taking this. Plan: ...") before you edit anything. The earliest live claim wins, and a claim is stale only after about seven days without a pull request.
|
||||
3. Stay inside the files the issue lists, and put `Closes #<n>` in the pull request description.
|
||||
4. Sign off every commit (DCO) and use only public documentation and original code. Anyone who has seen leaked or confidential Xbox material must not contribute.
|
||||
5. Update `CHANGELOG.md` for meaningful changes. Changes to `main` need maintainer review through [CODEOWNERS](.github/CODEOWNERS).
|
||||
|
||||
See [CONTRIBUTING.md](CONTRIBUTING.md), [docs/legal.md](docs/legal.md) and the [documentation index](docs/README.md) for the full rules.
|
||||
|
||||
### Where the work is heading
|
||||
|
||||
See the [roadmap table](#development-milestones) for proposed milestones, and the [changelog](CHANGELOG.md) for the current unreleased additions, such as the native blend pass, indexed draws and the depth pass. The remaining research steps are the outstanding items in [current limitations](#current-limitations).
|
||||
See the [roadmap](docs/roadmap.md) for the current phase and the [changelog](CHANGELOG.md) for unreleased additions. The paused native implementation's open research items are listed under [current limitations](#current-limitations).
|
||||
|
||||
---
|
||||
|
||||
@@ -367,6 +445,6 @@ BetterXen 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.
|
||||
BetterXen is an independent open-source project and is not affiliated with Microsoft, Xbox, any game publisher or Apple.
|
||||
|
||||
---
|
||||
@@ -15,3 +15,7 @@ Cargo resolves the Rust packages from crates.io at the source checksums in [Carg
|
||||
[LLVM 23.1.6](https://github.com/llvm/llvm-project/tree/5b10d2d74929eae78912771222c9855af97496f4) is used as an external fixture tool under Apache-2.0 WITH LLVM-exception. Xcode and Metal are separate Apple tools under Apple's license terms.
|
||||
|
||||
The [isolated fuzz workspace](fuzz/Cargo.lock) resolves developer-only dependencies, including [libfuzzer-sys](https://github.com/rust-fuzz/libfuzzer/tree/719e4efb9b8857ebaa782ae59376c8cbb78fed0f). See the [fuzz dependency inventory](docs/licenses.md#fuzz-development-dependencies) for locked revisions and selected licenses.
|
||||
|
||||
`crates/victory-shader` is vendored from skakwy's [victory-mac](https://github.com/skakwy/victory-mac) (GPL-3.0; authors and provenance in [its UPSTREAM.md](crates/victory-shader/UPSTREAM.md)); it contains opcode names generated from Mesa (MIT, Copyright (c) 2018 Valve Corporation) with the notice kept in `src/gfx10/opcodes.rs`. Its Rust dependencies are `thiserror` (MIT OR Apache-2.0), `zlib-rs` (Zlib), and on Windows targets `windows`/`windows-sys` (MIT OR Apache-2.0); versions are in `Cargo.lock`.
|
||||
|
||||
Microsoft's DirectX Shader Compiler (release v1.9.2609, `dxc_2026_09_29.zip`; University of Illinois/NCSA licence with MIT components per its `LICENSE-LLVM.txt`, `LICENCE-MIT.txt` and `LICENSE-MS.txt`) is used as an external tool to compile the HLSL probes in `workloads/d3d12-wave-probe/hlsl/`; it is not vendored or distributed.
|
||||
@@ -638,13 +638,65 @@ final class InspectionModel: ObservableObject {
|
||||
@Published var report = ""
|
||||
@Published var status: Int32 = Int32(XENORA_OK)
|
||||
@Published var busy = false
|
||||
@Published var importing = false
|
||||
/// Why the last file selection could not be used, shown until the next selection.
|
||||
@Published var selectionError: String?
|
||||
|
||||
/// Called when a window is about to show the read-only file importer, from its
|
||||
/// button or File > Open Executable…. Each window presents its own importer.
|
||||
func requestImport() {
|
||||
selectionError = nil
|
||||
}
|
||||
|
||||
/// Handles the importer's completion. A cancelled picker is not a failure.
|
||||
func importFinished(_ result: Result<URL, Error>) {
|
||||
switch result {
|
||||
case .success(let url):
|
||||
inspect(url)
|
||||
case .failure(let error):
|
||||
if let cocoa = error as? CocoaError, cocoa.code == .userCancelled {
|
||||
return
|
||||
}
|
||||
selectionError = "The selected file could not be opened: \(error.localizedDescription)"
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads and reports one file off the main thread. Replaceable only for the
|
||||
/// `--smoke-inspection-order` check.
|
||||
private let reader: @Sendable (URL) -> (Int32, String)
|
||||
/// Number of the latest `inspect` call. Only that call may publish a result.
|
||||
private var latestRequest: UInt64 = 0
|
||||
/// Reads that have finished, whether their result was published or discarded.
|
||||
/// `--smoke-inspection-order` waits on it instead of on a fixed delay.
|
||||
private(set) var finishedReads: UInt64 = 0
|
||||
|
||||
init(reader: @escaping @Sendable (URL) -> (Int32, String) = InspectionModel.run) {
|
||||
self.reader = reader
|
||||
}
|
||||
|
||||
var failed: Bool { !busy && fileName != nil && status != Int32(XENORA_OK) }
|
||||
|
||||
func inspect(_ url: URL) {
|
||||
latestRequest &+= 1
|
||||
let request = latestRequest
|
||||
selectionError = nil
|
||||
fileName = url.lastPathComponent
|
||||
report = ""
|
||||
status = Int32(XENORA_OK)
|
||||
busy = true
|
||||
let reader = reader
|
||||
Task {
|
||||
let (newStatus, newReport) = await Task.detached { InspectionModel.run(url) }.value
|
||||
// The read blocks on file I/O (and, in `--smoke-inspection-order`, on
|
||||
// its gate), so it runs on a Dispatch queue instead of occupying a
|
||||
// Swift concurrency worker that other tasks may need.
|
||||
let (newStatus, newReport) = await withCheckedContinuation { continuation in
|
||||
DispatchQueue.global(qos: .userInitiated).async {
|
||||
continuation.resume(returning: reader(url))
|
||||
}
|
||||
}
|
||||
finishedReads &+= 1
|
||||
// A newer selection owns the published state, including `busy`;
|
||||
// an older read that finishes late is discarded.
|
||||
guard request == latestRequest else { return }
|
||||
status = newStatus
|
||||
report = newReport
|
||||
busy = false
|
||||
@@ -685,17 +737,51 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens the file importer of the focused window. Absent when no window can
|
||||
/// present it, which disables File > Open Executable….
|
||||
struct OpenExecutableKey: FocusedValueKey {
|
||||
typealias Value = () -> Void
|
||||
}
|
||||
|
||||
extension FocusedValues {
|
||||
var openExecutable: OpenExecutableKey.Value? {
|
||||
get { self[OpenExecutableKey.self] }
|
||||
set { self[OpenExecutableKey.self] = newValue }
|
||||
}
|
||||
}
|
||||
|
||||
/// File > Open Executable… (Command-O), routed to the focused window's importer.
|
||||
struct OpenExecutableCommand: Commands {
|
||||
@FocusedValue(\.openExecutable) private var openExecutable
|
||||
|
||||
var body: some Commands {
|
||||
CommandGroup(after: .newItem) {
|
||||
Button("Open Executable…") { openExecutable?() }
|
||||
.keyboardShortcut("o")
|
||||
.disabled(openExecutable == nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct InspectorView: View {
|
||||
@ObservedObject var model: InspectionModel
|
||||
let openImporter: () -> Void
|
||||
|
||||
var body: some View {
|
||||
Section("Executable inspection (read-only)") {
|
||||
HStack {
|
||||
Button("Open Executable…") { model.importing = true }
|
||||
Button("Open Executable…") { openImporter() }
|
||||
Text("or drop a file on this window").foregroundStyle(.secondary)
|
||||
}
|
||||
if let error = model.selectionError {
|
||||
Text(error).foregroundStyle(.red)
|
||||
}
|
||||
if let name = model.fileName {
|
||||
LabeledContent("File", value: model.busy ? "\(name) (inspecting…)" : name)
|
||||
if model.failed {
|
||||
Text("Inspection of \(name) failed (status \(model.status)).")
|
||||
.foregroundStyle(.red)
|
||||
}
|
||||
ScrollView {
|
||||
Text(model.report)
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
@@ -716,12 +802,19 @@ struct ContentView: View {
|
||||
@ObservedObject var model: FrameModel
|
||||
@ObservedObject var loop: FrameLoopModel
|
||||
@ObservedObject var inspection = InspectionModel.shared
|
||||
/// This window's importer. Kept per window so only the window that asked shows it.
|
||||
@State private var importing = false
|
||||
private var frame: GuestFrame? { model.frame }
|
||||
private var running: Bool { model.running }
|
||||
|
||||
private func openImporter() {
|
||||
inspection.requestImport()
|
||||
importing = true
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
Form {
|
||||
InspectorView(model: inspection)
|
||||
InspectorView(model: inspection, openImporter: openImporter)
|
||||
Section("Guest display") {
|
||||
if let image = frame?.image {
|
||||
Image(decorative: image, scale: 1)
|
||||
@@ -822,8 +915,8 @@ struct ContentView: View {
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
.formStyle(.grouped)
|
||||
.fileImporter(isPresented: $inspection.importing, allowedContentTypes: [.item]) { result in
|
||||
if case .success(let url) = result { inspection.inspect(url) }
|
||||
.fileImporter(isPresented: $importing, allowedContentTypes: [.item]) { result in
|
||||
inspection.importFinished(result)
|
||||
}
|
||||
.dropDestination(for: URL.self) { urls, _ in
|
||||
guard let url = urls.first, url.isFileURL else { return false }
|
||||
@@ -831,6 +924,7 @@ struct ContentView: View {
|
||||
return true
|
||||
}
|
||||
.frame(minWidth: 520, minHeight: 680)
|
||||
.focusedSceneValue(\.openExecutable, openImporter)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -841,6 +935,7 @@ struct BetterXenApp: App {
|
||||
|
||||
var body: some Scene {
|
||||
WindowGroup("BetterXen") { ContentView(model: model, loop: loop) }
|
||||
.commands { OpenExecutableCommand() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1009,6 +1104,118 @@ if CommandLine.arguments.contains("--smoke-frame") {
|
||||
exit(frame.status == XENORA_OK ? 0 : 1)
|
||||
}
|
||||
|
||||
// `--smoke-inspection-order` checks that only the latest selection publishes an
|
||||
// inspection result. Files are never read: an injected reader blocks until the check
|
||||
// releases that file, so the check, not timing, decides which read finishes first.
|
||||
// It needs no GPU.
|
||||
if CommandLine.arguments.contains("--smoke-inspection-order") {
|
||||
final class ReadGates: @unchecked Sendable {
|
||||
private let lock = NSLock()
|
||||
private var gates: [String: DispatchSemaphore] = [:]
|
||||
func gate(_ name: String) -> DispatchSemaphore {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
if let gate = gates[name] { return gate }
|
||||
let gate = DispatchSemaphore(value: 0)
|
||||
gates[name] = gate
|
||||
return gate
|
||||
}
|
||||
func release(_ name: String) { gate(name).signal() }
|
||||
}
|
||||
let gates = ReadGates()
|
||||
// "<scenario>-<a|b>-<ok|fail>"; a gate that is never released times out
|
||||
// instead of hanging, and the check then fails on its own deadline.
|
||||
let reader: @Sendable (URL) -> (Int32, String) = { url in
|
||||
let name = url.lastPathComponent
|
||||
_ = gates.gate(name).wait(timeout: .now() + 10)
|
||||
let status = name.hasSuffix("-ok") ? Int32(XENORA_OK) : Int32(XENORA_INVALID_ARGUMENT)
|
||||
return (status, "report \(name)")
|
||||
}
|
||||
func file(_ name: String) -> URL { URL(fileURLWithPath: "/nonexistent/\(name)") }
|
||||
|
||||
Task { @MainActor in
|
||||
var failures: [String] = []
|
||||
// Waits for the model to finish `count` reads. The deadline only bounds the
|
||||
// check; the order of completions is set by releasing gates.
|
||||
@MainActor func settle(_ model: InspectionModel, _ count: UInt64, _ label: String) async -> Bool {
|
||||
let deadline = Date().addingTimeInterval(5)
|
||||
while model.finishedReads < count {
|
||||
if Date() > deadline {
|
||||
failures.append("\(label): read \(count) did not finish")
|
||||
return false
|
||||
}
|
||||
try? await Task.sleep(nanoseconds: 2_000_000)
|
||||
}
|
||||
return true
|
||||
}
|
||||
@MainActor func expect(_ model: InspectionModel, _ name: String, busy: Bool, report: String, ok: Bool, _ label: String) {
|
||||
let actual = "file=\(model.fileName ?? "-") busy=\(model.busy) status=\(model.status) report=\(model.report)"
|
||||
if model.fileName != name || model.busy != busy || model.report != report
|
||||
|| (model.status == Int32(XENORA_OK)) != ok {
|
||||
failures.append("\(label): \(actual)")
|
||||
}
|
||||
}
|
||||
// The newer read finishes first; the older one finishes afterwards and must
|
||||
// change nothing, whatever its outcome.
|
||||
for (scenario, first, second, ok) in [("s1", "a-ok", "b-ok", true), ("s2", "a-fail", "b-ok", true),
|
||||
("s3", "a-ok", "b-fail", false)] {
|
||||
let (older, newer) = ("\(scenario)-\(first)", "\(scenario)-\(second)")
|
||||
let model = InspectionModel(reader: reader)
|
||||
model.inspect(file(older))
|
||||
model.inspect(file(newer))
|
||||
gates.release(newer)
|
||||
if await settle(model, 1, "\(older) then \(newer)") {
|
||||
expect(model, newer, busy: false, report: "report \(newer)", ok: ok, "\(newer) finished")
|
||||
}
|
||||
gates.release(older)
|
||||
if await settle(model, 2, "\(older) then \(newer)") {
|
||||
expect(model, newer, busy: false, report: "report \(newer)", ok: ok, "stale \(older) finished")
|
||||
}
|
||||
}
|
||||
// The older read finishes first and must not clear the newer request's busy state.
|
||||
let model = InspectionModel(reader: reader)
|
||||
model.inspect(file("s4-a-ok"))
|
||||
model.inspect(file("s4-b-fail"))
|
||||
gates.release("s4-a-ok")
|
||||
if await settle(model, 1, "s4") {
|
||||
expect(model, "s4-b-fail", busy: true, report: "", ok: true, "stale s4-a-ok finished first")
|
||||
}
|
||||
gates.release("s4-b-fail")
|
||||
if await settle(model, 2, "s4") {
|
||||
expect(model, "s4-b-fail", busy: false, report: "report s4-b-fail", ok: false, "s4-b-fail finished")
|
||||
}
|
||||
for failure in failures { print("smoke-inspection-order: FAILED \(failure)") }
|
||||
print("smoke-inspection-order: \(failures.isEmpty ? "ok" : "\(failures.count) failed")")
|
||||
exit(failures.isEmpty ? 0 : 1)
|
||||
}
|
||||
dispatchMain()
|
||||
}
|
||||
|
||||
// `--smoke-import-result` checks how a file-importer result reaches the inspector:
|
||||
// a cancelled picker shows nothing, a failure is shown, and a new selection clears it.
|
||||
// No file is opened or read.
|
||||
if CommandLine.arguments.contains("--smoke-import-result") {
|
||||
let ok = MainActor.assumeIsolated { () -> Bool in
|
||||
var failures: [String] = []
|
||||
let model = InspectionModel()
|
||||
model.importFinished(.failure(CocoaError(.userCancelled)))
|
||||
if model.selectionError != nil || model.fileName != nil { failures.append("cancel shows a message") }
|
||||
model.importFinished(.failure(CocoaError(.fileReadNoPermission)))
|
||||
if model.selectionError == nil || model.fileName != nil { failures.append("failure is not shown") }
|
||||
model.requestImport()
|
||||
if model.selectionError != nil { failures.append("reopening keeps the old message") }
|
||||
model.importFinished(.failure(CocoaError(.fileReadNoPermission)))
|
||||
model.inspect(URL(fileURLWithPath: "/nonexistent/import-result-check"))
|
||||
if model.selectionError != nil || model.fileName != "import-result-check" {
|
||||
failures.append("a new selection keeps the old message")
|
||||
}
|
||||
for failure in failures { print("smoke-import-result: FAILED \(failure)") }
|
||||
return failures.isEmpty
|
||||
}
|
||||
print("smoke-import-result: \(ok ? "ok" : "failed")")
|
||||
exit(ok ? 0 : 1)
|
||||
}
|
||||
|
||||
// `--smoke` prints the probe and exits without opening a window, for scripts and CI.
|
||||
if CommandLine.arguments.contains("--smoke") {
|
||||
let probe = RuntimeProbe.run()
|
||||
|
||||
+120
-17
@@ -2,10 +2,10 @@
|
||||
|
||||
use std::error::Error;
|
||||
use std::ffi::OsString;
|
||||
use std::fs::{self, File};
|
||||
use std::fs::{self, File, OpenOptions};
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, ExitCode, Stdio};
|
||||
use std::process::{Child, Command, ExitCode, Stdio};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
@@ -16,6 +16,10 @@ use xenora_loader::{
|
||||
use xenora_metal::NativeCompute;
|
||||
use xenora_shader::{Architecture, PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics};
|
||||
|
||||
#[path = "startup_report.rs"]
|
||||
mod startup_report;
|
||||
use startup_report::{Events, JOURNAL_ERROR_EXIT, Journal, Termination, WATCHDOG_EXIT};
|
||||
|
||||
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);
|
||||
@@ -27,7 +31,7 @@ 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>]";
|
||||
const USAGE: &str = "usage: betterxen run --pe <trusted-fixture> --experimental [--trace] [--metal-hud] [--max-steps <1..=10000>] [--startup-report <path>]";
|
||||
|
||||
struct Options {
|
||||
path: PathBuf,
|
||||
@@ -35,6 +39,8 @@ struct Options {
|
||||
worker: bool,
|
||||
trace: bool,
|
||||
hud: bool,
|
||||
report: Option<PathBuf>,
|
||||
journal: Option<PathBuf>,
|
||||
}
|
||||
|
||||
impl Options {
|
||||
@@ -42,6 +48,8 @@ impl Options {
|
||||
let mut args = args.into_iter();
|
||||
let mut path = None;
|
||||
let mut max_steps = None;
|
||||
let mut report = None;
|
||||
let mut journal = None;
|
||||
let (mut experimental, mut trace, mut hud, mut worker) = (false, false, false, false);
|
||||
while let Some(arg) = args.next() {
|
||||
match arg.to_str() {
|
||||
@@ -56,6 +64,16 @@ impl Options {
|
||||
.ok_or("--max-steps must be in 1..=10000")?,
|
||||
);
|
||||
}
|
||||
Some("--startup-report") if report.is_none() => {
|
||||
report = Some(PathBuf::from(
|
||||
args.next().ok_or("missing --startup-report path")?,
|
||||
));
|
||||
}
|
||||
Some("--startup-journal") if journal.is_none() => {
|
||||
journal = Some(PathBuf::from(
|
||||
args.next().ok_or("missing worker journal path")?,
|
||||
));
|
||||
}
|
||||
Some("--experimental") if !experimental => experimental = true,
|
||||
Some("--trace") if !trace => trace = true,
|
||||
Some("--metal-hud") if !hud => hud = true,
|
||||
@@ -66,12 +84,17 @@ impl Options {
|
||||
if !experimental {
|
||||
return Err("run requires --experimental".into());
|
||||
}
|
||||
if (worker && report.is_some()) || (!worker && journal.is_some()) {
|
||||
return Err("invalid startup report option for this process".into());
|
||||
}
|
||||
Ok(Self {
|
||||
path: path.ok_or("missing --pe path")?,
|
||||
max_steps: max_steps.unwrap_or(DEFAULT_STEPS),
|
||||
worker,
|
||||
trace,
|
||||
hud,
|
||||
report,
|
||||
journal,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -85,7 +108,7 @@ pub fn command(args: impl IntoIterator<Item = OsString>) -> ExitCode {
|
||||
}
|
||||
};
|
||||
let result = if options.worker {
|
||||
run_worker(&options).map(|()| ExitCode::SUCCESS)
|
||||
worker_command(&options)
|
||||
} else {
|
||||
launch_worker(&options)
|
||||
};
|
||||
@@ -99,8 +122,26 @@ pub fn command(args: impl IntoIterator<Item = OsString>) -> ExitCode {
|
||||
}
|
||||
|
||||
fn launch_worker(options: &Options) -> Result<ExitCode, Box<dyn Error>> {
|
||||
let journal = options
|
||||
.report
|
||||
.as_ref()
|
||||
.map(|_| Journal::create())
|
||||
.transpose()?;
|
||||
let executable = std::env::current_exe()?;
|
||||
let destination = options
|
||||
.report
|
||||
.as_ref()
|
||||
.map(|path| {
|
||||
OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(path)
|
||||
.map_err(|error| format!("could not create startup report: {error}"))
|
||||
})
|
||||
.transpose()?;
|
||||
let started = Instant::now();
|
||||
let mut child = Command::new(std::env::current_exe()?)
|
||||
let mut command = Command::new(executable);
|
||||
command
|
||||
.args([
|
||||
"run",
|
||||
"--experimental",
|
||||
@@ -112,29 +153,73 @@ fn launch_worker(options: &Options) -> Result<ExitCode, Box<dyn Error>> {
|
||||
.arg(options.max_steps.to_string())
|
||||
.arg("--pe")
|
||||
.arg(&options.path)
|
||||
.stdin(Stdio::null())
|
||||
.spawn()?;
|
||||
.stdin(Stdio::null());
|
||||
if let Some(journal) = &journal {
|
||||
command.arg("--startup-journal").arg(journal.path());
|
||||
}
|
||||
let termination = command
|
||||
.spawn()
|
||||
.and_then(|child| supervise(child, started, WALL_LIMIT));
|
||||
if let (Some(journal), Some(destination)) = (&journal, destination)
|
||||
&& let Err(error) = journal.finish(destination, &termination)
|
||||
{
|
||||
eprintln!("could not write startup report: {error}");
|
||||
if matches!(&termination, Ok(Termination::Exited(status)) if status.success()) {
|
||||
return Ok(ExitCode::FAILURE);
|
||||
}
|
||||
}
|
||||
match termination? {
|
||||
Termination::Exited(status) => match status.code() {
|
||||
Some(code) => Ok(ExitCode::from(u8::try_from(code)?)),
|
||||
None => Err(format!("worker terminated: {status}").into()),
|
||||
},
|
||||
Termination::Deadline => {
|
||||
Err("experimental worker exceeded its 15 second wall deadline".into())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn supervise(mut child: Child, started: Instant, limit: Duration) -> std::io::Result<Termination> {
|
||||
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 => {
|
||||
Ok(Some(status)) => return Ok(Termination::Exited(status)),
|
||||
Ok(None) if started.elapsed() < 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());
|
||||
return Ok(Termination::Deadline);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn worker_command(options: &Options) -> Result<ExitCode, Box<dyn Error>> {
|
||||
let mut events = match options.journal.as_deref().map(Events::open).transpose() {
|
||||
Ok(events) => events,
|
||||
Err(error) => {
|
||||
eprintln!("could not open startup journal: {error}");
|
||||
return Ok(ExitCode::from(JOURNAL_ERROR_EXIT));
|
||||
}
|
||||
};
|
||||
let result = run_worker(options, events.as_mut());
|
||||
if let Some(events) = events.as_mut() {
|
||||
if let Err(error) = &result {
|
||||
events.failure(error.as_ref());
|
||||
}
|
||||
if let Some(error) = events.write_error() {
|
||||
if let Err(error) = result {
|
||||
eprintln!("run failed: {error}");
|
||||
}
|
||||
eprintln!("could not write startup journal: {error}");
|
||||
return Ok(ExitCode::from(JOURNAL_ERROR_EXIT));
|
||||
}
|
||||
}
|
||||
result.map(|()| ExitCode::SUCCESS)
|
||||
}
|
||||
|
||||
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;
|
||||
@@ -158,14 +243,14 @@ fn verify_fixture(path: &Path) -> Result<&'static [u8], Box<dyn Error>> {
|
||||
.ok_or_else(|| rejection.into())
|
||||
}
|
||||
|
||||
fn run_worker(options: &Options) -> Result<(), Box<dyn Error>> {
|
||||
fn run_worker(options: &Options, mut events: Option<&mut Events>) -> 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);
|
||||
std::process::exit(i32::from(WATCHDOG_EXIT));
|
||||
})?;
|
||||
let fixture = verify_fixture(&options.path)?;
|
||||
let (name, ticket, bound_imports) = if fixture == SERVICES_FIXTURE {
|
||||
@@ -232,6 +317,16 @@ fn run_worker(options: &Options) -> Result<(), Box<dyn Error>> {
|
||||
imports,
|
||||
options.max_steps,
|
||||
|event| {
|
||||
if let Some(events) = events.as_deref_mut() {
|
||||
events.stage(match &event {
|
||||
StartupEvent::Parsed { .. } => "parsed",
|
||||
StartupEvent::Mapped { .. } => "mapped",
|
||||
StartupEvent::Relocated { .. } => "relocated",
|
||||
StartupEvent::ImportsBound { .. } => "imports_bound",
|
||||
StartupEvent::TlsCompleted { .. } => "tls_completed",
|
||||
StartupEvent::Entering { .. } => "entry",
|
||||
});
|
||||
}
|
||||
if options.trace {
|
||||
trace_startup(event);
|
||||
}
|
||||
@@ -244,6 +339,11 @@ fn run_worker(options: &Options) -> Result<(), Box<dyn Error>> {
|
||||
.take();
|
||||
let exit = startup.execution.exit_reason;
|
||||
let rax = startup.execution.final_state.get(Register::Rax);
|
||||
if exit == ExitReason::Halt
|
||||
&& let Some(events) = events.as_deref_mut()
|
||||
{
|
||||
events.stage("exit");
|
||||
}
|
||||
if options.trace {
|
||||
println!(
|
||||
"trace stage=exit entry_steps={} exit={exit:?} rax={rax:#x}",
|
||||
@@ -264,6 +364,9 @@ fn run_worker(options: &Options) -> Result<(), Box<dyn Error>> {
|
||||
return Err("trusted fixture startup or result differs from the expected values".into());
|
||||
}
|
||||
let frame = result.ok_or("guest halted without a draw")??;
|
||||
if let Some(events) = events {
|
||||
events.stage("framebuffer");
|
||||
}
|
||||
if options.trace {
|
||||
println!(
|
||||
"trace stage=framebuffer extent={}x{} verified_pixels={}",
|
||||
|
||||
@@ -0,0 +1,399 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
use std::fmt::Write as _;
|
||||
use std::fs::{self, File, OpenOptions};
|
||||
use std::io::{self, Read, Write};
|
||||
use std::os::unix::fs::DirBuilderExt;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::ExitStatus;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
pub(super) const WATCHDOG_EXIT: u8 = 124;
|
||||
pub(super) const JOURNAL_ERROR_EXIT: u8 = 125;
|
||||
const VERSION: &str = "1";
|
||||
const RECORD_SEPARATOR: char = '\t';
|
||||
const MAX_BYTES: usize = 8192;
|
||||
const MAX_ERROR_BYTES: usize = 2048;
|
||||
const STAGES: [&str; 8] = [
|
||||
"parsed",
|
||||
"mapped",
|
||||
"relocated",
|
||||
"imports_bound",
|
||||
"tls_completed",
|
||||
"entry",
|
||||
"exit",
|
||||
"framebuffer",
|
||||
];
|
||||
|
||||
pub(super) struct Journal(PathBuf);
|
||||
|
||||
impl Journal {
|
||||
pub(super) fn create() -> io::Result<Self> {
|
||||
static NEXT: AtomicUsize = AtomicUsize::new(0);
|
||||
loop {
|
||||
let id = NEXT.fetch_add(1, Ordering::Relaxed);
|
||||
let directory =
|
||||
std::env::temp_dir().join(format!("betterxen-startup-{}-{id}", std::process::id()));
|
||||
match fs::DirBuilder::new().mode(0o700).create(&directory) {
|
||||
Ok(()) => return Ok(Self(directory)),
|
||||
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn path(&self) -> PathBuf {
|
||||
self.0.join("events")
|
||||
}
|
||||
|
||||
fn read(&self) -> Report {
|
||||
let mut bytes = Vec::new();
|
||||
match File::open(self.path())
|
||||
.and_then(|file| file.take((MAX_BYTES + 1) as u64).read_to_end(&mut bytes))
|
||||
{
|
||||
Ok(_) => Report::parse(&bytes),
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => Report::default(),
|
||||
Err(_) => Report {
|
||||
integrity: "unreadable",
|
||||
..Report::default()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn finish(
|
||||
&self,
|
||||
mut destination: File,
|
||||
termination: &io::Result<Termination>,
|
||||
) -> io::Result<()> {
|
||||
destination.write_all(self.read().json(termination).as_bytes())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Journal {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_file(self.path());
|
||||
let _ = fs::remove_dir(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) struct Events(File, Option<io::Error>);
|
||||
|
||||
impl Events {
|
||||
pub(super) fn open(path: &Path) -> io::Result<Self> {
|
||||
OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(path)
|
||||
.map(|file| Self(file, None))
|
||||
}
|
||||
|
||||
pub(super) fn stage(&mut self, stage: &str) {
|
||||
self.record(format_args!("{VERSION}\t{stage}"));
|
||||
}
|
||||
|
||||
pub(super) fn failure(&mut self, error: &dyn std::error::Error) {
|
||||
let message = error.to_string();
|
||||
let end = message.floor_char_boundary(MAX_ERROR_BYTES);
|
||||
let mut encoded = String::with_capacity(end * 2);
|
||||
for byte in message[..end].bytes() {
|
||||
write!(encoded, "{byte:02x}").unwrap();
|
||||
}
|
||||
self.record(format_args!(
|
||||
"{VERSION}\tfailure\t{}\t{encoded}",
|
||||
u8::from(end < message.len())
|
||||
));
|
||||
}
|
||||
fn record(&mut self, arguments: std::fmt::Arguments<'_>) {
|
||||
if self.1.is_none() {
|
||||
self.1 = writeln!(self.0, "{arguments}").err();
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn write_error(&self) -> Option<&io::Error> {
|
||||
self.1.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) enum Termination {
|
||||
Exited(ExitStatus),
|
||||
Deadline,
|
||||
}
|
||||
|
||||
struct Report {
|
||||
completed: usize,
|
||||
error: Option<String>,
|
||||
error_truncated: bool,
|
||||
integrity: &'static str,
|
||||
}
|
||||
|
||||
impl Default for Report {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
completed: 0,
|
||||
error: None,
|
||||
error_truncated: false,
|
||||
integrity: "complete",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Report {
|
||||
fn parse(bytes: &[u8]) -> Self {
|
||||
let mut report = Self::default();
|
||||
let bounded = &bytes[..bytes.len().min(MAX_BYTES)];
|
||||
for line in bounded.split_inclusive(|&byte| byte == b'\n') {
|
||||
let Some(line) = line.strip_suffix(b"\n") else {
|
||||
report.integrity = "truncated";
|
||||
break;
|
||||
};
|
||||
if !std::str::from_utf8(line).is_ok_and(|line| report.record(line)) {
|
||||
report.integrity = "malformed";
|
||||
break;
|
||||
}
|
||||
}
|
||||
if bytes.len() > MAX_BYTES {
|
||||
report.integrity = "oversized";
|
||||
}
|
||||
report
|
||||
}
|
||||
|
||||
fn record(&mut self, line: &str) -> bool {
|
||||
let Some((VERSION, record)) = line.split_once(RECORD_SEPARATOR) else {
|
||||
return false;
|
||||
};
|
||||
if self.error.is_some() {
|
||||
return false;
|
||||
}
|
||||
if STAGES.get(self.completed) == Some(&record) {
|
||||
self.completed += 1;
|
||||
return true;
|
||||
}
|
||||
let Some((truncated, encoded)) = record
|
||||
.strip_prefix("failure\t")
|
||||
.and_then(|s| s.split_once('\t'))
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
if !matches!(truncated, "0" | "1")
|
||||
|| encoded.len() > MAX_ERROR_BYTES * 2
|
||||
|| !encoded.len().is_multiple_of(2)
|
||||
|| !encoded.bytes().all(|byte| byte.is_ascii_hexdigit())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let (pairs, _) = encoded.as_bytes().as_chunks::<2>();
|
||||
let Some(message) = pairs
|
||||
.iter()
|
||||
.map(|pair| u8::from_str_radix(std::str::from_utf8(pair).ok()?, 16).ok())
|
||||
.collect::<Option<Vec<_>>>()
|
||||
.and_then(|bytes| String::from_utf8(bytes).ok())
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
self.error = Some(message);
|
||||
self.error_truncated = truncated == "1";
|
||||
true
|
||||
}
|
||||
|
||||
fn json(&self, termination: &io::Result<Termination>) -> String {
|
||||
let unwritable = matches!(termination, Ok(Termination::Exited(status))
|
||||
if status.code() == Some(i32::from(JOURNAL_ERROR_EXIT)));
|
||||
let integrity = if unwritable {
|
||||
"unwritable"
|
||||
} else {
|
||||
self.integrity
|
||||
};
|
||||
let (outcome, status, detail) = match termination {
|
||||
Ok(Termination::Deadline) => (
|
||||
"timeout",
|
||||
None,
|
||||
Some("worker exceeded the wall deadline".into()),
|
||||
),
|
||||
Err(error) => ("unknown", None, Some(error.to_string())),
|
||||
Ok(Termination::Exited(status)) if status.code() == Some(i32::from(WATCHDOG_EXIT)) => (
|
||||
"timeout",
|
||||
Some(status),
|
||||
Some("worker watchdog expired".into()),
|
||||
),
|
||||
Ok(Termination::Exited(status)) if unwritable => (
|
||||
"unknown",
|
||||
Some(status),
|
||||
Some("worker could not write its startup journal".into()),
|
||||
),
|
||||
Ok(Termination::Exited(status))
|
||||
if status.success()
|
||||
&& self.error.is_none()
|
||||
&& self.completed == STAGES.len()
|
||||
&& self.integrity == "complete" =>
|
||||
{
|
||||
("verified", Some(status), None)
|
||||
}
|
||||
Ok(Termination::Exited(status))
|
||||
if status.code().is_some() && !status.success() && self.error.is_some() =>
|
||||
{
|
||||
("stage_failure", Some(status), None)
|
||||
}
|
||||
Ok(Termination::Exited(status)) if status.code().is_some() && !status.success() => {
|
||||
("early_exit", Some(status), Some(status.to_string()))
|
||||
}
|
||||
Ok(Termination::Exited(status)) => ("unknown", Some(status), Some(status.to_string())),
|
||||
};
|
||||
let stages = &STAGES[..self.completed];
|
||||
let records = stages
|
||||
.iter()
|
||||
.map(|stage| format!(r#"{{"schema_version":{VERSION},"stage":"{stage}"}}"#))
|
||||
.collect::<Vec<_>>()
|
||||
.join(",");
|
||||
let last = json_string(stages.last().copied());
|
||||
let error = json_string(self.error.as_deref());
|
||||
let detail = json_string(detail.as_deref());
|
||||
let code = status
|
||||
.and_then(|status| status.code())
|
||||
.map_or("null".into(), |code| code.to_string());
|
||||
format!(
|
||||
"{{\"schema_version\":{VERSION},\"outcome\":\"{outcome}\",\"last_completed_stage\":{last},\"record_integrity\":\"{}\",\"worker_exit_code\":{code},\"termination_detail\":{detail},\"error\":{error},\"error_truncated\":{},\"stages\":[{records}]}}\n",
|
||||
integrity, self.error_truncated
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn json_string(value: Option<&str>) -> String {
|
||||
let Some(value) = value else {
|
||||
return String::from("null");
|
||||
};
|
||||
let mut escaped = String::from("\"");
|
||||
for ch in value.chars() {
|
||||
match ch {
|
||||
'"' => escaped.push_str("\\\""),
|
||||
'\\' => escaped.push_str("\\\\"),
|
||||
'\0'..='\u{1f}' => write!(escaped, "\\u{:04x}", u32::from(ch)).unwrap(),
|
||||
_ => escaped.push(ch),
|
||||
}
|
||||
}
|
||||
escaped.push('"');
|
||||
escaped
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::process::Command;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
#[test]
|
||||
fn journal_write_error_surfaces_in_report() {
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
let journal = Journal::create().unwrap();
|
||||
fs::write(journal.path(), b"1\tparsed\n").unwrap();
|
||||
let mut events = Events(File::open(journal.path()).unwrap(), None);
|
||||
events.stage("mapped");
|
||||
assert!(events.write_error().is_some());
|
||||
let status = ExitStatus::from_raw(i32::from(JOURNAL_ERROR_EXIT) << 8);
|
||||
let result = journal.read().json(&Ok(Termination::Exited(status)));
|
||||
assert!(
|
||||
result.contains(r#""record_integrity":"unwritable""#),
|
||||
"{result}"
|
||||
);
|
||||
assert!(
|
||||
result.contains(r#""last_completed_stage":"parsed""#),
|
||||
"{result}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn terminal_failure_keeps_signal_detail_after_all_stages() {
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
let journal = Journal::create().unwrap();
|
||||
let mut events = Events::open(&journal.path()).unwrap();
|
||||
for stage in STAGES {
|
||||
events.stage(stage);
|
||||
}
|
||||
events.failure(&io::Error::other("late error"));
|
||||
let report = journal.read();
|
||||
assert_eq!(report.integrity, "complete");
|
||||
let result = report.json(&Ok(Termination::Exited(ExitStatus::from_raw(15))));
|
||||
assert!(result.contains(r#""outcome":"unknown""#), "{result}");
|
||||
assert!(result.contains(r#""error":"late error""#), "{result}");
|
||||
assert!(result.contains("signal: 15"), "{result}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn supervisor_distinguishes_early_exit_watchdog_signal_and_deadline() {
|
||||
for (script, limit, outcome, code) in [
|
||||
("exit 9", Duration::from_secs(2), "early_exit", "9"),
|
||||
("exit 124", Duration::from_secs(2), "timeout", "124"),
|
||||
("kill -TERM $$", Duration::from_secs(2), "unknown", "null"),
|
||||
(
|
||||
"exec sleep 5",
|
||||
Duration::from_millis(250),
|
||||
"timeout",
|
||||
"null",
|
||||
),
|
||||
] {
|
||||
let journal = Journal::create().unwrap();
|
||||
let started = Instant::now();
|
||||
let child = Command::new("/bin/sh")
|
||||
.args([
|
||||
"-c",
|
||||
&format!("printf '1\\tparsed\\n' > \"$1\"; {script}"),
|
||||
"worker",
|
||||
])
|
||||
.arg(journal.path())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let termination = super::super::supervise(child, started, limit);
|
||||
let report = journal.read().json(&termination);
|
||||
assert!(
|
||||
report.contains(&format!(r#""outcome":"{outcome}""#)),
|
||||
"{report}"
|
||||
);
|
||||
assert!(
|
||||
report.contains(&format!(r#""worker_exit_code":{code}"#)),
|
||||
"{report}"
|
||||
);
|
||||
assert!(
|
||||
report.contains(r#""last_completed_stage":"parsed""#),
|
||||
"{report}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_records_keep_only_the_valid_prefix() {
|
||||
let mut oversized = b"1\tparsed\n1\tmapped".to_vec();
|
||||
oversized.resize(MAX_BYTES + 1, b'x');
|
||||
for (bytes, integrity) in [
|
||||
(&b"1\tparsed\n1\tmapped"[..], "truncated"),
|
||||
(&b"1\tparsed\n1\tentry\n1\tmapped\n"[..], "malformed"),
|
||||
(&b"1\tparsed\n1\tfailure\t0\tqq\n"[..], "malformed"),
|
||||
(oversized.as_slice(), "oversized"),
|
||||
] {
|
||||
let journal = Journal::create().unwrap();
|
||||
fs::write(journal.path(), bytes).unwrap();
|
||||
let report = journal.read();
|
||||
assert_eq!(report.completed, 1);
|
||||
assert_eq!(report.integrity, integrity);
|
||||
assert!(report.error.is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failure_preserves_original_context_with_bounded_utf8() {
|
||||
let journal = Journal::create().unwrap();
|
||||
let mut events = Events::open(&journal.path()).unwrap();
|
||||
events.stage("parsed");
|
||||
let message = format!("line\nwith \"quote\" and \\{}", "é".repeat(MAX_ERROR_BYTES));
|
||||
events.failure(&io::Error::other(&message[..]));
|
||||
let report = journal.read();
|
||||
assert_eq!(
|
||||
report.error.as_deref(),
|
||||
Some(&message[..message.floor_char_boundary(MAX_ERROR_BYTES)])
|
||||
);
|
||||
assert!(report.error_truncated);
|
||||
let json = report.json(&Ok(Termination::Deadline));
|
||||
assert!(
|
||||
json.contains(r#"line\u000awith \"quote\" and \\"#),
|
||||
"{json}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
const STARTUP_STAGES: &[&str] = &[
|
||||
"parsed",
|
||||
"mapped",
|
||||
"relocated",
|
||||
"imports_bound",
|
||||
"tls_completed",
|
||||
"entry",
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn trusted_fixture_preserves_step_failure() {
|
||||
let report = run_fixture("1", false);
|
||||
assert!(report.contains(r#""outcome":"stage_failure""#), "{report}");
|
||||
assert!(
|
||||
report.contains(r#""last_completed_stage":"entry""#),
|
||||
"{report}"
|
||||
);
|
||||
assert!(report.contains("step budget exhausted"), "{report}");
|
||||
assert_stages(&report, STARTUP_STAGES);
|
||||
assert!(!report.contains(r#""stage":"exit""#), "{report}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires a native Metal device with Apple family 7 capabilities"]
|
||||
fn trusted_fixture_reports_verified_progress() {
|
||||
let report = run_fixture("100", true);
|
||||
assert!(report.contains(r#""outcome":"verified""#), "{report}");
|
||||
assert!(
|
||||
report.contains(r#""last_completed_stage":"framebuffer""#),
|
||||
"{report}"
|
||||
);
|
||||
let stages = [STARTUP_STAGES, &["exit", "framebuffer"]].concat();
|
||||
assert_stages(&report, &stages);
|
||||
}
|
||||
|
||||
fn run_fixture(steps: &str, success: bool) -> String {
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"betterxen-report-test-{}-{steps}.json",
|
||||
std::process::id()
|
||||
));
|
||||
let fixture = concat!(
|
||||
env!("CARGO_MANIFEST_DIR"),
|
||||
"/../../fixtures/pe/trusted-runner.exe"
|
||||
);
|
||||
let output = Command::new(env!("CARGO_BIN_EXE_betterxen"))
|
||||
.args([
|
||||
"run",
|
||||
"--experimental",
|
||||
"--pe",
|
||||
fixture,
|
||||
"--max-steps",
|
||||
steps,
|
||||
"--startup-report",
|
||||
])
|
||||
.arg(&path)
|
||||
.output()
|
||||
.unwrap();
|
||||
let report = std::fs::read_to_string(&path);
|
||||
if report.is_ok() {
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
}
|
||||
assert_eq!(output.status.success(), success, "{output:?}, {report:?}");
|
||||
report.unwrap()
|
||||
}
|
||||
|
||||
fn assert_stages(report: &str, stages: &[&str]) {
|
||||
assert!(report.contains(r#""schema_version":1"#), "{report}");
|
||||
let mut remaining = report;
|
||||
for stage in stages {
|
||||
remaining = remaining
|
||||
.split_once(&format!(r#""stage":"{stage}""#))
|
||||
.unwrap()
|
||||
.1;
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn existing_report_path_prevents_worker_launch() {
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"betterxen-report-existing-{}.json",
|
||||
std::process::id()
|
||||
));
|
||||
std::fs::write(&path, "previous report").unwrap();
|
||||
let result = Command::new(env!("CARGO_BIN_EXE_betterxen"))
|
||||
.args([
|
||||
"run",
|
||||
"--experimental",
|
||||
"--pe",
|
||||
"missing-fixture",
|
||||
"--startup-report",
|
||||
])
|
||||
.arg(&path)
|
||||
.output()
|
||||
.unwrap();
|
||||
let contents = std::fs::read_to_string(&path).unwrap();
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
assert_eq!(contents, "previous report");
|
||||
assert!(!result.status.success());
|
||||
let stderr = String::from_utf8(result.stderr).unwrap();
|
||||
assert!(
|
||||
stderr.contains("could not create startup report"),
|
||||
"{stderr}"
|
||||
);
|
||||
assert!(!stderr.contains("No such file or directory"), "{stderr}");
|
||||
}
|
||||
+33
-10
@@ -633,15 +633,22 @@ impl Arm64Assembler {
|
||||
self.emit(0x92800000 | (hw << 21) | ((imm16 as u32) << 5) | (xd as u32 & 0x1f));
|
||||
}
|
||||
|
||||
/// Load a full 64-bit constant into register Xd with the fewest MOVZ or
|
||||
/// MOVN plus MOVK instructions: one for each halfword that differs from
|
||||
/// the background the first instruction leaves, and always at least one.
|
||||
/// MOVZ leaves zero halfwords and MOVN leaves 0xFFFF ones, so MOVN is used
|
||||
/// when more halfwords are 0xFFFF than zero.
|
||||
/// Load a full 64-bit constant into Xd with the fewest wide moves.
|
||||
/// A 32-bit MOVN leaves one low halfword set to 0xFFFF and zero-extends
|
||||
/// the result into Xd. For other values, select a 64-bit MOVZ or MOVN
|
||||
/// background and use MOVK for the remaining halfwords.
|
||||
pub fn load_imm_64(&mut self, xd: u8, val: u64) {
|
||||
let halves: [u16; 4] = std::array::from_fn(|i| (val >> (16 * i)) as u16);
|
||||
let zeros = halves.iter().filter(|&&h| h == 0).count();
|
||||
let ones = halves.iter().filter(|&&h| h == 0xffff).count();
|
||||
// With only the top two halfwords zero, a 32-bit MOVN saves one
|
||||
// instruction when either of the lower halfwords is all ones.
|
||||
if zeros == 2 && ones != 0 && val >> 32 == 0 {
|
||||
let index = usize::from(halves[1] != u16::MAX);
|
||||
let imm16 = u32::from(!halves[index]);
|
||||
self.emit(0x1280_0000 | ((index as u32) << 21) | (imm16 << 5) | u32::from(xd & 0x1f));
|
||||
return;
|
||||
}
|
||||
let background = if ones > zeros { 0xffff } else { 0 };
|
||||
// The first halfword that differs from the background, or halfword 0
|
||||
// when none does (val is 0 or all ones).
|
||||
@@ -883,12 +890,14 @@ mod tests {
|
||||
}
|
||||
|
||||
/// Constants at the halfword boundaries the MOVZ/MOVN choice depends on.
|
||||
const IMMEDIATE_EDGES: [u64; 16] = [
|
||||
const IMMEDIATE_EDGES: [u64; 18] = [
|
||||
0,
|
||||
1,
|
||||
0xffff,
|
||||
0x1_0000,
|
||||
0x8000_0000,
|
||||
0xffff_1234,
|
||||
0x1234_ffff,
|
||||
0xffff_ffff,
|
||||
0x1_0000_0000,
|
||||
0x1234_0000_0000_0000,
|
||||
@@ -904,10 +913,13 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn immediate_sequences_match_llvm_encodings() {
|
||||
// llvm-mc -triple=aarch64-apple-macos -show-encoding.
|
||||
// A64 words from llvm-mc and Apple Clang's integrated assembler.
|
||||
let cases: &[(u64, &[u32])] = &[
|
||||
(0, &[0xd2800000]), // movz x0, #0
|
||||
(u64::MAX, &[0x92800000]), // movn x0, #0
|
||||
(0xffff_1234, &[0x129db960]), // movn w0, #0xedcb
|
||||
(0x1234_ffff, &[0x12bdb960]), // movn w0, #0xedcb, lsl #16
|
||||
(0xffff_ffff, &[0x12800000]), // movn w0, #0
|
||||
(0xffff_ffff_ffff_1234, &[0x929db960]), // movn x0, #0xedcb
|
||||
(0x1234_0000_0000_0000, &[0xd2e24680]), // movz x0, #0x1234, lsl #48
|
||||
(0xffff_0000_ffff_ffff, &[0x92dfffe0]), // movn x0, #0xffff, lsl #32
|
||||
@@ -930,9 +942,16 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// Fewest MOVZ/MOVN/MOVK instructions for `value`: every halfword that is
|
||||
/// neither zero (after MOVZ) nor 0xFFFF (after MOVN), and at least one.
|
||||
/// A 32-bit MOVN can write a zero-extended value if its low word's
|
||||
/// complement fits in a single halfword. Otherwise count the halfwords
|
||||
/// that differ from either 64-bit initializer's background.
|
||||
fn shortest_wide_move(value: u64) -> usize {
|
||||
if let Ok(low) = u32::try_from(value) {
|
||||
let complement = !low;
|
||||
if complement <= u32::from(u16::MAX) || complement.trailing_zeros() >= 16 {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
let halves = (0..4).map(|i| (value >> (16 * i)) & 0xffff);
|
||||
let not_zero = halves.clone().filter(|&h| h != 0).count();
|
||||
let not_ones = halves.filter(|&h| h != 0xffff).count();
|
||||
@@ -964,9 +983,13 @@ mod tests {
|
||||
for value in values {
|
||||
for register in [X0, X9] {
|
||||
let mut asm = Arm64Assembler::new();
|
||||
// Seed the destination so a W-register load must clear the high bits.
|
||||
asm.movn_64(register, 0, 0);
|
||||
// Assembler offsets count 32-bit instruction words.
|
||||
let start = asm.current_offset();
|
||||
asm.load_imm_64(register, value);
|
||||
assert_eq!(
|
||||
asm.instructions().len(),
|
||||
asm.current_offset() - start,
|
||||
shortest_wide_move(value),
|
||||
"{value:#x}"
|
||||
);
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
[package]
|
||||
name = "victory-shader"
|
||||
description = "Xbox shader containers (DXBC/DXIL + precompiled GFX10) to host shaders. Vendored from skakwy/victory-mac; see UPSTREAM.md."
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
thiserror = "2.0.21"
|
||||
zlib-rs = { version = "0.6.8", default-features = false, features = ["std"] }
|
||||
|
||||
[features]
|
||||
# Host D3D12 pipeline checks (`emit::host`); Windows targets only.
|
||||
host = ["dep:windows"]
|
||||
# Debugging switches (emitted-module dumps and the like).
|
||||
diagnostics = []
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { version = "0.61.2", features = ["Win32_System_LibraryLoader"] }
|
||||
windows = { version = "0.62.2", optional = true, features = [
|
||||
"Win32_Foundation",
|
||||
"Win32_Graphics_Direct3D",
|
||||
"Win32_Graphics_Direct3D12",
|
||||
"Win32_Graphics_Dxgi",
|
||||
"Win32_Graphics_Dxgi_Common",
|
||||
] }
|
||||
|
||||
[target.'cfg(windows)'.dev-dependencies]
|
||||
windows = { version = "0.62.2", features = [
|
||||
"Win32_Foundation",
|
||||
"Win32_Graphics_Direct3D",
|
||||
"Win32_Graphics_Direct3D12",
|
||||
"Win32_Graphics_Dxgi",
|
||||
"Win32_Graphics_Dxgi_Common",
|
||||
] }
|
||||
|
||||
[lints.rust]
|
||||
unsafe_op_in_unsafe_fn = "deny"
|
||||
unused_must_use = "deny"
|
||||
|
||||
[lints.clippy]
|
||||
all = { level = "warn", priority = -1 }
|
||||
# Same allowances as the upstream workspace (victory-mac Cargo.toml [workspace.lints.clippy]).
|
||||
type_complexity = "allow"
|
||||
needless_range_loop = "allow"
|
||||
chunks_exact_to_as_chunks = "allow"
|
||||
sliced_string_as_bytes = "allow"
|
||||
collapsible_match = "allow"
|
||||
manual_clamp = "allow"
|
||||
implicit_saturating_sub = "allow"
|
||||
min_max = "allow"
|
||||
undocumented_unsafe_blocks = "allow"
|
||||
@@ -0,0 +1,36 @@
|
||||
# Upstream provenance: victory-shader
|
||||
|
||||
**Not approved for merge.** This crate was developed against one commercial title's shaders; the per-file review and the open maintainer decision are in `docs/research/victory-shader-provenance.md`.
|
||||
|
||||
| | |
|
||||
| --- | --- |
|
||||
| Source | <https://github.com/skakwy/victory-mac>, directory `crates/victory-shader/` (Cargo.toml and `src/`) |
|
||||
| Repository head when copied | `22b3f8e45a59` (2026-11-25); the directory's last change is commit `559357432b41` |
|
||||
| Licence | GPL-3.0 (repository `LICENSE`); workspace manifest declares `GPL-3.0-or-later`, the same as BetterXen. No file in the crate carries a different licence |
|
||||
| Third-party notice kept in place | `src/gfx10/opcodes.rs`: opcode names generated from Mesa's `aco_opcodes.py` (tag mesa-22.3.0), MIT, Copyright (c) 2018 Valve Corporation; the notice is in the file header |
|
||||
| Authorization | skakwy and the VIctory-macOS maintainer authorize reuse of their contributions (relayed by the BetterXen maintainer). Other authors' lines are used under the repository's GPL-3.0 |
|
||||
| Authors (commits touching this directory, from `git shortlog`) | Marvis (33), skakwy (12), fxceless (11), r4. (6), Duff (4), 9hvn9yt2vk-netizen (3), tedin7 (3), DexNom (2), Luiz Neves (2), Saitken91 (2), others; some commits are credited to an AI assistant |
|
||||
| What it is | Xbox Series shader containers (DXBC with Xbox additions) and precompiled GFX10 (RDNA 2) machine code translated to PC DXIL (SM 6.6): GFX10 decoder and SP3 printer, control-flow structurizer, IR, register spilling, wave emulation, fp64 by integer operations, an own LLVM 3.7 bitcode writer and container signing |
|
||||
| Upstream commit-level history | Not carried; see the upstream repository. This directory is a snapshot, so later upstream fixes must be merged by comparing with the pinned commit |
|
||||
|
||||
## Modifications made by BetterXen
|
||||
|
||||
Changes to upstream files (19 lines, nothing functional) and files BetterXen added (marked `BetterXen addition`, GPL-3.0-or-later): `src/emit/betterxen.rs` (a public `translate_native` for raw compute programs, same stages as `translate`) and `src/emit/betterxen_tests.rs` (BetterXen gfx1030 fixtures through the recompiler, and on the GPU under CrossOver). Two lines in `src/emit/mod.rs` declare them. Validation record: `docs/research/victory-shader-integration.md`.
|
||||
|
||||
### Edits to upstream files
|
||||
|
||||
- `Cargo.toml` rewritten: workspace-inherited dependency versions replaced by explicit ones (`thiserror` 2.0.21, `zlib-rs` 0.6.8, `windows` 0.62.2, `windows-sys` 0.61.2), same features and lint allowances as upstream's workspace.
|
||||
- `src/lib.rs`: `#[rustfmt::skip]` on each `mod` so the vendored files stay byte-comparable with upstream.
|
||||
- `src/emit/mod.rs`, `src/emit/f64.rs`, `src/emit/lower.rs`: `#[allow(...)]` attributes only, so the crate passes `clippy -D warnings` here. They silence imports and variables used only by Windows-only tests, an unused trait method, a test constant that looks like pi, and two dead duplicate match arms in `lower.rs` that exist upstream (an earlier arm already handles `v_cvt_f32_f64` and `v_permlanex16_b32`).
|
||||
|
||||
### Functional edits to upstream files (research/shader-wave-semantics, PR #392)
|
||||
|
||||
- `src/emit/lower.rs` (`active_f64_sum`, about 90 lines): the whole-wave f64 sum no longer emits a native `double` wave operation (`makeDouble`, `waveActiveOp.f64`, `splitDouble`); it builds the console's balanced tree over the lanes with the crate's own integer `add_f64`, reading partner runs through `waveReadLaneAt` and a ballot for lanes that are not present, and no longer sets the doubles feature flag. Why: D3DMetal reports no double-precision shader operations and a shader that uses a `double` ran without writing anything (docs/research/shader-wave-semantics.md).
|
||||
- `src/emit/bitcode.rs`: two `#[allow(dead_code)]` for the double type, now never constructed.
|
||||
- `src/emit/host.rs`: `Host::wave_lane_count_max()` and `Host::hardware()` (test host only; `hardware()` ignores `VICTORY_WARP`).
|
||||
- `src/emit/mod.rs`: the static-sampler construction is factored into `static_samplers()` so `translate_native` reports immediate samplers.
|
||||
- `src/emit/wave64_tests.rs`: `a_sum_of_halves_where_lanes_have_left_is_the_consoles_tree_bit_for_bit` checks the device's wave width and, on a device narrower than 64 lanes, asserts the recompiler's refusal instead of running a 64-lane lowering.
|
||||
|
||||
## Not carried
|
||||
|
||||
The upstream repository's other crates (`victory-gpu`, `victory-loader`, `victory-hle`, ...), which are tied to one console title and its runtime, and `mac/`, `tools/`. No shader binaries or dumps of the title the upstream project targets are included, but comments and behaviour in this crate refer to that title's shaders; BetterXen validates this crate only with its own synthetic fixtures (see `docs/research/` for the validation record).
|
||||
@@ -0,0 +1,696 @@
|
||||
//! The console GPU's ray-tracing node test, `image_bvh_intersect_ray` and
|
||||
//! `image_bvh64_intersect_ray`, on the CPU: the node formats, and what the
|
||||
//! instruction returns for one ray and one node. The emitter lowers the
|
||||
//! instruction to the same arithmetic in the same order
|
||||
//! (`emit/intersect.rs`), so its code can be compared against this dword
|
||||
//! for dword.
|
||||
//!
|
||||
//! The instruction tests one ray against one 64-byte node of a bounding
|
||||
//! volume hierarchy and returns four dwords. Traversal (the stack, instance
|
||||
//! transforms, culling, the hit distance `numerator / denominator`) is the
|
||||
//! program's own code.
|
||||
//!
|
||||
//! # Node pointers
|
||||
//!
|
||||
//! A node pointer's low three bits are the node's kind, the rest its byte
|
||||
//! offset in 8-byte units: the node is at `(pointer >> 3) << 6` past the
|
||||
//! base address of the descriptor (40 bits in dword 0 and the low byte of
|
||||
//! dword 1, in 256-byte units). The 32-bit form takes a 32-bit pointer;
|
||||
//! the 64-bit form a 64-bit one, with which a program uses one descriptor
|
||||
//! with base 0 for every structure and adds `address >> 3` itself.
|
||||
//!
|
||||
//! | kind | node |
|
||||
//! |---|---|
|
||||
//! | 0-3 | triangle 0-3 of a triangle node |
|
||||
//! | 4 | box node, 16-bit floats (64 bytes) |
|
||||
//! | 5 | box node, 32-bit floats (128 bytes) |
|
||||
//! | 6 | instance: not read by the instruction |
|
||||
//! | 7 | procedural primitive: not read by the instruction |
|
||||
//!
|
||||
//! # Box nodes
|
||||
//!
|
||||
//! Four child pointers at bytes 0-15 (`0xffff_ffff`: none), then four
|
||||
//! boxes, each minimum x y z, maximum x y z: 16-bit floats from byte 16
|
||||
//! (12 bytes a box), or 32-bit floats from byte 16 (24 bytes a box; bytes
|
||||
//! 112-127 are not read). The result is the pointers of the children whose
|
||||
//! box the ray enters before its extent, nearest entry first when the
|
||||
//! descriptor enables box sorting (bit 63), and `0xffff_ffff` for the rest.
|
||||
//!
|
||||
//! # Triangle nodes
|
||||
//!
|
||||
//! Five vertices of three 32-bit floats at bytes 0-59 and a dword at byte
|
||||
//! 60 with one byte per triangle: bits 1:0 name the triangle's vertex that
|
||||
//! barycentric I weighs, bits 3:2 the one J weighs (the builder stores an
|
||||
//! input triangle's second vertex at the former, its third at the latter
|
||||
//! and its first at the remaining one, so I and J are the weights of the
|
||||
//! input triangle's second and third vertices). Triangle `k` of the node
|
||||
//! uses the node's vertices [`TRIANGLE_VERTICES`]`[k]`. A program that
|
||||
//! keeps fewer triangles in a node uses the bytes of the unused vertices
|
||||
//! for its own data.
|
||||
//!
|
||||
//! With the descriptor's triangle return mode set (bit 120) the result is
|
||||
//! the hit distance's numerator, its denominator, and the numerators of I
|
||||
//! and J over the same denominator, as floats. The denominator is positive
|
||||
//! for a triangle whose vertices run clockwise seen from the ray's origin
|
||||
//! in a left-handed coordinate system. A miss returns +infinity, 1.0, 0, 0.
|
||||
//! The ray's extent is not tested for triangles.
|
||||
//!
|
||||
//! # Where this comes from
|
||||
//!
|
||||
//! The node formats, the descriptor bits and the tests are those of the
|
||||
//! public software emulation of this instruction in the open-source Vulkan
|
||||
//! driver for this GPU family (box test and sorting network as there; the
|
||||
//! triangle test is the watertight one it uses, Woop, Benthin and Wald,
|
||||
//! JCGT 2013), and agree with what the title's own structure
|
||||
//! builder writes and its trace programs read. Not known from either: how
|
||||
//! the console rounds, which of two boxes entered at the same distance it
|
||||
//! returns first, and what it returns for a ray exactly through an edge
|
||||
//! (here: a hit in both triangles of the edge) or for kinds 6 and 7 (here:
|
||||
//! a triangle miss; the title's programs do not read it).
|
||||
|
||||
/// The result dword for a box the ray misses, or a child that is not there.
|
||||
pub const NONE: u32 = 0xffff_ffff;
|
||||
|
||||
/// The node's vertices that make triangle 0-3, by the triangle's own
|
||||
/// vertex numbers 0-2.
|
||||
pub const TRIANGLE_VERTICES: [[u32; 3]; 4] = [[0, 1, 2], [1, 3, 2], [2, 3, 4], [2, 4, 0]];
|
||||
|
||||
/// Descriptor dword 1: boxes are returned nearest first.
|
||||
pub const BOX_SORT: u32 = 1 << 31;
|
||||
/// Descriptor dword 3: triangles return the numerators of I and J (clear:
|
||||
/// a triangle id and a hit status, which nothing here produces).
|
||||
pub const RETURN_BARYCENTRICS: u32 = 1 << 24;
|
||||
/// Descriptor dword 3, bits 31:28: the descriptor's type, a ray-tracing
|
||||
/// structure.
|
||||
pub const DESCRIPTOR_TYPE: u32 = 8;
|
||||
|
||||
/// The ray as the instruction takes it.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct Ray {
|
||||
pub extent: f32,
|
||||
pub origin: [f32; 3],
|
||||
pub direction: [f32; 3],
|
||||
/// What the program computed as `1 / direction`.
|
||||
pub inverse: [f32; 3],
|
||||
}
|
||||
|
||||
impl Ray {
|
||||
/// A ray with the inverse direction a program computes by division.
|
||||
pub fn new(origin: [f32; 3], direction: [f32; 3], extent: f32) -> Self {
|
||||
Self {
|
||||
extent,
|
||||
origin,
|
||||
direction,
|
||||
inverse: direction.map(|d| 1.0 / d),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The kind of the node a pointer names.
|
||||
pub fn kind(pointer: u64) -> u32 {
|
||||
(pointer & 7) as u32
|
||||
}
|
||||
|
||||
/// The byte address of the node `pointer` names, for a descriptor whose
|
||||
/// first two dwords are `word0` and `word1`.
|
||||
pub fn node_address(word0: u32, word1: u32, pointer: u64) -> u64 {
|
||||
let base = (u64::from(word1 & 0xff) << 32 | u64::from(word0)) << 8;
|
||||
base.wrapping_add((pointer >> 3) << 6)
|
||||
}
|
||||
|
||||
/// What the instruction returns for the node at `words` (its first 28
|
||||
/// dwords; a 64-byte node's dwords 16-27 are not read) named by a pointer
|
||||
/// of this `kind`, with box sorting as `sort` says and the triangle return
|
||||
/// mode set.
|
||||
pub fn intersect(words: &[u32; 28], kind: u32, ray: &Ray, sort: bool) -> [u32; 4] {
|
||||
match kind & 7 {
|
||||
4 => boxes(&children(words), &boxes16(words), ray, sort),
|
||||
5 => boxes(&children(words), &boxes32(words), ray, sort),
|
||||
k @ 0..=3 => triangle(&triangle_vertices(words, k), ray).map(f32::to_bits),
|
||||
_ => MISS.map(f32::to_bits),
|
||||
}
|
||||
}
|
||||
|
||||
/// A box node's four child pointers.
|
||||
pub fn children(words: &[u32; 28]) -> [u32; 4] {
|
||||
[words[0], words[1], words[2], words[3]]
|
||||
}
|
||||
|
||||
/// The four boxes of a 16-bit box node: minimum x y z, maximum x y z.
|
||||
pub fn boxes16(words: &[u32; 28]) -> [[f32; 6]; 4] {
|
||||
std::array::from_fn(|b| {
|
||||
std::array::from_fn(|k| {
|
||||
let half = 6 * b + k;
|
||||
half_to_f32((words[4 + half / 2] >> (16 * (half % 2))) as u16)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// The four boxes of a 32-bit box node.
|
||||
pub fn boxes32(words: &[u32; 28]) -> [[f32; 6]; 4] {
|
||||
std::array::from_fn(|b| std::array::from_fn(|k| f32::from_bits(words[4 + 6 * b + k])))
|
||||
}
|
||||
|
||||
/// [`TRIANGLE_VERTICES`] of triangle `k` in four bits each, vertex 0 lowest
|
||||
/// (as the public descriptions of the format give it: 0x210, 0x231, 0x432,
|
||||
/// 0x042).
|
||||
pub fn vertex_map(k: u32) -> u32 {
|
||||
let v = TRIANGLE_VERTICES[(k & 3) as usize];
|
||||
v[0] | v[1] << 4 | v[2] << 8
|
||||
}
|
||||
|
||||
/// The vertices of triangle `k` (0-3) of a triangle node, the first being
|
||||
/// the one neither barycentric weighs, then I's, then J's.
|
||||
pub fn triangle_vertices(words: &[u32; 28], k: u32) -> [[f32; 3]; 3] {
|
||||
let id = words[15] >> (8 * k);
|
||||
let (i, j) = (id & 3, id >> 2 & 3);
|
||||
// An id naming one vertex twice, or a vertex 3, is malformed; it reads
|
||||
// what this arithmetic lands on (a vertex of the node), as the emitted
|
||||
// code does.
|
||||
let first = 3u32.wrapping_sub(i).wrapping_sub(j) & 3;
|
||||
[first, i, j].map(|n| {
|
||||
let vertex = (vertex_map(k) >> (4 * n) & 0xf) as usize;
|
||||
std::array::from_fn(|c| f32::from_bits(words[3 * vertex + c]))
|
||||
})
|
||||
}
|
||||
|
||||
/// The box test: child pointers of the boxes the ray enters, `NONE` for
|
||||
/// the others; sorted by entry distance when `sort`, in child order
|
||||
/// otherwise.
|
||||
pub fn boxes(children: &[u32; 4], boxes: &[[f32; 6]; 4], ray: &Ray, sort: bool) -> [u32; 4] {
|
||||
// An infinite inverse (a direction component of 0) would turn an
|
||||
// origin exactly on a box's face into a NaN. (Maximum then minimum, as
|
||||
// the emitted code: a NaN becomes the lower bound, where `clamp` would
|
||||
// keep it.)
|
||||
#[allow(clippy::manual_clamp)]
|
||||
let inverse = ray.inverse.map(|x| x.max(-f32::MAX).min(f32::MAX));
|
||||
let mut ids = [NONE; 4];
|
||||
let mut distances = [f32::INFINITY; 4];
|
||||
for (n, b) in boxes.iter().enumerate() {
|
||||
let (mut near, mut far) = ([0f32; 3], [0f32; 3]);
|
||||
for a in 0..3 {
|
||||
let low = (b[a] - ray.origin[a]) * inverse[a];
|
||||
let high = (b[3 + a] - ray.origin[a]) * inverse[a];
|
||||
near[a] = low.min(high);
|
||||
far[a] = low.max(high);
|
||||
}
|
||||
let enter = near[0].max(near[1]).max(near[2]);
|
||||
let leave = far[0].min(far[1]).min(far[2]);
|
||||
// A box whose minimum x is NaN is switched off.
|
||||
if !b[0].is_nan() && leave >= enter.max(0.0) && enter < ray.extent {
|
||||
ids[n] = children[n];
|
||||
distances[n] = enter;
|
||||
}
|
||||
}
|
||||
if sort {
|
||||
for (a, b) in [(0, 1), (2, 3), (0, 2), (1, 3), (1, 2)] {
|
||||
if distances[b] < distances[a] {
|
||||
distances.swap(a, b);
|
||||
ids.swap(a, b);
|
||||
}
|
||||
}
|
||||
}
|
||||
ids
|
||||
}
|
||||
|
||||
/// What a triangle the ray misses returns.
|
||||
pub const MISS: [f32; 4] = [f32::INFINITY, 1.0, 0.0, 0.0];
|
||||
|
||||
/// The triangle test: the hit distance's numerator, the denominator, and
|
||||
/// the numerators of the weights of vertices 1 and 2; [`MISS`] otherwise.
|
||||
/// Watertight: the vertices are sheared so the ray runs along its largest
|
||||
/// axis, and the signs of the three edge functions decide, so a ray
|
||||
/// between two triangles that share an edge cannot miss both. Any NaN
|
||||
/// misses, and so does a triangle seen edge-on.
|
||||
pub fn triangle(p: &[[f32; 3]; 3], ray: &Ray) -> [f32; 4] {
|
||||
let d = ray.direction;
|
||||
let size = d.map(f32::abs);
|
||||
// The largest axis, and the other two in an order that keeps the
|
||||
// triangle's winding.
|
||||
let kz = if size[0] >= size[1] {
|
||||
if size[0] >= size[2] { 0 } else { 2 }
|
||||
} else if size[1] >= size[2] {
|
||||
1
|
||||
} else {
|
||||
2
|
||||
};
|
||||
let (mut kx, mut ky) = ((kz + 1) % 3, (kz + 2) % 3);
|
||||
if d[kz] < 0.0 {
|
||||
std::mem::swap(&mut kx, &mut ky);
|
||||
}
|
||||
let sz = ray.inverse[kz];
|
||||
let (sx, sy) = (d[kx] * sz, d[ky] * sz);
|
||||
let sheared = |v: &[f32; 3]| {
|
||||
let r = [
|
||||
v[0] - ray.origin[0],
|
||||
v[1] - ray.origin[1],
|
||||
v[2] - ray.origin[2],
|
||||
];
|
||||
(r[kx] - sx * r[kz], r[ky] - sy * r[kz], sz * r[kz])
|
||||
};
|
||||
let (ax, ay, az) = sheared(&p[0]);
|
||||
let (bx, by, bz) = sheared(&p[1]);
|
||||
let (cx, cy, cz) = sheared(&p[2]);
|
||||
let u = cx * by - cy * bx;
|
||||
let v = ax * cy - ay * cx;
|
||||
let w = bx * ay - by * ax;
|
||||
let behind = u < 0.0 || v < 0.0 || w < 0.0;
|
||||
let before = u > 0.0 || v > 0.0 || w > 0.0;
|
||||
let det = u + (v + w);
|
||||
let t = (u * az + v * bz) + w * cz;
|
||||
let ahead = det > 0.0 && t >= 0.0 || det < 0.0 && t <= 0.0;
|
||||
if !(behind && before) && ahead {
|
||||
[t, det, v, w]
|
||||
} else {
|
||||
MISS
|
||||
}
|
||||
}
|
||||
|
||||
/// A 16-bit float as a 32-bit one (exact).
|
||||
pub fn half_to_f32(h: u16) -> f32 {
|
||||
let sign = u32::from(h >> 15) << 31;
|
||||
let (exponent, mantissa) = (u32::from(h >> 10 & 0x1f), u32::from(h & 0x3ff));
|
||||
let bits = match exponent {
|
||||
0 if mantissa == 0 => sign,
|
||||
0 => {
|
||||
// Subnormal: normalise.
|
||||
let shift = mantissa.leading_zeros() - 21;
|
||||
sign | (113 - shift) << 23 | (mantissa << shift & 0x3ff) << 13
|
||||
}
|
||||
0x1f => sign | 0xff << 23 | mantissa << 13,
|
||||
e => sign | (e + 112) << 23 | mantissa << 13,
|
||||
};
|
||||
f32::from_bits(bits)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The smallest 16-bit float not below `x` (`up`) or not above it.
|
||||
pub(crate) fn f32_to_half(x: f32, up: bool) -> u16 {
|
||||
let mut best: Option<u16> = None;
|
||||
for h in 0..=0xffffu16 {
|
||||
let f = half_to_f32(h);
|
||||
if f.is_nan() || if up { f < x } else { f > x } {
|
||||
continue;
|
||||
}
|
||||
best = match best {
|
||||
Some(b) if (half_to_f32(b) - x).abs() <= (f - x).abs() => Some(b),
|
||||
_ => Some(h),
|
||||
};
|
||||
}
|
||||
best.expect("a half")
|
||||
}
|
||||
|
||||
/// A 32-bit box node.
|
||||
pub(crate) fn box32(children: [u32; 4], boxes: [[f32; 6]; 4]) -> [u32; 28] {
|
||||
let mut w = [0u32; 28];
|
||||
w[..4].copy_from_slice(&children);
|
||||
for (b, bx) in boxes.iter().enumerate() {
|
||||
for (k, x) in bx.iter().enumerate() {
|
||||
w[4 + 6 * b + k] = x.to_bits();
|
||||
}
|
||||
}
|
||||
w
|
||||
}
|
||||
|
||||
/// A 16-bit box node holding `boxes` rounded outward.
|
||||
pub(crate) fn box16(children: [u32; 4], boxes: [[f32; 6]; 4]) -> [u32; 28] {
|
||||
let mut w = [0u32; 28];
|
||||
w[..4].copy_from_slice(&children);
|
||||
for (b, bx) in boxes.iter().enumerate() {
|
||||
for (k, x) in bx.iter().enumerate() {
|
||||
let half = 6 * b + k;
|
||||
let h = if x.is_nan() {
|
||||
0x7e00
|
||||
} else {
|
||||
f32_to_half(*x, k >= 3)
|
||||
};
|
||||
w[4 + half / 2] |= u32::from(h) << (16 * (half % 2));
|
||||
}
|
||||
}
|
||||
w
|
||||
}
|
||||
|
||||
/// A triangle node: up to five vertices, and the dword at byte 60.
|
||||
pub(crate) fn triangles(vertices: &[[f32; 3]], id: u32) -> [u32; 28] {
|
||||
let mut w = [0u32; 28];
|
||||
for (n, v) in vertices.iter().enumerate() {
|
||||
for (c, x) in v.iter().enumerate() {
|
||||
w[3 * n + c] = x.to_bits();
|
||||
}
|
||||
}
|
||||
w[15] = id;
|
||||
w
|
||||
}
|
||||
|
||||
const UNIT: [f32; 6] = [-1.0, -1.0, -1.0, 1.0, 1.0, 1.0];
|
||||
|
||||
fn moved(b: [f32; 6], by: [f32; 3]) -> [f32; 6] {
|
||||
std::array::from_fn(|k| b[k] + by[k % 3])
|
||||
}
|
||||
|
||||
const OFF: [f32; 6] = [f32::NAN; 6];
|
||||
|
||||
#[test]
|
||||
fn node_pointers_name_64_byte_nodes_past_the_descriptors_base() {
|
||||
// The 64-bit form as the title uses it: base 0, the structure's
|
||||
// address folded into the pointer.
|
||||
let structure = 0x12_3456_7800u64;
|
||||
let pointer = (structure >> 8 << 5) + (0x40 >> 3 | 5);
|
||||
assert_eq!(kind(pointer), 5);
|
||||
assert_eq!(node_address(0, BOX_SORT, pointer), structure + 0x40);
|
||||
// The 32-bit form: the base in the descriptor.
|
||||
let word0 = (structure >> 8) as u32;
|
||||
let word1 = (structure >> 40) as u32 | BOX_SORT;
|
||||
assert_eq!(
|
||||
node_address(word0, word1, 0x1000 >> 3 | 4),
|
||||
structure + 0x1000
|
||||
);
|
||||
// A base past 4 GiB of 256-byte units.
|
||||
assert_eq!(node_address(0, 0x8000_0001, 8), (1 << 40) + 64);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn halves_convert_exactly() {
|
||||
assert_eq!(half_to_f32(0x3c00), 1.0);
|
||||
assert_eq!(half_to_f32(0xc000), -2.0);
|
||||
assert_eq!(half_to_f32(0x7c00), f32::INFINITY);
|
||||
assert_eq!(half_to_f32(0x0001), 2f32.powi(-24));
|
||||
assert_eq!(half_to_f32(0x03ff), 1023.0 * 2f32.powi(-24));
|
||||
assert_eq!(half_to_f32(0x7bff), 65504.0);
|
||||
assert!(half_to_f32(0x7e00).is_nan());
|
||||
assert_eq!(half_to_f32(0x8000).to_bits(), 0x8000_0000);
|
||||
// Outward rounding of the test helper.
|
||||
assert!(half_to_f32(f32_to_half(0.1, true)) >= 0.1);
|
||||
assert!(half_to_f32(f32_to_half(0.1, false)) <= 0.1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn boxes_are_returned_nearest_first_and_misses_last() {
|
||||
let children = [0x105, 0x20c, 0x304, 0x400];
|
||||
// Along +x from the origin: boxes at x = 30, 10, (off axis), 20.
|
||||
let node = box32(
|
||||
children,
|
||||
[
|
||||
moved(UNIT, [30.0, 0.0, 0.0]),
|
||||
moved(UNIT, [10.0, 0.0, 0.0]),
|
||||
moved(UNIT, [10.0, 5.0, 0.0]),
|
||||
moved(UNIT, [20.0, 0.0, 0.0]),
|
||||
],
|
||||
);
|
||||
let ray = Ray::new([0.0; 3], [1.0, 0.0, 0.0], 1000.0);
|
||||
assert_eq!(intersect(&node, 5, &ray, true), [0x20c, 0x400, 0x105, NONE]);
|
||||
// Without sorting: child order, the miss in its place.
|
||||
assert_eq!(
|
||||
intersect(&node, 5, &ray, false),
|
||||
[0x105, 0x20c, NONE, 0x400]
|
||||
);
|
||||
// The extent cuts the far ones off (entered at 9, 19, 29).
|
||||
let short = Ray {
|
||||
extent: 19.5,
|
||||
..ray
|
||||
};
|
||||
assert_eq!(
|
||||
intersect(&node, 5, &short, true),
|
||||
[0x20c, 0x400, NONE, NONE]
|
||||
);
|
||||
// An entry exactly at the extent is no hit.
|
||||
let exact = Ray {
|
||||
extent: 19.0,
|
||||
..ray
|
||||
};
|
||||
assert_eq!(intersect(&node, 5, &exact, true), [0x20c, NONE, NONE, NONE]);
|
||||
// Backwards: nothing.
|
||||
let back = Ray::new([0.0; 3], [-1.0, 0.0, 0.0], 1000.0);
|
||||
assert_eq!(intersect(&node, 5, &back, true), [NONE; 4]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_ray_starting_inside_a_box_enters_it_at_its_origin() {
|
||||
let node = box32(
|
||||
[8, 16, NONE, NONE],
|
||||
[UNIT, moved(UNIT, [3.0, 0.0, 0.0]), OFF, OFF],
|
||||
);
|
||||
let ray = Ray::new([0.0; 3], [1.0, 0.0, 0.0], 100.0);
|
||||
// Box 0 is entered at -1 (behind the origin), box 1 at 2.
|
||||
assert_eq!(intersect(&node, 5, &ray, true), [8, 16, NONE, NONE]);
|
||||
// Even with a tiny extent the box around the origin is a hit.
|
||||
let tiny = Ray {
|
||||
extent: 1e-6,
|
||||
..ray
|
||||
};
|
||||
assert_eq!(intersect(&node, 5, &tiny, true), [8, NONE, NONE, NONE]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn axis_aligned_rays_and_origins_on_a_face_make_no_nan() {
|
||||
let node = box32([8, 16, 24, 32], [UNIT, OFF, OFF, OFF]);
|
||||
// Direction components of 0: the inverse is infinite.
|
||||
let ray = Ray::new([-5.0, -1.0, 0.0], [1.0, 0.0, 0.0], 100.0);
|
||||
assert!(ray.inverse[1].is_infinite());
|
||||
// The origin lies in the plane of the box's -y face: (-1 - -1) x inf
|
||||
// would be a NaN; with the inverse held finite it is 0, and the ray
|
||||
// running along the face is inside.
|
||||
assert_eq!(intersect(&node, 5, &ray, true), [8, NONE, NONE, NONE]);
|
||||
// Along the +y face it is outside: the face's plane is left at 0
|
||||
// and the box is entered at 4 (as the public emulation has it).
|
||||
let top = Ray::new([-5.0, 1.0, 0.0], [1.0, 0.0, 0.0], 100.0);
|
||||
assert_eq!(intersect(&node, 5, &top, true), [NONE; 4]);
|
||||
let outside = Ray::new([-5.0, 1.5, 0.0], [1.0, 0.0, 0.0], 100.0);
|
||||
assert_eq!(intersect(&node, 5, &outside, true), [NONE; 4]);
|
||||
// -0 gives -infinity.
|
||||
let minus = Ray::new([-5.0, 0.5, 0.0], [1.0, -0.0, 0.0], 100.0);
|
||||
assert_eq!(minus.inverse[1], f32::NEG_INFINITY);
|
||||
assert_eq!(intersect(&node, 5, &minus, true), [8, NONE, NONE, NONE]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_box_switched_off_and_a_missing_child_return_none() {
|
||||
let node = box32(
|
||||
[8, NONE, 24, 32],
|
||||
[UNIT, UNIT, [f32::NAN, -1.0, -1.0, 1.0, 1.0, 1.0], OFF],
|
||||
);
|
||||
let ray = Ray::new([-5.0, 0.0, 0.0], [1.0, 0.0, 0.0], 100.0);
|
||||
// Child 1 is hit but is not there: its pointer is what "none" is.
|
||||
assert_eq!(intersect(&node, 5, &ray, true), [8, NONE, NONE, NONE]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn equal_distances_keep_child_order() {
|
||||
let node = box32([8, 16, 24, 32], [UNIT; 4]);
|
||||
let ray = Ray::new([-5.0, 0.0, 0.0], [1.0, 0.0, 0.0], 100.0);
|
||||
assert_eq!(intersect(&node, 5, &ray, true), [8, 16, 24, 32]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn half_float_boxes_test_like_their_widened_values() {
|
||||
let boxes = [
|
||||
moved(UNIT, [30.0, 0.1, 0.0]),
|
||||
moved(UNIT, [10.0, 0.0, 0.3]),
|
||||
moved(UNIT, [10.0, 5.0, 0.0]),
|
||||
moved(UNIT, [20.7, 0.0, 0.0]),
|
||||
];
|
||||
let children = [0x105, 0x20c, 0x304, 0x400];
|
||||
let node = box16(children, boxes);
|
||||
let wide = boxes16(&node);
|
||||
for (w, b) in wide.iter().zip(&boxes) {
|
||||
for k in 0..3 {
|
||||
assert!(w[k] <= b[k] && w[3 + k] >= b[3 + k], "rounded outward");
|
||||
}
|
||||
}
|
||||
let ray = Ray::new([0.0; 3], [1.0, 0.0, 0.0], 1000.0);
|
||||
assert_eq!(intersect(&node, 4, &ray, true), [0x20c, 0x400, 0x105, NONE]);
|
||||
assert_eq!(
|
||||
intersect(&node, 4, &ray, true),
|
||||
intersect(&box32(children, wide), 5, &ray, true)
|
||||
);
|
||||
}
|
||||
|
||||
/// The hit a result describes: distance, I, J, front face.
|
||||
fn hit(r: [u32; 4]) -> Option<(f32, f32, f32, bool)> {
|
||||
let [t, det, i, j] = r.map(f32::from_bits);
|
||||
(t != f32::INFINITY).then(|| (t / det, i / det, j / det, det > 0.0))
|
||||
}
|
||||
|
||||
/// Clockwise seen from the origin looking down +z in a left-handed
|
||||
/// system (x right, y up): the front face.
|
||||
const TRIANGLE: [[f32; 3]; 3] = [[0.0, 2.0, 5.0], [2.0, -2.0, 5.0], [-2.0, -2.0, 5.0]];
|
||||
|
||||
#[test]
|
||||
fn a_triangle_returns_distance_and_weights_over_one_denominator() {
|
||||
let node = triangles(&TRIANGLE, 9);
|
||||
let ray = Ray::new([0.0; 3], [0.0, 0.0, 1.0], 100.0);
|
||||
let (t, i, j, front) = hit(intersect(&node, 0, &ray, true)).expect("a hit");
|
||||
assert_eq!(t, 5.0);
|
||||
// (0, 0) = 0.5 v0 + 0.25 v1 + 0.25 v2.
|
||||
assert_eq!((i, j), (0.25, 0.25));
|
||||
assert!(front);
|
||||
// Near vertex 1: I near 1.
|
||||
let ray = Ray::new([1.75, -1.75, 0.0], [0.0, 0.0, 1.0], 100.0);
|
||||
let (_, i, j, _) = hit(intersect(&node, 0, &ray, true)).expect("a hit");
|
||||
assert!(i > 0.85 && j < 0.1, "{i} {j}");
|
||||
// From behind: the same weights, the back face.
|
||||
let ray = Ray::new([0.0, 0.0, 10.0], [0.0, 0.0, -1.0], 100.0);
|
||||
let (t, i, j, front) = hit(intersect(&node, 0, &ray, true)).expect("a hit");
|
||||
assert_eq!((t, i, j, front), (5.0, 0.25, 0.25, false));
|
||||
// An unnormalised direction: the distance is in its units.
|
||||
let ray = Ray::new([0.0; 3], [0.0, 0.0, 4.0], 100.0);
|
||||
assert_eq!(hit(intersect(&node, 0, &ray, true)).unwrap().0, 1.25);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_triangle_is_missed_beside_behind_and_edge_on() {
|
||||
let node = triangles(&TRIANGLE, 9);
|
||||
let miss = MISS.map(f32::to_bits);
|
||||
// Beside it.
|
||||
let ray = Ray::new([3.0, 0.0, 0.0], [0.0, 0.0, 1.0], 100.0);
|
||||
assert_eq!(intersect(&node, 0, &ray, true), miss);
|
||||
// It lies behind the origin.
|
||||
let ray = Ray::new([0.0, 0.0, 6.0], [0.0, 0.0, 1.0], 100.0);
|
||||
assert_eq!(intersect(&node, 0, &ray, true), miss);
|
||||
// In its plane.
|
||||
let ray = Ray::new([-5.0, 0.0, 5.0], [1.0, 0.0, 0.0], 100.0);
|
||||
assert_eq!(intersect(&node, 0, &ray, true), miss);
|
||||
// A triangle with no area.
|
||||
let flat = triangles(&[[0.0, 0.0, 5.0], [1.0, 1.0, 5.0], [2.0, 2.0, 5.0]], 9);
|
||||
let ray = Ray::new([1.0, 1.0, 0.0], [0.0, 0.0, 1.0], 100.0);
|
||||
assert_eq!(intersect(&flat, 0, &ray, true), miss);
|
||||
// A vertex that is not a number, a direction of zero.
|
||||
let nan = triangles(&[[f32::NAN, 2.0, 5.0], TRIANGLE[1], TRIANGLE[2]], 9);
|
||||
let ray = Ray::new([0.0; 3], [0.0, 0.0, 1.0], 100.0);
|
||||
assert_eq!(intersect(&nan, 0, &ray, true), miss);
|
||||
let still = Ray::new([0.0; 3], [0.0; 3], 100.0);
|
||||
assert_eq!(intersect(&node, 0, &still, true), miss);
|
||||
// The extent is the program's to test: a far triangle is a hit.
|
||||
let short = Ray::new([0.0; 3], [0.0, 0.0, 1.0], 1.0);
|
||||
assert!(hit(intersect(&node, 0, &short, true)).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_ray_through_a_shared_edge_misses_neither_triangle() {
|
||||
// Two triangles of a quad sharing the diagonal, wound alike.
|
||||
let quad = [
|
||||
[-1.0, -1.0, 4.0],
|
||||
[-1.0, 1.0, 4.0],
|
||||
[1.0, 1.0, 4.0],
|
||||
[1.0, -1.0, 4.0],
|
||||
];
|
||||
let first = triangles(&[quad[0], quad[1], quad[2]], 9);
|
||||
let second = triangles(&[quad[0], quad[2], quad[3]], 9);
|
||||
// A fan of rays crossing the diagonal, some exactly on it.
|
||||
for n in -40..=40 {
|
||||
let x = n as f32 / 64.0;
|
||||
for (ox, oy) in [(x, x), (x, x + 1.0 / 1024.0), (x + 1.0 / 1024.0, x)] {
|
||||
for d in [[0.0, 0.0, 1.0], [0.125, -0.0625, 1.0], [0.25, 0.5, 2.0]] {
|
||||
// Aim at (ox, oy, 4).
|
||||
let s = 4.0 / d[2];
|
||||
let ray = Ray::new([ox - d[0] * s, oy - d[1] * s, 0.0], d, 100.0);
|
||||
let a = hit(intersect(&first, 0, &ray, true));
|
||||
let b = hit(intersect(&second, 0, &ray, true));
|
||||
assert!(
|
||||
a.is_some() || b.is_some(),
|
||||
"a hole at {ox} {oy} along {d:?}"
|
||||
);
|
||||
for h in [a, b].into_iter().flatten() {
|
||||
assert!((h.0 - s).abs() < 1e-5 && h.3, "{h:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_id_dword_says_which_vertices_the_weights_belong_to() {
|
||||
// What the title's builder does with an input triangle (a, b, c)
|
||||
// and an id byte: a at the vertex neither field names, b at I's,
|
||||
// c at J's.
|
||||
let [a, b, c] = TRIANGLE;
|
||||
let ray = Ray::new([0.5, -0.25, 0.0], [0.0, 0.0, 1.0], 100.0);
|
||||
let plain = intersect(&triangles(&[a, b, c], 9), 0, &ray, true);
|
||||
for (i, j) in [(1u32, 2u32), (2, 0), (0, 1), (2, 1), (0, 2), (1, 0)] {
|
||||
let mut stored = [[0f32; 3]; 3];
|
||||
stored[(3 - i - j) as usize] = a;
|
||||
stored[i as usize] = b;
|
||||
stored[j as usize] = c;
|
||||
let node = triangles(&stored, i | j << 2);
|
||||
assert_eq!(intersect(&node, 0, &ray, true), plain, "I {i} J {j}");
|
||||
}
|
||||
// The higher bits of the byte (opaque and the like) change nothing.
|
||||
let node = triangles(&[a, b, c], 9 | 0x80);
|
||||
assert_eq!(intersect(&node, 0, &ray, true), plain);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn triangles_one_to_three_take_their_vertices_and_their_id_byte() {
|
||||
let [a, b, c] = TRIANGLE;
|
||||
let far = [50.0, 50.0, 50.0];
|
||||
let ray = Ray::new([0.5, -0.25, 0.0], [0.0, 0.0, 1.0], 100.0);
|
||||
let plain = intersect(&triangles(&[a, b, c], 9), 0, &ray, true);
|
||||
for k in 1..4u32 {
|
||||
// Triangle k's vertices 0, 1, 2 are the node's `TRIANGLE_VERTICES[k]`.
|
||||
let mut vertices = [far; 5];
|
||||
let at = TRIANGLE_VERTICES[k as usize];
|
||||
vertices[at[0] as usize] = a;
|
||||
vertices[at[1] as usize] = b;
|
||||
vertices[at[2] as usize] = c;
|
||||
// Triangle 0's byte would be malformed here; only byte k counts.
|
||||
let node = triangles(&vertices, 9 << (8 * k));
|
||||
assert_eq!(intersect(&node, k, &ray, true), plain, "triangle {k}");
|
||||
}
|
||||
// A pair as the title's builder stores it: the second triangle's
|
||||
// own vertex at node vertex 3, named by I.
|
||||
let d = [2.0, 2.0, 5.0];
|
||||
// Input triangles (a, b, c) and (a, d, b): they share a and b.
|
||||
let node = triangles(&[a, b, c, d], 9 | (1 | 2 << 2) << 8);
|
||||
// Triangle 1 = node vertices (1, 3, 2) = (b, d, c) as vertices 0, 1, 2.
|
||||
let got = triangle_vertices(&node, 1);
|
||||
assert_eq!(got, [b, d, c]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instances_and_procedural_nodes_return_a_triangle_miss() {
|
||||
let node = triangles(&TRIANGLE, 9);
|
||||
let ray = Ray::new([0.0; 3], [0.0, 0.0, 1.0], 100.0);
|
||||
for k in [6, 7] {
|
||||
assert_eq!(intersect(&node, k, &ray, true), MISS.map(f32::to_bits));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_largest_axis_and_its_sign_do_not_change_the_answer() {
|
||||
// The same triangle and ray turned so the ray's largest axis is each
|
||||
// of the three, forwards and backwards. Both turns are rotations,
|
||||
// so the facing stays.
|
||||
let turn = |v: [f32; 3], axis: usize, flip: bool| {
|
||||
let mut r = v;
|
||||
for _ in 0..axis {
|
||||
r = [r[2], r[0], r[1]];
|
||||
}
|
||||
if flip {
|
||||
// Half a turn about the axis after the largest one's next.
|
||||
let largest = (2 + axis) % 3;
|
||||
r[largest] = -r[largest];
|
||||
r[(largest + 1) % 3] = -r[(largest + 1) % 3];
|
||||
}
|
||||
r
|
||||
};
|
||||
let ray = Ray::new([0.25, -0.5, 0.0], [0.0625, 0.125, 1.0], 100.0);
|
||||
let base = hit(triangle(&TRIANGLE, &ray).map(f32::to_bits)).expect("a hit");
|
||||
for axis in 0..3 {
|
||||
for flip in [false, true] {
|
||||
let p = TRIANGLE.map(|v| turn(v, axis, flip));
|
||||
let r = Ray::new(
|
||||
turn(ray.origin, axis, flip),
|
||||
turn(ray.direction, axis, flip),
|
||||
100.0,
|
||||
);
|
||||
let h = hit(triangle(&p, &r).map(f32::to_bits)).expect("a hit");
|
||||
assert!((h.0 - base.0).abs() < 1e-5, "{axis} {flip}: {h:?} {base:?}");
|
||||
assert!((h.1 - base.1).abs() < 1e-5 && (h.2 - base.2).abs() < 1e-5);
|
||||
assert_eq!(h.3, base.3, "facing, axis {axis} flip {flip}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
//! The DXBC container: a header, then a table of FourCC-tagged parts.
|
||||
//!
|
||||
//! ```text
|
||||
//! 0x00 "DXBC"
|
||||
//! 0x04 digest[16]
|
||||
//! 0x14 version major u16, minor u16
|
||||
//! 0x18 total size u32
|
||||
//! 0x1C part count u32
|
||||
//! 0x20 part offsets u32[count]
|
||||
//! part: fourcc[4], size u32, data[size]
|
||||
//! ```
|
||||
|
||||
use crate::ShaderError;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub struct FourCC(pub [u8; 4]);
|
||||
|
||||
impl FourCC {
|
||||
pub const DXIL: FourCC = FourCC(*b"DXIL");
|
||||
pub const STAT: FourCC = FourCC(*b"STAT");
|
||||
pub const RTS0: FourCC = FourCC(*b"RTS0");
|
||||
pub const PSV0: FourCC = FourCC(*b"PSV0");
|
||||
pub const ISG1: FourCC = FourCC(*b"ISG1");
|
||||
pub const OSG1: FourCC = FourCC(*b"OSG1");
|
||||
/// Per-primitive outputs of a mesh shader.
|
||||
pub const PSG1: FourCC = FourCC(*b"PSG1");
|
||||
pub const SFI0: FourCC = FourCC(*b"SFI0");
|
||||
pub const HASH: FourCC = FourCC(*b"HASH");
|
||||
pub const ILDB: FourCC = FourCC(*b"ILDB");
|
||||
pub const ILDN: FourCC = FourCC(*b"ILDN");
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for FourCC {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}", self)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for FourCC {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
for &b in &self.0 {
|
||||
let c = if b.is_ascii_graphic() { b as char } else { '.' };
|
||||
write!(f, "{c}")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Part<'a> {
|
||||
pub fourcc: FourCC,
|
||||
/// Offset of the part header within the container.
|
||||
pub offset: usize,
|
||||
pub data: &'a [u8],
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Container<'a> {
|
||||
pub digest: [u8; 16],
|
||||
pub version: (u16, u16),
|
||||
pub parts: Vec<Part<'a>>,
|
||||
}
|
||||
|
||||
const HEADER_SIZE: usize = 0x20;
|
||||
const MAX_PARTS: usize = 256;
|
||||
|
||||
impl<'a> Container<'a> {
|
||||
pub fn parse(data: &'a [u8]) -> Result<Self, ShaderError> {
|
||||
if data.len() < HEADER_SIZE || &data[0..4] != b"DXBC" {
|
||||
return Err(ShaderError::NotDxbc);
|
||||
}
|
||||
let digest = data[4..20].try_into().expect("16 bytes");
|
||||
let version = (u16_at(data, 0x14)?, u16_at(data, 0x16)?);
|
||||
let total = u32_at(data, 0x18)? as usize;
|
||||
if total > data.len() || total < HEADER_SIZE {
|
||||
return Err(ShaderError::Malformed("container size disagrees with data"));
|
||||
}
|
||||
let data = &data[..total];
|
||||
let count = u32_at(data, 0x1C)? as usize;
|
||||
if count > MAX_PARTS {
|
||||
return Err(ShaderError::Malformed("implausible part count"));
|
||||
}
|
||||
let mut parts = Vec::with_capacity(count);
|
||||
for i in 0..count {
|
||||
let offset = u32_at(data, HEADER_SIZE + 4 * i)? as usize;
|
||||
let fourcc = FourCC(
|
||||
data.get(offset..offset + 4)
|
||||
.ok_or(ShaderError::Malformed("part header out of bounds"))?
|
||||
.try_into()
|
||||
.expect("4 bytes"),
|
||||
);
|
||||
let size = u32_at(data, offset + 4)? as usize;
|
||||
let body = data
|
||||
.get(offset + 8..offset + 8 + size)
|
||||
.ok_or(ShaderError::Malformed("part data out of bounds"))?;
|
||||
parts.push(Part {
|
||||
fourcc,
|
||||
offset,
|
||||
data: body,
|
||||
});
|
||||
}
|
||||
Ok(Container {
|
||||
digest,
|
||||
version,
|
||||
parts,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn part(&self, fourcc: FourCC) -> Option<&Part<'a>> {
|
||||
self.parts.iter().find(|p| p.fourcc == fourcc)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn u16_at(data: &[u8], at: usize) -> Result<u16, ShaderError> {
|
||||
data.get(at..at + 2)
|
||||
.map(|b| u16::from_le_bytes(b.try_into().expect("2 bytes")))
|
||||
.ok_or(ShaderError::Malformed("truncated"))
|
||||
}
|
||||
|
||||
pub(crate) fn u32_at(data: &[u8], at: usize) -> Result<u32, ShaderError> {
|
||||
data.get(at..at + 4)
|
||||
.map(|b| u32::from_le_bytes(b.try_into().expect("4 bytes")))
|
||||
.ok_or(ShaderError::Malformed("truncated"))
|
||||
}
|
||||
|
||||
pub(crate) fn u64_at(data: &[u8], at: usize) -> Result<u64, ShaderError> {
|
||||
data.get(at..at + 8)
|
||||
.map(|b| u64::from_le_bytes(b.try_into().expect("8 bytes")))
|
||||
.ok_or(ShaderError::Malformed("truncated"))
|
||||
}
|
||||
|
||||
/// Builds a container from parts (test helper).
|
||||
#[cfg(test)]
|
||||
pub fn build(parts: &[(FourCC, &[u8])]) -> Vec<u8> {
|
||||
let table = HEADER_SIZE + 4 * parts.len();
|
||||
let total = table + parts.iter().map(|(_, d)| 8 + d.len()).sum::<usize>();
|
||||
let mut out = Vec::with_capacity(total);
|
||||
out.extend_from_slice(b"DXBC");
|
||||
out.extend_from_slice(&[0; 16]);
|
||||
out.extend_from_slice(&1u16.to_le_bytes());
|
||||
out.extend_from_slice(&0u16.to_le_bytes());
|
||||
out.extend_from_slice(&(total as u32).to_le_bytes());
|
||||
out.extend_from_slice(&(parts.len() as u32).to_le_bytes());
|
||||
let mut offset = table;
|
||||
for (_, d) in parts {
|
||||
out.extend_from_slice(&(offset as u32).to_le_bytes());
|
||||
offset += 8 + d.len();
|
||||
}
|
||||
for (fourcc, d) in parts {
|
||||
out.extend_from_slice(&fourcc.0);
|
||||
out.extend_from_slice(&(d.len() as u32).to_le_bytes());
|
||||
out.extend_from_slice(d);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn round_trips_parts() {
|
||||
let bytes = build(&[(FourCC::SFI0, &[1, 2, 3, 4]), (FourCC::HASH, &[9; 20])]);
|
||||
let c = Container::parse(&bytes).unwrap();
|
||||
assert_eq!(c.parts.len(), 2);
|
||||
assert_eq!(c.part(FourCC::SFI0).unwrap().data, &[1, 2, 3, 4]);
|
||||
assert_eq!(c.part(FourCC::HASH).unwrap().data.len(), 20);
|
||||
assert!(c.part(FourCC::DXIL).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_bad_input() {
|
||||
assert_eq!(Container::parse(b"nope").unwrap_err(), ShaderError::NotDxbc);
|
||||
let mut bytes = build(&[(FourCC::SFI0, &[0; 8])]);
|
||||
let last = bytes.len() - 1;
|
||||
bytes[0x20] = 0xFF; // corrupt the first part offset
|
||||
assert!(Container::parse(&bytes).is_err());
|
||||
bytes.truncate(last);
|
||||
assert!(Container::parse(&bytes).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
//! The DXIL program inside a container's `DXIL` (or `STAT`) part.
|
||||
//!
|
||||
//! ```text
|
||||
//! 0x00 program version u32 (kind << 16 | major << 4 | minor)
|
||||
//! 0x04 size in dwords u32
|
||||
//! 0x08 "DXIL" <- bitcode offset is relative to here
|
||||
//! 0x0C dxil version u32
|
||||
//! 0x10 bitcode offset u32 (16 in standard PC DXIL)
|
||||
//! 0x14 bitcode size u32
|
||||
//! ```
|
||||
|
||||
use crate::ShaderError;
|
||||
use crate::dxbc::u32_at;
|
||||
|
||||
const LLVM_BITCODE_MAGIC: [u8; 4] = [0x42, 0x43, 0xC0, 0xDE];
|
||||
#[cfg(test)]
|
||||
const STANDARD_BITCODE_OFFSET: u32 = 16;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ShaderKind {
|
||||
Pixel,
|
||||
Vertex,
|
||||
Geometry,
|
||||
Hull,
|
||||
Domain,
|
||||
Compute,
|
||||
Library,
|
||||
RayGeneration,
|
||||
Intersection,
|
||||
AnyHit,
|
||||
ClosestHit,
|
||||
Miss,
|
||||
Callable,
|
||||
Mesh,
|
||||
Amplification,
|
||||
Node,
|
||||
Unknown(u16),
|
||||
}
|
||||
|
||||
impl ShaderKind {
|
||||
fn from_raw(v: u16) -> Self {
|
||||
use ShaderKind::*;
|
||||
match v {
|
||||
0 => Pixel,
|
||||
1 => Vertex,
|
||||
2 => Geometry,
|
||||
3 => Hull,
|
||||
4 => Domain,
|
||||
5 => Compute,
|
||||
6 => Library,
|
||||
7 => RayGeneration,
|
||||
8 => Intersection,
|
||||
9 => AnyHit,
|
||||
10 => ClosestHit,
|
||||
11 => Miss,
|
||||
12 => Callable,
|
||||
13 => Mesh,
|
||||
14 => Amplification,
|
||||
15 => Node,
|
||||
other => Unknown(other),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct DxilProgram<'a> {
|
||||
pub kind: ShaderKind,
|
||||
pub shader_model: (u8, u8),
|
||||
pub dxil_version: u32,
|
||||
/// LLVM bitcode (starts with `BC C0 DE`).
|
||||
pub bitcode: &'a [u8],
|
||||
/// Bytes between the bitcode header and the bitcode. Empty on PC.
|
||||
pub prefix: &'a [u8],
|
||||
/// Bytes after the bitcode, up to the program size. Empty on PC.
|
||||
pub trailer: &'a [u8],
|
||||
}
|
||||
|
||||
/// Xbox additions recognised around the bitcode.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub struct XboxExtras {
|
||||
/// The prefix starts with an `XDAT` table.
|
||||
pub xdat: bool,
|
||||
/// The trailer contains an `xbop` blob (compiler options).
|
||||
pub xbop: bool,
|
||||
}
|
||||
|
||||
impl<'a> DxilProgram<'a> {
|
||||
pub fn parse(part: &'a [u8]) -> Result<Self, ShaderError> {
|
||||
let version = u32_at(part, 0)?;
|
||||
let size = (u32_at(part, 4)? as usize)
|
||||
.checked_mul(4)
|
||||
.filter(|&s| s <= part.len() && s >= 24)
|
||||
.ok_or(ShaderError::Malformed(
|
||||
"program size disagrees with part size",
|
||||
))?;
|
||||
let part = &part[..size];
|
||||
if part.get(8..12) != Some(b"DXIL") {
|
||||
return Err(ShaderError::Malformed("missing DXIL magic"));
|
||||
}
|
||||
let dxil_version = u32_at(part, 12)?;
|
||||
let offset = u32_at(part, 16)?;
|
||||
let len = u32_at(part, 20)? as usize;
|
||||
let start = 8 + offset as usize;
|
||||
let bitcode = part
|
||||
.get(start..start + len)
|
||||
.ok_or(ShaderError::Malformed("bitcode out of bounds"))?;
|
||||
if bitcode.get(0..4) != Some(&LLVM_BITCODE_MAGIC) {
|
||||
return Err(ShaderError::Malformed("bitcode lacks LLVM magic"));
|
||||
}
|
||||
let prefix = part
|
||||
.get(24..start)
|
||||
.ok_or(ShaderError::Malformed("bitcode offset too small"))?;
|
||||
Ok(DxilProgram {
|
||||
kind: ShaderKind::from_raw((version >> 16) as u16),
|
||||
shader_model: (((version >> 4) & 0xF) as u8, (version & 0xF) as u8),
|
||||
dxil_version,
|
||||
bitcode,
|
||||
prefix,
|
||||
trailer: &part[start + len..],
|
||||
})
|
||||
}
|
||||
|
||||
/// True for a program laid out exactly like PC DXIL.
|
||||
pub fn is_standard_layout(&self) -> bool {
|
||||
self.prefix.is_empty() && self.trailer.is_empty()
|
||||
}
|
||||
|
||||
pub fn xbox_extras(&self) -> XboxExtras {
|
||||
XboxExtras {
|
||||
xdat: self.prefix.starts_with(b"XDAT"),
|
||||
xbop: self.trailer.windows(4).any(|w| w == b"xbop"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds a standard PC-layout program around `bitcode` (test helper).
|
||||
#[cfg(test)]
|
||||
pub fn build_standard(kind: u16, sm: (u8, u8), dxil_version: u32, bitcode: &[u8]) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
let version = (u32::from(kind) << 16) | (u32::from(sm.0) << 4) | u32::from(sm.1);
|
||||
let padded = bitcode.len().next_multiple_of(4);
|
||||
let size_dwords = (24 + padded) / 4;
|
||||
out.extend_from_slice(&version.to_le_bytes());
|
||||
out.extend_from_slice(&(size_dwords as u32).to_le_bytes());
|
||||
out.extend_from_slice(b"DXIL");
|
||||
out.extend_from_slice(&dxil_version.to_le_bytes());
|
||||
out.extend_from_slice(&STANDARD_BITCODE_OFFSET.to_le_bytes());
|
||||
out.extend_from_slice(&(bitcode.len() as u32).to_le_bytes());
|
||||
out.extend_from_slice(bitcode);
|
||||
out.resize(24 + padded, 0);
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn fake_bitcode() -> Vec<u8> {
|
||||
let mut b = LLVM_BITCODE_MAGIC.to_vec();
|
||||
b.extend_from_slice(&[0xAA; 12]);
|
||||
b
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_standard_layout() {
|
||||
let bytes = build_standard(0, (6, 0), 0x100, &fake_bitcode());
|
||||
let p = DxilProgram::parse(&bytes).unwrap();
|
||||
assert_eq!(p.kind, ShaderKind::Pixel);
|
||||
assert_eq!(p.shader_model, (6, 0));
|
||||
assert!(p.is_standard_layout());
|
||||
assert_eq!(p.xbox_extras(), XboxExtras::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detects_xbox_layout() {
|
||||
// Xbox layout: XDAT table before the bitcode, xbop blob after it.
|
||||
let bitcode = fake_bitcode();
|
||||
let xdat = b"XDAT\x01\x00\x00\x00";
|
||||
let trailer = b"xbop\x02\x00\x00\x00";
|
||||
let mut bytes = Vec::new();
|
||||
let size = 24 + xdat.len() + bitcode.len() + trailer.len();
|
||||
bytes.extend_from_slice(&((5u32 << 16) | 0x65).to_le_bytes()); // cs_6_5
|
||||
bytes.extend_from_slice(&((size / 4) as u32).to_le_bytes());
|
||||
bytes.extend_from_slice(b"DXIL");
|
||||
bytes.extend_from_slice(&0x105u32.to_le_bytes());
|
||||
bytes.extend_from_slice(&(16 + xdat.len() as u32).to_le_bytes());
|
||||
bytes.extend_from_slice(&(bitcode.len() as u32).to_le_bytes());
|
||||
bytes.extend_from_slice(xdat);
|
||||
bytes.extend_from_slice(&bitcode);
|
||||
bytes.extend_from_slice(trailer);
|
||||
|
||||
let p = DxilProgram::parse(&bytes).unwrap();
|
||||
assert_eq!(p.kind, ShaderKind::Compute);
|
||||
assert_eq!(p.shader_model, (6, 5));
|
||||
assert!(!p.is_standard_layout());
|
||||
assert_eq!(
|
||||
p.xbox_extras(),
|
||||
XboxExtras {
|
||||
xdat: true,
|
||||
xbop: true
|
||||
}
|
||||
);
|
||||
assert_eq!(p.bitcode, &bitcode[..]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_missing_bitcode_magic() {
|
||||
let bytes = build_standard(0, (6, 0), 0x100, &[0u8; 16]);
|
||||
assert!(DxilProgram::parse(&bytes).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// BetterXen addition to the vendored victory-shader crate (see ../../UPSTREAM.md): a public
|
||||
// entry point for a raw compute program, with the same stages `translate` runs for a container.
|
||||
|
||||
use super::{HostShader, lower};
|
||||
use crate::native::{HwStage, NativeProgram};
|
||||
use crate::{ShaderError, io, resource, spill, structure};
|
||||
|
||||
/// Translates a compute program that is already a [`NativeProgram`] (machine code plus its
|
||||
/// root layout) instead of one stored in a console shader container. Only the compute stage is
|
||||
/// accepted: graphics stages need signatures that only a container carries.
|
||||
pub fn translate_native(native: &NativeProgram) -> Result<HostShader, ShaderError> {
|
||||
if native.stage != HwStage::Cs {
|
||||
return Err(ShaderError::Unsupported {
|
||||
offset: 0,
|
||||
what: "translate_native takes compute programs only",
|
||||
});
|
||||
}
|
||||
// (what an earlier program's lowering on this thread left behind)
|
||||
lower::take_needs();
|
||||
let p = spill::build(native)?;
|
||||
let st = structure::structure(&p);
|
||||
let res = resource::track(&p, &native.layout, native.stage, st.as_ref().ok())?;
|
||||
let io = io::raise(&p, native)?;
|
||||
let st = st?;
|
||||
let lowered = lower::lower(&lower::Parts {
|
||||
native,
|
||||
p: &p,
|
||||
st: &st,
|
||||
io: &io,
|
||||
res: &res,
|
||||
inputs: Vec::new(),
|
||||
outputs: Vec::new(),
|
||||
prims: Vec::new(),
|
||||
mesh_stride: 0,
|
||||
})?;
|
||||
Ok(HostShader {
|
||||
stage: native.stage,
|
||||
dxil: lowered.dxil,
|
||||
user_data: lowered.user_data,
|
||||
static_samplers: super::static_samplers(&lowered.samplers, lowered.cmp_samplers),
|
||||
samplers: lowered.samplers,
|
||||
root_cbvs: lowered.root_cbvs,
|
||||
root_srvs: lowered.root_srvs,
|
||||
root_uavs: lowered.root_uavs,
|
||||
root_indexed_views: res.root_indexed_views,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,491 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// BetterXen tests for the vendored victory-shader crate (see ../../UPSTREAM.md).
|
||||
//
|
||||
// BetterXen's own synthetic gfx1030 Wave32 fixtures (`fixtures/rdna2/*.bin`, original, assembled
|
||||
// with LLVM's llvm-mc) are translated to DXIL by the vendored recompiler. Their expected output
|
||||
// words come from `fixtures/manifest.toml`, derived by hand there and checked by BetterXen's own
|
||||
// independent reference; nothing in this file derives an expectation from the recompiler.
|
||||
//
|
||||
// Fixture ABI (docs/interfaces.md): v0 = grid index, V# of the input buffer in s[0:3], of the
|
||||
// output buffer in s[4:7]. The vendored recompiler instead gets descriptors from a table, so
|
||||
// the program is wrapped in a prologue that loads both from a descriptor table into s[0:3] and
|
||||
// s[4:7] and then continues into the fixture's code unchanged.
|
||||
|
||||
use super::translate_native;
|
||||
use crate::native::{
|
||||
ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource,
|
||||
};
|
||||
|
||||
const MANIFEST: &str = include_str!("../../../../fixtures/manifest.toml");
|
||||
|
||||
/// Fixtures that bind an input and an output buffer and have expected words in the manifest.
|
||||
/// Keyed by the file name in the manifest's `path`.
|
||||
const BINARIES: &[(&str, &[u8])] = &[
|
||||
("add.bin", include_bytes!("../../../../fixtures/rdna2/add.bin")),
|
||||
("float-exact.bin", include_bytes!("../../../../fixtures/rdna2/float-exact.bin")),
|
||||
("bitwise-branch.bin", include_bytes!("../../../../fixtures/rdna2/bitwise-branch.bin")),
|
||||
("or.bin", include_bytes!("../../../../fixtures/rdna2/or.bin")),
|
||||
("shifts.bin", include_bytes!("../../../../fixtures/rdna2/shifts.bin")),
|
||||
("ashr.bin", include_bytes!("../../../../fixtures/rdna2/ashr.bin")),
|
||||
];
|
||||
|
||||
struct Fixture {
|
||||
id: String,
|
||||
code: &'static [u8],
|
||||
input: Vec<u32>,
|
||||
expected: Vec<u32>,
|
||||
}
|
||||
|
||||
fn words(line: &str) -> Vec<u32> {
|
||||
line.trim()
|
||||
.trim_start_matches('[')
|
||||
.trim_end_matches(']')
|
||||
.split(',')
|
||||
.filter(|t| !t.trim().is_empty())
|
||||
.map(|t| t.trim().parse().expect("a decimal word"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Fixtures with input and expected words in the manifest. A fixture the manifest lists with
|
||||
/// expected words but that is not embedded above fails the test instead of being skipped.
|
||||
fn fixtures() -> Vec<Fixture> {
|
||||
let mut out = Vec::new();
|
||||
for block in MANIFEST.split("[[fixture]]").skip(1) {
|
||||
let get = |key: &str| {
|
||||
block
|
||||
.lines()
|
||||
.find_map(|l| l.strip_prefix(&format!("{key} = ")))
|
||||
.map(str::to_owned)
|
||||
};
|
||||
let (Some(input), Some(expected)) = (get("input"), get("expected")) else { continue };
|
||||
let (input, expected) = (words(&input), words(&expected));
|
||||
if input.is_empty() || expected.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let id = get("id").unwrap().trim_matches('"').to_owned();
|
||||
let path = get("path").unwrap().trim_matches('"').to_owned();
|
||||
let name = path.rsplit('/').next().unwrap();
|
||||
let code = BINARIES
|
||||
.iter()
|
||||
.find(|(n, _)| *n == name)
|
||||
.unwrap_or_else(|| panic!("fixture {id} ({name}) is in the manifest but not embedded"))
|
||||
.1;
|
||||
out.push(Fixture { id, code, input, expected });
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `s_mov_b32 sdst, 0` (inline constant 0 is source 0x80).
|
||||
const fn s_mov_b32_zero(sdst: u32) -> u32 {
|
||||
0xBE80_0000 | sdst << 16 | 0x03 << 8 | 0x80
|
||||
}
|
||||
|
||||
/// SMEM `s_load_dwordx4 s[dst:dst+3], s[base:base+1], byte_offset` (soffset = null).
|
||||
const fn s_load_dwordx4(dst: u32, base: u32, byte_offset: u32) -> [u32; 2] {
|
||||
[0x3D << 26 | 0x02 << 18 | dst << 6 | base >> 1, 125 << 25 | byte_offset]
|
||||
}
|
||||
|
||||
/// `s_waitcnt lgkmcnt(0)` with the other counters left alone.
|
||||
const S_WAITCNT_LGKM0: u32 = 0xBF8C_C07F;
|
||||
|
||||
/// Wraps a fixture so its descriptors arrive through a descriptor table. The table's two
|
||||
/// 32-byte slots hold the input SRV (heap index 0) and the output UAV (heap index 1).
|
||||
fn program(code: &[u8], threads: u32) -> NativeProgram {
|
||||
let mut w: Vec<u32> = Vec::new();
|
||||
w.push(s_mov_b32_zero(9)); // upper half of the table address; the lower half is user data s8
|
||||
w.extend(s_load_dwordx4(0, 8, 0x00)); // input V# -> s[0:3]
|
||||
w.extend(s_load_dwordx4(4, 8, 0x20)); // output V# -> s[4:7]
|
||||
w.push(S_WAITCNT_LGKM0);
|
||||
let mut bytes: Vec<u8> = w.iter().flat_map(|x| x.to_le_bytes()).collect();
|
||||
bytes.extend_from_slice(code);
|
||||
NativeProgram {
|
||||
stage: HwStage::Cs,
|
||||
wave64: false,
|
||||
vgprs: 32,
|
||||
layout: vec![RootParam {
|
||||
root: RootType::Table,
|
||||
table_offset_dwords: 0,
|
||||
sgprs: 1,
|
||||
base_register: 0,
|
||||
user_data: 8,
|
||||
slot: 0,
|
||||
}],
|
||||
used: vec![
|
||||
UsedResource {
|
||||
kind: ResourceType::Srv,
|
||||
root: RootType::Table,
|
||||
table_offset_dwords: 0,
|
||||
lower_bound: 0,
|
||||
stride: 4, // 4-byte elements, as the fixtures index them (idxen)
|
||||
dwords: 4,
|
||||
user_data: 8,
|
||||
slot: 0,
|
||||
},
|
||||
UsedResource {
|
||||
kind: ResourceType::Uav,
|
||||
root: RootType::Table,
|
||||
table_offset_dwords: 8,
|
||||
lower_bound: 0,
|
||||
stride: 4, // 4-byte elements, as the fixtures index them (idxen)
|
||||
dwords: 4,
|
||||
user_data: 8,
|
||||
slot: 0,
|
||||
},
|
||||
],
|
||||
io: StageIo::Cs(ComputeIo { rsrc2: 9 << 1, threads: [threads, 1, 1] }),
|
||||
code: bytes,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_embedded_fixture_is_listed_in_the_manifest() {
|
||||
let listed = fixtures();
|
||||
assert_eq!(listed.len(), BINARIES.len(), "embedded list and manifest disagree");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fixtures_translate_to_a_dxil_container() {
|
||||
for f in fixtures() {
|
||||
assert!(!f.expected.is_empty(), "{}: no expected words", f.id);
|
||||
let native = program(f.code, f.input.len() as u32);
|
||||
let shader = translate_native(&native)
|
||||
.unwrap_or_else(|e| panic!("{}: translate_native failed: {e}", f.id));
|
||||
assert_eq!(&shader.dxil[..4], b"DXBC", "{}: not a DXBC/DXIL container", f.id);
|
||||
assert!(shader.dxil.len() > 100, "{}: container too small", f.id);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
mod on_the_gpu {
|
||||
use super::*;
|
||||
use crate::emit::host::{Dispatch, Host, Root, Stride, View};
|
||||
|
||||
fn run_on_gpu(host: &Host, f: &Fixture) -> Vec<u32> {
|
||||
let shader = translate_native(&program(f.code, f.input.len() as u32)).expect("translate");
|
||||
let (root, pso) = host.compute_pipeline(&shader).expect("compute pipeline");
|
||||
// The table parameter's value is the heap offset: both views start at heap index 0.
|
||||
let ud = vec![0u32; shader.user_data_dwords().max(1) as usize];
|
||||
let out = host
|
||||
.dispatch(
|
||||
&root,
|
||||
&pso,
|
||||
&Dispatch {
|
||||
roots: vec![(0, Root::Constants(ud))],
|
||||
views: &[
|
||||
View::Buffer { data: &f.input, stride: Stride::Raw },
|
||||
View::RawUav(f.input.len() as u32),
|
||||
],
|
||||
samplers: &[],
|
||||
groups: [1, 1, 1],
|
||||
},
|
||||
)
|
||||
.unwrap_or_else(|e| panic!("{}: dispatch failed: {e}", f.id));
|
||||
out[0][..f.expected.len()].to_vec()
|
||||
}
|
||||
|
||||
/// Runs each fixture on the default D3D12 device and compares every output word with the
|
||||
/// manifest. If no suitable device exists the test fails loudly rather than passing: a
|
||||
/// skipped run is not GPU verification.
|
||||
#[test]
|
||||
fn fixtures_on_the_default_d3d12_device_match_the_manifest() {
|
||||
let _one = crate::emit::valu_tests::ONE_AT_A_TIME
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner());
|
||||
let host = Host::hardware().expect("no SM 6.6 D3D12 hardware device: not verified");
|
||||
let mut ran = 0;
|
||||
for f in fixtures() {
|
||||
let got = run_on_gpu(&host, &f);
|
||||
assert_eq!(got, f.expected, "{}: output words differ from the manifest", f.id);
|
||||
eprintln!("betterxen fixture {} ran on the GPU and matched the manifest", f.id);
|
||||
ran += 1;
|
||||
}
|
||||
assert_eq!(ran, fixtures().len());
|
||||
}
|
||||
|
||||
/// Negative control: the comparison above must be able to fail. A copy of each expected
|
||||
/// output with one bit flipped must not equal what the GPU produced, and the output must
|
||||
/// not be the untouched zeroed buffer or an echo of the input (unless the manifest says so).
|
||||
#[test]
|
||||
fn a_wrong_expectation_is_detected() {
|
||||
let _one = crate::emit::valu_tests::ONE_AT_A_TIME
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner());
|
||||
let host = Host::hardware().expect("no SM 6.6 D3D12 hardware device: not verified");
|
||||
for f in fixtures() {
|
||||
let got = run_on_gpu(&host, &f);
|
||||
let mut wrong = f.expected.clone();
|
||||
wrong[0] ^= 1;
|
||||
assert_ne!(got, wrong, "{}: a flipped expectation was accepted", f.id);
|
||||
assert!(got.iter().any(|&w| w != 0) || f.expected.iter().all(|&w| w == 0), "{}: output is the zeroed buffer", f.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- f64 whole-wave sum (research/shader-wave-semantics) --------------------------------------
|
||||
//
|
||||
// The console's whole-wave f64 sum, as `valu_tests::whole_wave_f64_sum_and_cvt_f32_f64` builds it,
|
||||
// but storing both words of the f64 result instead of converting to f32, so all 64 bits are
|
||||
// compared. Upstream lowered it to a native `double` wave operation, which D3DMetal does not run
|
||||
// (docs/research/shader-wave-semantics.md); it is now done with the integer fp64 add.
|
||||
// Expected results come from a CPU model of the balanced tree over the lanes in their order
|
||||
// (lanes 2k and 2k+1, then pairs, ...) with the CPU's own f64 additions, `+0.0` for lanes that
|
||||
// are not launched; nothing is taken from the recompiler.
|
||||
|
||||
const fn vop1(op: u16, vdst: u8, src0: u16) -> u32 {
|
||||
0x7E00_0000 | (vdst as u32) << 17 | (op as u32) << 9 | (src0 as u32 & 0x1FF)
|
||||
}
|
||||
|
||||
const fn vop3(op: u16, vdst: u8, src0: u16, src1: u16, src2: u16) -> [u32; 2] {
|
||||
[
|
||||
0x35 << 26 | (op as u32 & 0x3FF) << 16 | vdst as u32,
|
||||
(src0 as u32 & 0x1FF) | (src1 as u32 & 0x1FF) << 9 | (src2 as u32 & 0x1FF) << 18,
|
||||
]
|
||||
}
|
||||
|
||||
const fn buffer_store_dword(vdata: u8, srsrc: u8, byte_off: u16) -> [u32; 2] {
|
||||
[
|
||||
0x38 << 26 | 0x1C << 18 | (byte_off as u32 & 0xFFF),
|
||||
0x80 << 24 | ((srsrc as u32 >> 2) & 0x1F) << 16 | (vdata as u32) << 8,
|
||||
]
|
||||
}
|
||||
|
||||
/// A one-group compute program over `threads` threads: each lane's f64 is root constants
|
||||
/// `(s0, s1)`; the program sums the wave and stores the sum's low then high word to the UAV.
|
||||
fn f64_wave_sum_program(threads: u32) -> NativeProgram {
|
||||
let v_mov_dpp8 = |vdst: u8, vsrc: u8, sel: u32| [vop1(0x001, vdst, 0xE9), vsrc as u32 | (sel << 8)];
|
||||
let v_mov_row_mirror = |vdst: u8, vsrc: u8| {
|
||||
[
|
||||
vop1(0x001, vdst, 0xFA),
|
||||
vsrc as u32 | (0x140 << 8) | (1 << 19) | (0xF << 24) | (0xF << 28),
|
||||
]
|
||||
};
|
||||
let mut w: Vec<u32> = Vec::new();
|
||||
w.push(0xBE80_0000 | 5 << 16 | 0x03 << 8 | 0x80); // s_mov_b32 s5, 0 (table address high)
|
||||
w.extend_from_slice(&[0x3D << 26 | 0x02 << 18 | 8 << 6 | (4 >> 1), 125 << 25]); // s_load_dwordx4 s[8:11], s[4:5], 0
|
||||
w.push(vop1(0x001, 6, 0)); // v_mov_b32 v6, s0
|
||||
w.push(vop1(0x001, 7, 1)); // v_mov_b32 v7, s1
|
||||
w.push(0xBE80_0000 | 12 << 16 | 0x3D << 8 | 0xC1); // s_or_saveexec_b32 s12, -1
|
||||
w.extend_from_slice(&vop3(0x101, 2, 0x80, 256 + 6, 12));
|
||||
w.extend_from_slice(&vop3(0x101, 3, 0x80, 256 + 7, 12));
|
||||
for sel in [14570689u32, 9658386, 2340] {
|
||||
w.extend_from_slice(&v_mov_dpp8(4, 2, sel));
|
||||
w.extend_from_slice(&v_mov_dpp8(5, 3, sel));
|
||||
w.extend_from_slice(&vop3(0x164, 2, 256 + 4, 256 + 2, 0)); // v_add_f64
|
||||
}
|
||||
w.extend_from_slice(&v_mov_row_mirror(4, 2));
|
||||
w.extend_from_slice(&v_mov_row_mirror(5, 3));
|
||||
w.extend_from_slice(&vop3(0x164, 2, 256 + 4, 256 + 2, 0));
|
||||
w.extend_from_slice(&vop3(0x378, 4, 256 + 2, 0x80, 0x80)); // v_permlanex16_b32
|
||||
w.extend_from_slice(&vop3(0x378, 5, 256 + 3, 0x80, 0x80));
|
||||
w.extend_from_slice(&vop3(0x164, 2, 256 + 4, 256 + 2, 0));
|
||||
w.extend_from_slice(&vop3(0x360, 14, 256 + 2, 0x80, 0)); // v_readlane_b32 s14, v2, 0
|
||||
w.extend_from_slice(&vop3(0x360, 15, 256 + 3, 0x80, 0)); // v_readlane_b32 s15, v3, 0
|
||||
w.push(0xBE80_0000 | 16 << 16 | 0x03 << 8 | 14); // s_mov_b32 s16, s14
|
||||
w.push(0xBE80_0000 | 17 << 16 | 0x03 << 8 | 15); // s_mov_b32 s17, s15
|
||||
w.push(0xBE80_0000 | 126 << 16 | 0x03 << 8 | 12); // s_mov_b32 exec_lo, s12
|
||||
w.push(vop1(0x001, 0, 16)); // v_mov_b32 v0, s16 (low word)
|
||||
w.extend_from_slice(&buffer_store_dword(0, 8, 0));
|
||||
w.push(vop1(0x001, 0, 17)); // v_mov_b32 v0, s17 (high word)
|
||||
w.extend_from_slice(&buffer_store_dword(0, 8, 4));
|
||||
w.push(0xBF81_0000); // s_endpgm
|
||||
let code: Vec<u8> = w.iter().flat_map(|x| x.to_le_bytes()).collect();
|
||||
let param = |root, sgprs, user_data, slot| RootParam {
|
||||
root,
|
||||
table_offset_dwords: 0,
|
||||
sgprs,
|
||||
base_register: 0,
|
||||
user_data,
|
||||
slot,
|
||||
};
|
||||
NativeProgram {
|
||||
stage: HwStage::Cs,
|
||||
wave64: false,
|
||||
vgprs: 12,
|
||||
layout: vec![param(RootType::Constants, 4, 0, 0), param(RootType::Table, 1, 4, 1)],
|
||||
used: vec![UsedResource {
|
||||
kind: ResourceType::Uav,
|
||||
root: RootType::Table,
|
||||
table_offset_dwords: 0,
|
||||
lower_bound: 0,
|
||||
stride: 0,
|
||||
dwords: 4,
|
||||
user_data: 4,
|
||||
slot: 1,
|
||||
}],
|
||||
io: StageIo::Cs(ComputeIo { rsrc2: 5 << 1, threads: [threads, 1, 1] }),
|
||||
code,
|
||||
}
|
||||
}
|
||||
|
||||
/// The CPU model: the balanced tree over 32 lanes, the first `launched` holding `x`, the rest `+0.0`.
|
||||
fn tree_sum(x: f64, launched: usize) -> f64 {
|
||||
let mut v: Vec<f64> = (0..32).map(|l| if l < launched { x } else { 0.0 }).collect();
|
||||
while v.len() > 1 {
|
||||
v = v.chunks(2).map(|p| p[0] + p[1]).collect();
|
||||
}
|
||||
v[0]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_f64_wave_sum_is_lowered_without_native_doubles() {
|
||||
let shader = translate_native(&f64_wave_sum_program(4)).expect("translate");
|
||||
let c = crate::dxbc::Container::parse(&shader.dxil).expect("container");
|
||||
let sfi0 = c.part(crate::dxbc::FourCC::SFI0).expect("SFI0 part").data;
|
||||
let features = u64::from_le_bytes(sfi0[..8].try_into().unwrap());
|
||||
assert_ne!(features & 0x4000, 0, "the sum uses wave operations (sanity check of this parse)");
|
||||
assert_eq!(features & 0x1, 0, "no native double may be declared: D3DMetal does not run them");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cpu_model_is_the_balanced_tree() {
|
||||
// 4 lanes of 1.25: (1.25 + 1.25) twice, then 2.5 + 2.5, then the rest +0
|
||||
assert_eq!(tree_sum(1.25, 4), 5.0);
|
||||
assert_eq!(tree_sum(1.25, 32), 40.0);
|
||||
// the order matters for values that round: this is not the sequential sum
|
||||
let x = 0.1;
|
||||
let sequential: f64 = (0..32).fold(0.0, |a, _| a + x);
|
||||
assert_ne!(tree_sum(x, 32).to_bits(), sequential.to_bits());
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
mod f64_on_the_gpu {
|
||||
use super::*;
|
||||
use crate::emit::host::{Dispatch, Host, Root, View};
|
||||
|
||||
/// Whole-wave f64 sums on the default D3D12 device, all 64 bits compared with the CPU model,
|
||||
/// for full and partial waves and for values that round. Fails when there is no device.
|
||||
#[test]
|
||||
fn f64_wave_sums_match_the_cpu_tree_bit_for_bit() {
|
||||
let _one = crate::emit::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let host = Host::hardware().expect("no SM 6.6 D3D12 hardware device: not verified");
|
||||
let mut ran = 0;
|
||||
for threads in [1u32, 4, 20, 32] {
|
||||
let shader = translate_native(&f64_wave_sum_program(threads)).expect("translate");
|
||||
let (root, pso) = host.compute_pipeline(&shader).expect("compute pipeline");
|
||||
for x in [1.25f64, 0.1, -3.75e10, 1.0e-300, 123456.789, f64::from_bits(0x3FF0_0000_0000_0001)] {
|
||||
let b = x.to_bits();
|
||||
let inputs = [b as u32, (b >> 32) as u32, 0, 0];
|
||||
let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize];
|
||||
for u in &shader.user_data {
|
||||
ud[u.index as usize] = match (u.root, u.slot) {
|
||||
(RootType::Constants, 0) => inputs[u.dword as usize],
|
||||
(RootType::Table, 1) => 0,
|
||||
other => panic!("unexpected user data {other:?}"),
|
||||
};
|
||||
}
|
||||
let out = host
|
||||
.dispatch(
|
||||
&root,
|
||||
&pso,
|
||||
&Dispatch {
|
||||
roots: vec![(0, Root::Constants(ud))],
|
||||
views: &[View::RawUav(2)],
|
||||
samplers: &[],
|
||||
groups: [1, 1, 1],
|
||||
},
|
||||
)
|
||||
.unwrap_or_else(|e| panic!("dispatch failed: {e}"));
|
||||
let got = u64::from(out[0][0]) | u64::from(out[0][1]) << 32;
|
||||
let want = tree_sum(x, threads as usize).to_bits();
|
||||
assert_eq!(got, want, "{threads} threads of {x:e}: got {got:#018x}, want {want:#018x}");
|
||||
ran += 1;
|
||||
}
|
||||
}
|
||||
eprintln!("betterxen: {ran} f64 wave sums ran on the GPU and matched the CPU tree bit for bit");
|
||||
}
|
||||
}
|
||||
|
||||
// ---- immediate samplers through translate_native ---------------------------------------------
|
||||
//
|
||||
// A compute program that builds its sampler from constants in the code (an immediate sampler)
|
||||
// needs a static sampler in the host's root signature. `translate_native` must report it, as the
|
||||
// container path does; the buffer-only fixtures above cannot notice.
|
||||
|
||||
/// Samples texel (0.5, 0.5) of the 2D texture in table slot 0 with an immediate sampler and stores
|
||||
/// the red channel to the raw UAV in table slot 1.
|
||||
fn immediate_sampler_program() -> NativeProgram {
|
||||
let s_mov_lit = |dst: u8, lit: u32| [0xBE80_03FF | (dst as u32) << 16, lit];
|
||||
let smem = |op: u32, dst: u32, base: u32, off: u32| [0x3D << 26 | op << 18 | dst << 6 | base >> 1, 125 << 25 | off];
|
||||
let mut w: Vec<u32> = Vec::new();
|
||||
w.push(0xBE80_0300 | 2 << 16); // s_mov_b32 s2, s0 (table address)
|
||||
w.push(0xBE80_0380 | 3 << 16); // s_mov_b32 s3, 0
|
||||
w.extend(smem(0x03, 8, 2, 0)); // s_load_dwordx8 s[8:15]: the texture SRV
|
||||
w.extend(smem(0x02, 20, 2, 32)); // s_load_dwordx4 s[20:23]: the UAV
|
||||
w.push(0x7E00_02F0 | 2 << 17); // v_mov_b32 v2, 0.5
|
||||
w.push(0x7E00_02F0 | 3 << 17); // v_mov_b32 v3, 0.5
|
||||
for (i, word) in [0x0000_0092u32, 0x00C0_0000, 0x1850_0000, 0].into_iter().enumerate() {
|
||||
w.extend(s_mov_lit(16 + i as u8, word)); // s[16:19]: the sampler, as constants
|
||||
}
|
||||
// image_sample_lz v4, v[2:3], s[8:15], s[16:19] dmask:0x1 dim:2D
|
||||
w.extend([0x3C << 26 | 0x21 << 18 | 1 << 8 | 1 << 3, (16u32 >> 2) << 21 | (8u32 >> 2) << 16 | 4 << 8 | 2]);
|
||||
w.extend([0x38 << 26 | 0x1C << 18, 0x80 << 24 | (20u32 >> 2) << 16 | 4 << 8]); // buffer_store_dword v4
|
||||
w.push(0xBF81_0000); // s_endpgm
|
||||
let used = |kind, table_offset_dwords, dwords| UsedResource {
|
||||
kind,
|
||||
root: RootType::Table,
|
||||
table_offset_dwords,
|
||||
lower_bound: 0,
|
||||
stride: 0,
|
||||
dwords,
|
||||
user_data: 0,
|
||||
slot: 0,
|
||||
};
|
||||
NativeProgram {
|
||||
stage: HwStage::Cs,
|
||||
wave64: false,
|
||||
vgprs: 8,
|
||||
layout: vec![RootParam {
|
||||
root: RootType::Table,
|
||||
table_offset_dwords: 0,
|
||||
sgprs: 1,
|
||||
base_register: 0,
|
||||
user_data: 0,
|
||||
slot: 0,
|
||||
}],
|
||||
used: vec![used(ResourceType::Srv, 0, 8), used(ResourceType::Uav, 8, 4)],
|
||||
io: StageIo::Cs(ComputeIo { rsrc2: 1 << 1, threads: [1, 1, 1] }),
|
||||
code: w.iter().flat_map(|x| x.to_le_bytes()).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn translate_native_reports_immediate_samplers_as_static_samplers() {
|
||||
let shader = translate_native(&immediate_sampler_program()).expect("translate");
|
||||
assert_eq!(shader.samplers.len(), 1, "the program has one immediate sampler");
|
||||
assert_eq!(shader.static_samplers.len(), 1, "the host builds s0 from this list");
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn immediate_sampler_samples_the_texture_on_the_gpu() {
|
||||
use crate::emit::host::{Dispatch, Host, Root, View};
|
||||
let _one = crate::emit::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let host = Host::hardware().expect("no SM 6.6 D3D12 hardware device: not verified");
|
||||
let shader = translate_native(&immediate_sampler_program()).expect("translate");
|
||||
let (root, pso) = host.compute_pipeline(&shader).expect("compute pipeline");
|
||||
let ud = vec![0u32; shader.user_data_dwords().max(1) as usize];
|
||||
let texels = [[0.25f32, 0.5, 0.75, 1.0]];
|
||||
let out = host
|
||||
.dispatch(
|
||||
&root,
|
||||
&pso,
|
||||
&Dispatch {
|
||||
roots: vec![(0, Root::Constants(ud))],
|
||||
views: &[View::Texture(1, 1, &texels), View::RawUav(1)],
|
||||
samplers: &[],
|
||||
groups: [1, 1, 1],
|
||||
},
|
||||
)
|
||||
.expect("dispatch");
|
||||
assert_eq!(out[0][0], 0.25f32.to_bits(), "red of the only texel");
|
||||
eprintln!("betterxen: the immediate-sampler program sampled the texture on the GPU");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn static_samplers_keep_the_comparison_filter_flag() {
|
||||
let words = [0x0000_0092u32, 0x00C0_0000, 0x1850_0000, 0];
|
||||
let list = super::static_samplers(&[words, words], 0b10);
|
||||
assert_eq!(list.len(), 2);
|
||||
assert_eq!(list[0].filter & 0x80, 0, "sampler 0 is not a comparison sampler");
|
||||
assert_ne!(list[1].filter & 0x80, 0, "sampler 1 is");
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,174 @@
|
||||
//! Counts of a module's instructions by kind (a diagnostic): what a
|
||||
//! translated program costs before the driver's compiler sees it.
|
||||
//!
|
||||
//! `VICTORY_SHADER_CENSUS` (any value) turns the counting on; the counts of
|
||||
//! the module a thread wrote last are read with [`take`]. The `translate`
|
||||
//! command writes them as a table (see `apps/victory/src/translate.rs`).
|
||||
|
||||
use super::{Cast, Module, Op, Tag, Term, V};
|
||||
use std::cell::RefCell;
|
||||
|
||||
/// The kinds, in the order of [`Census::counts`].
|
||||
pub const KINDS: [&str; 26] = [
|
||||
"total",
|
||||
"arith",
|
||||
"math_call",
|
||||
"bitcast",
|
||||
"cast",
|
||||
"select",
|
||||
"guard_select",
|
||||
"phi",
|
||||
"extract",
|
||||
"buffer_load",
|
||||
"cbuffer_load",
|
||||
"texture_read",
|
||||
"lds_load",
|
||||
"buffer_store",
|
||||
"lds_store",
|
||||
"atomic",
|
||||
"handle",
|
||||
"annotate",
|
||||
"dimensions",
|
||||
"barrier",
|
||||
"wave_op",
|
||||
"io_other",
|
||||
"gep",
|
||||
"clamp",
|
||||
"loop_counter",
|
||||
"blocks",
|
||||
];
|
||||
|
||||
/// Instruction counts of one written module, by [`KINDS`].
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct Census {
|
||||
pub counts: [u32; KINDS.len()],
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// The modules this thread wrote since the last [`take`]: the length and
|
||||
/// a hash of each one's bitcode, with its counts (a program may be
|
||||
/// emitted in several forms before one is kept).
|
||||
static WRITTEN: RefCell<Vec<(usize, u64, Census)>> = const { RefCell::new(Vec::new()) };
|
||||
}
|
||||
|
||||
fn fnv(bytes: &[u8]) -> u64 {
|
||||
bytes.iter().fold(0xcbf2_9ce4_8422_2325, |h, &b| {
|
||||
(h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3)
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether modules are counted (`VICTORY_SHADER_CENSUS` set).
|
||||
pub fn enabled() -> bool {
|
||||
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
*ON.get_or_init(|| std::env::var_os("VICTORY_SHADER_CENSUS").is_some())
|
||||
}
|
||||
|
||||
/// The counts of the module whose bitcode the container `dxil` holds, if
|
||||
/// this thread wrote it since the last call (which forgets the others).
|
||||
pub fn take(dxil: &[u8]) -> Option<Census> {
|
||||
let written = WRITTEN.with(|l| std::mem::take(&mut *l.borrow_mut()));
|
||||
let at = dxil.windows(4).position(|w| w == b"BC\xC0\xDE")?;
|
||||
written
|
||||
.into_iter()
|
||||
.rev()
|
||||
.find(|(len, hash, _)| dxil.get(at..at + len).is_some_and(|b| fnv(b) == *hash))
|
||||
.map(|w| w.2)
|
||||
}
|
||||
|
||||
/// Counts `m`, whose written form is `bitcode`, and keeps the result for
|
||||
/// [`take`].
|
||||
pub(crate) fn note(m: &Module, bitcode: &[u8]) {
|
||||
if !enabled() {
|
||||
return;
|
||||
}
|
||||
let c = m.census();
|
||||
WRITTEN.with(|l| l.borrow_mut().push((bitcode.len(), fnv(bitcode), c)));
|
||||
}
|
||||
|
||||
fn kind(name: &str) -> usize {
|
||||
let n = name.strip_prefix("dx.op.").unwrap_or(name);
|
||||
let n = n.split('.').next().unwrap_or(n);
|
||||
let k = |s: &str| KINDS.iter().position(|k| *k == s).expect("kind");
|
||||
match n {
|
||||
"unary" | "binary" | "tertiary" | "unaryBits" | "legacyF16ToF32" | "legacyF32ToF16"
|
||||
| "isSpecialFloat" | "dot2" | "dot3" | "dot4" | "quaternary" => k("math_call"),
|
||||
"bufferLoad" | "rawBufferLoad" => k("buffer_load"),
|
||||
"cbufferLoadLegacy" | "cbufferLoad" => k("cbuffer_load"),
|
||||
"bufferStore" | "rawBufferStore" | "textureStore" => k("buffer_store"),
|
||||
"atomicBinOp" | "atomicCompareExchange" => k("atomic"),
|
||||
"createHandle" | "createHandleFromBinding" | "createHandleFromHeap" => k("handle"),
|
||||
"annotateHandle" => k("annotate"),
|
||||
"getDimensions" => k("dimensions"),
|
||||
"barrier" => k("barrier"),
|
||||
_ if n.starts_with("wave") || n.starts_with("quad") => k("wave_op"),
|
||||
_ if n.starts_with("textureLoad")
|
||||
|| n.starts_with("sample")
|
||||
|| n.starts_with("textureGather")
|
||||
|| n.starts_with("calculateLOD") =>
|
||||
{
|
||||
k("texture_read")
|
||||
}
|
||||
_ => k("io_other"),
|
||||
}
|
||||
}
|
||||
|
||||
impl Module {
|
||||
/// The instructions [`Module::write`] writes, by kind.
|
||||
pub(crate) fn census(&self) -> Census {
|
||||
let k = |s: &str| KINDS.iter().position(|k| *k == s).expect("kind");
|
||||
let call_kind: Vec<usize> = self.funcs.iter().map(|f| kind(&f.name)).collect();
|
||||
let live = self.live();
|
||||
// The blocks `write` lays out: those reached from the entry.
|
||||
let mut seen = vec![false; self.blocks.len()];
|
||||
let mut stack = vec![0usize];
|
||||
if !self.blocks.is_empty() {
|
||||
seen[0] = true;
|
||||
}
|
||||
while let Some(b) = stack.pop() {
|
||||
for &s in super::successors(self.blocks[b].term).iter() {
|
||||
if !seen[s] {
|
||||
seen[s] = true;
|
||||
stack.push(s);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut c = Census::default();
|
||||
for (b, blk) in self.blocks.iter().enumerate() {
|
||||
if !seen[b] {
|
||||
continue;
|
||||
}
|
||||
c.counts[k("blocks")] += 1;
|
||||
let _: Option<Term> = blk.term;
|
||||
for &i in blk
|
||||
.phis
|
||||
.iter()
|
||||
.filter(|&&i| live[i as usize])
|
||||
.chain(&blk.body)
|
||||
{
|
||||
c.counts[0] += 1;
|
||||
let at = match &self.insts[i as usize].op {
|
||||
Op::Bin(..) | Op::Cmp(..) => k("arith"),
|
||||
Op::Cast(Cast::Bitcast, _) => k("bitcast"),
|
||||
Op::Cast(..) => k("cast"),
|
||||
Op::Select(..) => k("select"),
|
||||
Op::Extract(..) => k("extract"),
|
||||
Op::Phi(_) => k("phi"),
|
||||
Op::Gep(..) => k("gep"),
|
||||
Op::Load(_) => k("lds_load"),
|
||||
Op::Store(..) => k("lds_store"),
|
||||
Op::AtomicRmw(..) | Op::CmpXchg(..) => k("atomic"),
|
||||
Op::Call(f, _) => call_kind[*f as usize],
|
||||
};
|
||||
c.counts[at] += 1;
|
||||
match self.tags.get(&i) {
|
||||
Some(Tag::Guard) => c.counts[k("guard_select")] += 1,
|
||||
Some(Tag::Clamp) => c.counts[k("clamp")] += 1,
|
||||
Some(Tag::Counter) => c.counts[k("loop_counter")] += 1,
|
||||
None => {}
|
||||
}
|
||||
let _ = V::Inst(i);
|
||||
}
|
||||
}
|
||||
c
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,419 @@
|
||||
//! The PC container around emitted DXIL: feature flags (`SFI0`), the
|
||||
//! signatures (`ISG1`, `OSG1`), pipeline state validation (`PSV0`) and the
|
||||
//! program (`DXIL`), laid out as validator version 1.6 lays them out, plus
|
||||
//! the container hash that D3D12 checks.
|
||||
|
||||
/// One signature element: one row (D3D12 links stages by semantic).
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) struct SigElement {
|
||||
pub name: String,
|
||||
pub index: u32,
|
||||
/// DXIL semantic kind (0 arbitrary, 1 vertex id, 3 position, 16 target...).
|
||||
pub kind: u8,
|
||||
/// DXIL component type (4 i32, 5 u32, 9 f32, 1 i1).
|
||||
pub comp: u8,
|
||||
/// DXIL interpolation mode (0 for none).
|
||||
pub interp: u8,
|
||||
/// Start row, if the element has a register.
|
||||
pub row: Option<u32>,
|
||||
pub col: u8,
|
||||
pub cols: u8,
|
||||
/// Components read (inputs) or written (outputs), relative to `col`.
|
||||
pub usage: u8,
|
||||
/// 16-bit on the console (declared 32-bit here).
|
||||
pub half: bool,
|
||||
}
|
||||
|
||||
impl SigElement {
|
||||
fn system_value(&self) -> u32 {
|
||||
match self.kind {
|
||||
1 => 6, // vertex id
|
||||
2 => 8, // instance id
|
||||
3 => 1, // position
|
||||
4 => 4, // render target array index
|
||||
5 => 5, // viewport array index
|
||||
6 => 2, // clip distance
|
||||
7 => 3, // cull distance
|
||||
10 => 7, // primitive id
|
||||
12 => 10,
|
||||
13 => 9, // front face
|
||||
14 => 66,
|
||||
15 => 70,
|
||||
16 => 64, // target
|
||||
17 => 65, // depth
|
||||
18 => 68,
|
||||
19 => 67,
|
||||
20 => 69,
|
||||
28 => 23, // barycentrics
|
||||
30 => 25, // cull primitive
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn sig_comp(&self) -> u32 {
|
||||
match self.comp {
|
||||
1 | 5 => 1, // bool and u32
|
||||
4 => 2,
|
||||
9 => 3,
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn mask(&self) -> u8 {
|
||||
((1u8 << self.cols) - 1) << self.col
|
||||
}
|
||||
}
|
||||
|
||||
/// `ISG1`/`OSG1`: 32-byte rows, then the names.
|
||||
pub(crate) fn signature(elements: &[SigElement], input: bool) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
out.extend((elements.len() as u32).to_le_bytes());
|
||||
out.extend(8u32.to_le_bytes());
|
||||
// Validator 1.6 writes one name per element in element order, repeats
|
||||
// included, except that system values share theirs (it keys names by
|
||||
// the semantic's string, which is one static string per system value);
|
||||
// the rows sorted by register (unallocated last).
|
||||
let mut offsets: Vec<u32> = Vec::new();
|
||||
let mut next = 8 + 32 * elements.len() as u32;
|
||||
let mut names = Vec::new();
|
||||
for (i, e) in elements.iter().enumerate() {
|
||||
let shared = (e.kind != 0)
|
||||
.then(|| (0..i).find(|&j| elements[j].kind == e.kind))
|
||||
.flatten();
|
||||
match shared {
|
||||
Some(j) => offsets.push(offsets[j]),
|
||||
None => {
|
||||
offsets.push(next);
|
||||
next += e.name.len() as u32 + 1;
|
||||
names.push(&e.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut order: Vec<usize> = (0..elements.len()).collect();
|
||||
order.sort_by_key(|&i| (elements[i].row.unwrap_or(u32::MAX), elements[i].col));
|
||||
for i in order {
|
||||
let (e, offset) = (&elements[i], offsets[i]);
|
||||
let used = e.usage << e.col;
|
||||
let rw = if input { used } else { !used & 0xf };
|
||||
for v in [
|
||||
0,
|
||||
offset,
|
||||
e.index,
|
||||
e.system_value(),
|
||||
e.sig_comp(),
|
||||
e.row.unwrap_or(u32::MAX),
|
||||
] {
|
||||
out.extend(v.to_le_bytes());
|
||||
}
|
||||
out.extend([e.mask(), rw, 0, 0]);
|
||||
out.extend(0u32.to_le_bytes());
|
||||
}
|
||||
for name in names {
|
||||
out.extend(name.as_bytes());
|
||||
out.push(0);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The most a mesh shader's outputs may take, in bytes (D3D12).
|
||||
pub(crate) const MESH_OUTPUT_LIMIT: u64 = 32 * 1024;
|
||||
|
||||
/// A mesh shader's output size as the DXIL validator measures it against
|
||||
/// [`MESH_OUTPUT_LIMIT`]: 4 bytes per component of every vertex element
|
||||
/// and primitive element, times the maxima rounded up to multiples of 32.
|
||||
pub(crate) fn mesh_output_bytes(
|
||||
vertex: &[SigElement],
|
||||
primitive: &[SigElement],
|
||||
max_vertices: u32,
|
||||
max_primitives: u32,
|
||||
) -> u64 {
|
||||
let scalars = |els: &[SigElement]| els.iter().map(|e| u64::from(e.cols)).sum::<u64>();
|
||||
let align = |n: u32| u64::from(n).next_multiple_of(32);
|
||||
4 * (scalars(vertex) * align(max_vertices) + scalars(primitive) * align(max_primitives))
|
||||
}
|
||||
|
||||
/// A resource bound by register, as `PSV0` lists it.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) struct Binding {
|
||||
/// PSV resource type: 1 sampler, 2 CBV, 4 raw SRV, 7 raw UAV.
|
||||
pub kind: u32,
|
||||
pub space: u32,
|
||||
pub register: u32,
|
||||
/// DXIL resource kind (13 cbuffer, 14 sampler).
|
||||
pub dxil_kind: u32,
|
||||
}
|
||||
|
||||
pub(crate) struct Psv<'a> {
|
||||
/// PSV shader kind: 0 pixel, 1 vertex, 2 geometry, 5 compute.
|
||||
pub stage: u8,
|
||||
/// Vertex: writes `SV_Position`. Pixel: writes depth.
|
||||
pub flag: bool,
|
||||
pub inputs: &'a [SigElement],
|
||||
pub outputs: &'a [SigElement],
|
||||
/// Mesh: per-primitive outputs.
|
||||
pub prims: &'a [SigElement],
|
||||
/// Mesh: its state and the group-shared bytes it declares.
|
||||
pub mesh: Option<(super::shader::Mesh, u32)>,
|
||||
/// Geometry (triangles in, triangle strips out on stream 0): its
|
||||
/// maximum vertex count. `flag`: writes `SV_Position`.
|
||||
pub geometry: Option<u32>,
|
||||
pub bindings: &'a [Binding],
|
||||
/// Compute: thread-group size and required wave size.
|
||||
pub threads: [u32; 3],
|
||||
pub wave_size: Option<u32>,
|
||||
}
|
||||
|
||||
/// `PSV0` with runtime info version 2 (validator 1.6).
|
||||
pub(crate) fn psv(p: &Psv) -> Vec<u8> {
|
||||
let vectors = |els: &[SigElement]| {
|
||||
els.iter()
|
||||
.filter_map(|e| e.row)
|
||||
.map(|r| r + 1)
|
||||
.max()
|
||||
.unwrap_or(0)
|
||||
};
|
||||
let (in_vectors, out_vectors) = (vectors(p.inputs), vectors(p.outputs));
|
||||
let mut out = Vec::new();
|
||||
let u32s = |out: &mut Vec<u8>, vs: &[u32]| {
|
||||
for v in vs {
|
||||
out.extend(v.to_le_bytes());
|
||||
}
|
||||
};
|
||||
u32s(&mut out, &[48]);
|
||||
let mut info = [0u8; 48];
|
||||
info[0] = u8::from(p.flag);
|
||||
if p.stage == 0 {
|
||||
// PSInfo.SampleFrequency: an input interpolated per sample, or the
|
||||
// sample index.
|
||||
info[1] = u8::from(
|
||||
p.inputs
|
||||
.iter()
|
||||
.any(|e| matches!(e.interp, 6 | 7) || e.kind == 12),
|
||||
);
|
||||
}
|
||||
let (min, max) = p.wave_size.map_or((0, u32::MAX), |n| (n, n));
|
||||
info[16..20].copy_from_slice(&min.to_le_bytes());
|
||||
info[20..24].copy_from_slice(&max.to_le_bytes());
|
||||
info[24] = p.stage;
|
||||
for (k, n) in p.threads.into_iter().enumerate() {
|
||||
info[36 + 4 * k..40 + 4 * k].copy_from_slice(&n.to_le_bytes());
|
||||
}
|
||||
info[28] = p.inputs.len() as u8;
|
||||
info[29] = p.outputs.len() as u8;
|
||||
info[31] = in_vectors as u8;
|
||||
info[32] = out_vectors as u8;
|
||||
if let Some((mesh, shared)) = p.mesh {
|
||||
info[0..4].copy_from_slice(&shared.to_le_bytes());
|
||||
info[12..14].copy_from_slice(&(mesh.max_vertices as u16).to_le_bytes());
|
||||
info[14..16].copy_from_slice(&(mesh.max_primitives as u16).to_le_bytes());
|
||||
info[26] = vectors(p.prims) as u8;
|
||||
info[27] = mesh.topology;
|
||||
info[30] = p.prims.len() as u8;
|
||||
}
|
||||
if let Some(max_vertices) = p.geometry {
|
||||
// Input primitive (3: triangles), output topology (5: triangle
|
||||
// strips), stream mask, position written; the vertex maximum.
|
||||
info[0..4].copy_from_slice(&3u32.to_le_bytes());
|
||||
info[4..8].copy_from_slice(&5u32.to_le_bytes());
|
||||
info[8..12].copy_from_slice(&1u32.to_le_bytes());
|
||||
info[12] = u8::from(p.flag);
|
||||
info[26..28].copy_from_slice(&(max_vertices as u16).to_le_bytes());
|
||||
}
|
||||
out.extend(info);
|
||||
u32s(&mut out, &[p.bindings.len() as u32]);
|
||||
if !p.bindings.is_empty() {
|
||||
u32s(&mut out, &[24]);
|
||||
for b in p.bindings {
|
||||
u32s(
|
||||
&mut out,
|
||||
&[b.kind, b.space, b.register, b.register, b.dxil_kind, 0],
|
||||
);
|
||||
}
|
||||
}
|
||||
// Names of arbitrary semantics (system values use ""), then indices.
|
||||
let mut strings = vec![0u8];
|
||||
let mut indices: Vec<u32> = Vec::new();
|
||||
let mut elements = Vec::new();
|
||||
for e in p.inputs.iter().chain(p.outputs).chain(p.prims) {
|
||||
let name = if e.kind == 0 {
|
||||
let needle: Vec<u8> = e.name.bytes().chain([0]).collect();
|
||||
match find(&strings, &needle) {
|
||||
Some(at) => at,
|
||||
None => {
|
||||
strings.extend(&needle);
|
||||
strings.len() - needle.len()
|
||||
}
|
||||
}
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let index = match indices.iter().position(|&i| i == e.index) {
|
||||
Some(at) => at,
|
||||
None => {
|
||||
indices.push(e.index);
|
||||
indices.len() - 1
|
||||
}
|
||||
};
|
||||
let (start, alloc) = match e.row {
|
||||
Some(r) => (r as u8, 0x40 | (e.col << 4)),
|
||||
None => (0, 0),
|
||||
};
|
||||
elements.push((name as u32, index as u32, start, e.cols | alloc, e));
|
||||
}
|
||||
strings.resize(strings.len().next_multiple_of(4), 0);
|
||||
u32s(&mut out, &[strings.len() as u32]);
|
||||
out.extend(&strings);
|
||||
u32s(&mut out, &[indices.len() as u32]);
|
||||
u32s(&mut out, &indices);
|
||||
if !elements.is_empty() {
|
||||
u32s(&mut out, &[16]);
|
||||
for (name, index, start, cols, e) in elements {
|
||||
u32s(&mut out, &[name, index]);
|
||||
out.extend([1, start, cols, e.kind, e.sig_comp() as u8, e.interp, 0, 0]);
|
||||
}
|
||||
}
|
||||
// Input-to-output dependencies, as the view-id state declares them:
|
||||
// every output scalar on every input scalar.
|
||||
if in_vectors > 0 && out_vectors > 0 {
|
||||
let scalars = |els: &[SigElement]| {
|
||||
els.iter()
|
||||
.filter_map(|e| e.row.map(|r| r * 4 + u32::from(e.col + e.cols)))
|
||||
.max()
|
||||
.unwrap_or(0)
|
||||
};
|
||||
let (ni, no) = (scalars(p.inputs), scalars(p.outputs));
|
||||
let per = (out_vectors * 4).div_ceil(32);
|
||||
for i in 0..in_vectors * 4 {
|
||||
for k in 0..per {
|
||||
let bits = if i < ni {
|
||||
no.saturating_sub(32 * k).min(32)
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let mask = if bits == 32 {
|
||||
u32::MAX
|
||||
} else {
|
||||
(1u32 << bits) - 1
|
||||
};
|
||||
u32s(&mut out, &[mask]);
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn find(hay: &[u8], needle: &[u8]) -> Option<usize> {
|
||||
hay.windows(needle.len()).position(|w| w == needle)
|
||||
}
|
||||
|
||||
/// The container: parts in order, hashed.
|
||||
pub(crate) fn build(parts: &[(&[u8; 4], &[u8])]) -> Vec<u8> {
|
||||
let table = 0x20 + 4 * parts.len();
|
||||
let total = table + parts.iter().map(|(_, d)| 8 + d.len()).sum::<usize>();
|
||||
let mut out = Vec::with_capacity(total);
|
||||
out.extend(b"DXBC");
|
||||
out.extend([0; 16]);
|
||||
out.extend(1u16.to_le_bytes());
|
||||
out.extend(0u16.to_le_bytes());
|
||||
out.extend((total as u32).to_le_bytes());
|
||||
out.extend((parts.len() as u32).to_le_bytes());
|
||||
let mut offset = table;
|
||||
for (_, d) in parts {
|
||||
out.extend((offset as u32).to_le_bytes());
|
||||
offset += 8 + d.len();
|
||||
}
|
||||
for (fourcc, d) in parts {
|
||||
out.extend(*fourcc);
|
||||
out.extend((d.len() as u32).to_le_bytes());
|
||||
out.extend(*d);
|
||||
}
|
||||
let digest = hash(&out[20..]);
|
||||
out[4..20].copy_from_slice(&digest);
|
||||
out
|
||||
}
|
||||
|
||||
/// The container hash D3D12 checks: MD5 whose last block carries the bit
|
||||
/// count first and `2 × bytes + 1` last instead of standard padding.
|
||||
pub(crate) fn hash(data: &[u8]) -> [u8; 16] {
|
||||
let len = data.len();
|
||||
let left = len % 64;
|
||||
let mut tail = Vec::with_capacity(128);
|
||||
if left < 56 {
|
||||
tail.extend(((len as u32) << 3).to_le_bytes());
|
||||
tail.extend(&data[len - left..]);
|
||||
tail.push(0x80);
|
||||
tail.resize(60, 0);
|
||||
} else {
|
||||
tail.extend(&data[len - left..]);
|
||||
tail.push(0x80);
|
||||
tail.resize(64, 0);
|
||||
tail.extend(((len as u32) << 3).to_le_bytes());
|
||||
tail.resize(124, 0);
|
||||
}
|
||||
tail.extend(((len as u32) << 1 | 1).to_le_bytes());
|
||||
let mut state = [0x6745_2301u32, 0xefcd_ab89, 0x98ba_dcfe, 0x1032_5476];
|
||||
for block in data[..len - left]
|
||||
.as_chunks::<64>()
|
||||
.0
|
||||
.iter()
|
||||
.chain(tail.as_chunks::<64>().0)
|
||||
{
|
||||
md5_block(&mut state, block);
|
||||
}
|
||||
let mut out = [0; 16];
|
||||
for (o, s) in out.as_chunks_mut::<4>().0.iter_mut().zip(state) {
|
||||
o.copy_from_slice(&s.to_le_bytes());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn md5_block(state: &mut [u32; 4], block: &[u8; 64]) {
|
||||
const S: [u32; 16] = [7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21];
|
||||
let x: Vec<u32> = block
|
||||
.as_chunks::<4>()
|
||||
.0
|
||||
.iter()
|
||||
.map(|c| u32::from_le_bytes(*c))
|
||||
.collect();
|
||||
let [mut a, mut b, mut c, mut d] = *state;
|
||||
for i in 0..64 {
|
||||
let (f, g) = match i / 16 {
|
||||
0 => ((b & c) | (!b & d), i),
|
||||
1 => ((d & b) | (!d & c), (5 * i + 1) % 16),
|
||||
2 => (b ^ c ^ d, (3 * i + 5) % 16),
|
||||
_ => (c ^ (b | !d), (7 * i) % 16),
|
||||
};
|
||||
let k = ((i as f64 + 1.0).sin().abs() * 4_294_967_296.0) as u32;
|
||||
let rotated = a
|
||||
.wrapping_add(f)
|
||||
.wrapping_add(k)
|
||||
.wrapping_add(x[g])
|
||||
.rotate_left(S[(i / 16) * 4 + i % 4]);
|
||||
(a, b, c, d) = (d, b.wrapping_add(rotated), b, c);
|
||||
}
|
||||
for (s, v) in state.iter_mut().zip([a, b, c, d]) {
|
||||
*s = s.wrapping_add(v);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn md5_core_matches_the_standard() {
|
||||
// Standard MD5 of "abc" with standard padding, through md5_block.
|
||||
let mut block = b"abc".to_vec();
|
||||
block.push(0x80);
|
||||
block.resize(56, 0);
|
||||
block.extend(24u64.to_le_bytes());
|
||||
let mut state = [0x6745_2301u32, 0xefcd_ab89, 0x98ba_dcfe, 0x1032_5476];
|
||||
md5_block(&mut state, block.as_slice().try_into().unwrap());
|
||||
let hex: String = state
|
||||
.iter()
|
||||
.flat_map(|s| s.to_le_bytes())
|
||||
.map(|b| format!("{b:02x}"))
|
||||
.collect();
|
||||
assert_eq!(hex, "900150983cd24fb0d6963f7d28e17f72");
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,411 @@
|
||||
//! 64-bit floating point by integer operations: the host (D3DMetal, Metal) has no fp64, and the
|
||||
//! console's shaders use a little of it (`v_cvt_f32_f64` of a constant stored as a double,
|
||||
//! `v_add_f64` sums). The algorithms are written once over [`Ops`], on values that are 64-bit
|
||||
//! integers, and run on the IR builder in the lowering and on `u64` in the tests, where they are
|
||||
//! checked against the CPU's own `f64`.
|
||||
//!
|
||||
//! Round-to-nearest-even throughout, denormals included (the f32 result of a conversion may be
|
||||
//! one too).
|
||||
|
||||
/// What the algorithms need: 64-bit integer values and conditions. Shifts are by amounts below 64.
|
||||
pub(crate) trait Ops {
|
||||
type V: Copy;
|
||||
type C: Copy;
|
||||
fn k(&mut self, v: u64) -> Self::V;
|
||||
fn and(&mut self, a: Self::V, b: Self::V) -> Self::V;
|
||||
fn or(&mut self, a: Self::V, b: Self::V) -> Self::V;
|
||||
#[allow(dead_code)]
|
||||
fn xor(&mut self, a: Self::V, b: Self::V) -> Self::V;
|
||||
fn add(&mut self, a: Self::V, b: Self::V) -> Self::V;
|
||||
fn sub(&mut self, a: Self::V, b: Self::V) -> Self::V;
|
||||
fn shl(&mut self, a: Self::V, by: Self::V) -> Self::V;
|
||||
fn lshr(&mut self, a: Self::V, by: Self::V) -> Self::V;
|
||||
fn eq(&mut self, a: Self::V, b: Self::V) -> Self::C;
|
||||
fn ne(&mut self, a: Self::V, b: Self::V) -> Self::C;
|
||||
/// Unsigned a < b.
|
||||
fn ult(&mut self, a: Self::V, b: Self::V) -> Self::C;
|
||||
/// Signed a >= b.
|
||||
fn sge(&mut self, a: Self::V, b: Self::V) -> Self::C;
|
||||
fn sel(&mut self, c: Self::C, a: Self::V, b: Self::V) -> Self::V;
|
||||
}
|
||||
|
||||
fn kshl<O: Ops>(o: &mut O, a: O::V, n: u64) -> O::V {
|
||||
let n = o.k(n);
|
||||
o.shl(a, n)
|
||||
}
|
||||
|
||||
fn klshr<O: Ops>(o: &mut O, a: O::V, n: u64) -> O::V {
|
||||
let n = o.k(n);
|
||||
o.lshr(a, n)
|
||||
}
|
||||
|
||||
fn kn_plus_one<O: Ops>(o: &mut O, n: u64) -> O::V {
|
||||
o.k(n + 1)
|
||||
}
|
||||
|
||||
fn kand<O: Ops>(o: &mut O, a: O::V, m: u64) -> O::V {
|
||||
let m = o.k(m);
|
||||
o.and(a, m)
|
||||
}
|
||||
|
||||
/// `v_cvt_f32_f64`: the f32 bits (in the low 32 bits of the result) of the double `b`.
|
||||
pub(crate) fn cvt_f32_f64<O: Ops>(o: &mut O, b: O::V) -> O::V {
|
||||
let sign = klshr(o, b, 63);
|
||||
let e = klshr(o, b, 52);
|
||||
let e = kand(o, e, 0x7ff);
|
||||
let m = kand(o, b, (1 << 52) - 1);
|
||||
let (zero, one) = (o.k(0), o.k(1));
|
||||
// infinity and NaN (a quiet NaN with the payload's top bits)
|
||||
let payload = klshr(o, m, 29);
|
||||
let qnan = o.k(0x40_0000);
|
||||
let payload = o.or(payload, qnan);
|
||||
let m_zero = o.eq(m, zero);
|
||||
let payload = o.sel(m_zero, zero, payload);
|
||||
let inf = o.k(0x7f80_0000);
|
||||
let special = o.or(inf, payload);
|
||||
// normal results
|
||||
let bias = o.k(896); // 1023 - 127
|
||||
let ee = o.sub(e, bias);
|
||||
let rem = kand(o, m, 0x1fff_ffff);
|
||||
let q = klshr(o, m, 29);
|
||||
let half = o.k(1 << 28);
|
||||
let above = o.ult(half, rem);
|
||||
let tie = o.eq(rem, half);
|
||||
let odd = o.and(q, one);
|
||||
let up_tie = o.sel(tie, odd, zero);
|
||||
let up = o.sel(above, one, up_tie);
|
||||
let ee23 = kshl(o, ee, 23);
|
||||
let normal = o.add(ee23, q);
|
||||
let normal = o.add(normal, up);
|
||||
// results below the smallest normal
|
||||
let implicit = o.k(1 << 52);
|
||||
let mant = o.or(m, implicit);
|
||||
let thirty = o.k(30);
|
||||
let raw = o.sub(thirty, ee);
|
||||
let sixty3 = o.k(63);
|
||||
let too_far = o.ult(sixty3, raw); // raw > 63, or negative (huge)
|
||||
let raw = o.sel(too_far, sixty3, raw);
|
||||
let ee_pos = o.sge(ee, one);
|
||||
let s = o.sel(ee_pos, thirty, raw);
|
||||
let q2 = o.lshr(mant, s);
|
||||
let mask = o.shl(one, s);
|
||||
let mask = o.sub(mask, one);
|
||||
let rem2 = o.and(mant, mask);
|
||||
let sm1 = o.sub(s, one);
|
||||
let half2 = o.shl(one, sm1);
|
||||
let above2 = o.ult(half2, rem2);
|
||||
let tie2 = o.eq(rem2, half2);
|
||||
let odd2 = o.and(q2, one);
|
||||
let up_tie2 = o.sel(tie2, odd2, zero);
|
||||
let up2 = o.sel(above2, one, up_tie2);
|
||||
let denormal = o.add(q2, up2);
|
||||
// choose
|
||||
let k255 = o.k(255);
|
||||
let big = o.sge(ee, k255);
|
||||
let mag = o.sel(ee_pos, normal, denormal);
|
||||
let mag = o.sel(big, inf, mag);
|
||||
let e_zero = o.eq(e, zero);
|
||||
let mag = o.sel(e_zero, zero, mag);
|
||||
let k7ff = o.k(0x7ff);
|
||||
let e_all = o.eq(e, k7ff);
|
||||
let mag = o.sel(e_all, special, mag);
|
||||
let sign = kshl(o, sign, 31);
|
||||
o.or(sign, mag)
|
||||
}
|
||||
|
||||
/// `v_add_f64`: the bits of `a + b` for the doubles `a` and `b`.
|
||||
pub(crate) fn add_f64<O: Ops>(o: &mut O, a: O::V, b: O::V) -> O::V {
|
||||
let (zero, one) = (o.k(0), o.k(1));
|
||||
let magnitude = |o: &mut O, x: O::V| kand(o, x, (1 << 63) - 1);
|
||||
let (ma, mb) = (magnitude(o, a), magnitude(o, b));
|
||||
// `big` has the larger magnitude
|
||||
let swap = o.ult(ma, mb);
|
||||
let big = o.sel(swap, b, a);
|
||||
let small = o.sel(swap, a, b);
|
||||
let parts = |o: &mut O, x: O::V| {
|
||||
let s = klshr(o, x, 63);
|
||||
let e = klshr(o, x, 52);
|
||||
let e = kand(o, e, 0x7ff);
|
||||
let m = kand(o, x, (1 << 52) - 1);
|
||||
(s, e, m)
|
||||
};
|
||||
let (sb, eb0, mb_) = parts(o, big);
|
||||
let (ss, es0, ms_) = parts(o, small);
|
||||
let k7ff = o.k(0x7ff);
|
||||
// 53-bit significands (a denormal has no implicit bit and the exponent 1)
|
||||
let implicit = o.k(1 << 52);
|
||||
let sig = |o: &mut O, e: O::V, m: O::V| {
|
||||
let full = o.or(m, implicit);
|
||||
let z = o.k(0);
|
||||
let is0 = o.eq(e, z);
|
||||
o.sel(is0, m, full)
|
||||
};
|
||||
let (mant_b, mant_s) = (sig(o, eb0, mb_), sig(o, es0, ms_));
|
||||
let eff = |o: &mut O, e: O::V| {
|
||||
let z = o.k(0);
|
||||
let one = o.k(1);
|
||||
let is0 = o.eq(e, z);
|
||||
o.sel(is0, one, e)
|
||||
};
|
||||
let (eb, es) = (eff(o, eb0), eff(o, es0));
|
||||
// three extra low bits (guard, round, sticky)
|
||||
let mant_b = kshl(o, mant_b, 3);
|
||||
let mant_s = kshl(o, mant_s, 3);
|
||||
// align the smaller one
|
||||
let d = o.sub(eb, es);
|
||||
let sixty3 = o.k(63);
|
||||
let far = o.ult(sixty3, d);
|
||||
let sh = o.sel(far, sixty3, d);
|
||||
let shifted = o.lshr(mant_s, sh);
|
||||
let mask = o.shl(one, sh);
|
||||
let mask = o.sub(mask, one);
|
||||
let lost = o.and(mant_s, mask);
|
||||
let lost = o.ne(lost, zero);
|
||||
let sticky = o.sel(lost, one, zero);
|
||||
let shifted = o.or(shifted, sticky);
|
||||
// add or subtract
|
||||
let same = o.eq(sb, ss);
|
||||
let sum = o.add(mant_b, shifted);
|
||||
let diff = o.sub(mant_b, shifted);
|
||||
let mut v = o.sel(same, sum, diff);
|
||||
let mut e = eb;
|
||||
// carry out: bit 56
|
||||
let top = o.k(1 << 56);
|
||||
let carry = o.and(v, top);
|
||||
let carried = o.ne(carry, zero);
|
||||
let lowbit = o.and(v, one);
|
||||
let halved = klshr(o, v, 1);
|
||||
let halved = o.or(halved, lowbit);
|
||||
v = o.sel(carried, halved, v);
|
||||
let e_plus = o.add(e, one);
|
||||
e = o.sel(carried, e_plus, e);
|
||||
// cancellation: shift left until bit 55 is set
|
||||
for n in [32u64, 16, 8, 4, 2, 1] {
|
||||
// the top n bits below bit 56: bits 55 down to 56 - n
|
||||
let ones = (1u64 << n) - 1;
|
||||
let field = ones << (56 - n);
|
||||
let top_bits = kand(o, v, field);
|
||||
let empty = o.eq(top_bits, zero);
|
||||
let nonzero = o.ne(v, zero);
|
||||
let kn = o.k(n);
|
||||
let shift = o.sel(empty, kn, zero);
|
||||
let shift = o.sel(nonzero, shift, zero);
|
||||
// not below the exponent 1: the result is then a denormal
|
||||
let np1 = kn_plus_one(o, n);
|
||||
let allowed = o.sge(e, np1);
|
||||
let shift = o.sel(allowed, shift, zero);
|
||||
v = o.shl(v, shift);
|
||||
e = o.sub(e, shift);
|
||||
}
|
||||
// round to nearest even
|
||||
let low = kand(o, v, 7);
|
||||
let m = klshr(o, v, 3);
|
||||
let k4 = o.k(4);
|
||||
let above = o.ult(k4, low);
|
||||
let tie = o.eq(low, k4);
|
||||
let odd = o.and(m, one);
|
||||
let up_tie = o.sel(tie, odd, zero);
|
||||
let up = o.sel(above, one, up_tie);
|
||||
let m = o.add(m, up);
|
||||
// (exponent - 1) << 52 plus the significand with its hidden bit: a carry out of the
|
||||
// significand, and a denormal that rounds up to the smallest normal, add to the exponent
|
||||
let e_minus = o.sub(e, one);
|
||||
let e_field = kshl(o, e_minus, 52);
|
||||
let bits = o.add(e_field, m);
|
||||
let sign = kshl(o, sb, 63);
|
||||
let inf_mag = o.k(0x7ff0_0000_0000_0000);
|
||||
let overflow = o.ult(bits, inf_mag);
|
||||
let mag = o.sel(overflow, bits, inf_mag);
|
||||
let finite = o.or(sign, mag);
|
||||
// exact cancellation: +0, or -0 for two negative zeros
|
||||
let result_zero = o.eq(v, zero);
|
||||
let neg_zero = o.sel(same, sign, zero);
|
||||
let r = o.sel(result_zero, neg_zero, finite);
|
||||
// infinities and NaNs
|
||||
let a_all = {
|
||||
let ea = {
|
||||
let t = klshr(o, a, 52);
|
||||
kand(o, t, 0x7ff)
|
||||
};
|
||||
o.eq(ea, k7ff)
|
||||
};
|
||||
let b_all = {
|
||||
let eb2 = {
|
||||
let t = klshr(o, b, 52);
|
||||
kand(o, t, 0x7ff)
|
||||
};
|
||||
o.eq(eb2, k7ff)
|
||||
};
|
||||
let a_m = kand(o, a, (1 << 52) - 1);
|
||||
let b_m = kand(o, b, (1 << 52) - 1);
|
||||
let a_nan = {
|
||||
let nz = o.ne(a_m, zero);
|
||||
let x = o.sel(nz, one, zero);
|
||||
o.sel(a_all, x, zero)
|
||||
};
|
||||
let b_nan = {
|
||||
let nz = o.ne(b_m, zero);
|
||||
let x = o.sel(nz, one, zero);
|
||||
o.sel(b_all, x, zero)
|
||||
};
|
||||
let nan_bits = o.k(0x7ff8_0000_0000_0000);
|
||||
let any_nan = o.or(a_nan, b_nan);
|
||||
let any_nan = o.ne(any_nan, zero);
|
||||
// a (or b) is an infinity: the result is that infinity, a NaN if the other is the opposite one
|
||||
let a_inf = a_all;
|
||||
let b_inf = b_all;
|
||||
let (sa, sb2) = (klshr(o, a, 63), klshr(o, b, 63));
|
||||
let signs_differ = o.ne(sa, sb2);
|
||||
let both_inf = {
|
||||
let x = o.sel(a_inf, one, zero);
|
||||
let y = o.sel(b_inf, one, zero);
|
||||
let z = o.and(x, y);
|
||||
o.ne(z, zero)
|
||||
};
|
||||
let inf_nan = {
|
||||
let x = o.sel(both_inf, one, zero);
|
||||
let y = o.sel(signs_differ, one, zero);
|
||||
let z = o.and(x, y);
|
||||
o.ne(z, zero)
|
||||
};
|
||||
let r = o.sel(b_inf, b, r);
|
||||
let r = o.sel(a_inf, a, r);
|
||||
let nan_case = {
|
||||
let x = o.sel(any_nan, one, zero);
|
||||
let y = o.sel(inf_nan, one, zero);
|
||||
let z = o.or(x, y);
|
||||
o.ne(z, zero)
|
||||
};
|
||||
o.sel(nan_case, nan_bits, r)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The algorithms on `u64`.
|
||||
struct Native;
|
||||
|
||||
impl Ops for Native {
|
||||
type V = u64;
|
||||
type C = bool;
|
||||
fn k(&mut self, v: u64) -> u64 { v }
|
||||
fn and(&mut self, a: u64, b: u64) -> u64 { a & b }
|
||||
fn or(&mut self, a: u64, b: u64) -> u64 { a | b }
|
||||
fn xor(&mut self, a: u64, b: u64) -> u64 { a ^ b }
|
||||
fn add(&mut self, a: u64, b: u64) -> u64 { a.wrapping_add(b) }
|
||||
fn sub(&mut self, a: u64, b: u64) -> u64 { a.wrapping_sub(b) }
|
||||
fn shl(&mut self, a: u64, by: u64) -> u64 { assert!(by < 64, "shift by {by}"); a << by }
|
||||
fn lshr(&mut self, a: u64, by: u64) -> u64 { assert!(by < 64, "shift by {by}"); a >> by }
|
||||
fn eq(&mut self, a: u64, b: u64) -> bool { a == b }
|
||||
fn ne(&mut self, a: u64, b: u64) -> bool { a != b }
|
||||
fn ult(&mut self, a: u64, b: u64) -> bool { a < b }
|
||||
fn sge(&mut self, a: u64, b: u64) -> bool { a as i64 >= b as i64 }
|
||||
fn sel(&mut self, c: bool, a: u64, b: u64) -> u64 { if c { a } else { b } }
|
||||
}
|
||||
|
||||
struct Rng(u64);
|
||||
impl Rng {
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 ^= self.0 << 13;
|
||||
self.0 ^= self.0 >> 7;
|
||||
self.0 ^= self.0 << 17;
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
fn cvt(x: f64) -> u32 {
|
||||
cvt_f32_f64(&mut Native, x.to_bits()) as u32
|
||||
}
|
||||
|
||||
fn same_f32(got: u32, want: f32) -> bool {
|
||||
if want.is_nan() {
|
||||
f32::from_bits(got).is_nan()
|
||||
} else {
|
||||
got == want.to_bits()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[allow(clippy::approx_constant)] // 3.14159265358979 is a test value, not the constant
|
||||
fn f32_from_f64_edges() {
|
||||
let cases = [
|
||||
0.0, -0.0, 1.0, -1.0, 0.5, 3.14159265358979, 1e-10, 1e10, 1e38, 3.4028234663852886e38, 3.4028235677973366e38,
|
||||
3.4028236e38, 1e39, -1e39, f64::INFINITY, f64::NEG_INFINITY, f64::NAN, 1e-38, 1.1754943508222875e-38, 1e-40,
|
||||
1.4e-45, 7e-46, 7.006492321624085e-46, 7.006492321624086e-46, 1e-50, 5e-324, 2.2250738585072014e-308,
|
||||
// ties: 1 + 2^-24 (halfway between two f32), and just above and below
|
||||
1.0 + 2f64.powi(-24), 1.0 + 2f64.powi(-24) + 2f64.powi(-40), 1.0 + 3.0 * 2f64.powi(-24),
|
||||
16777217.0, 16777219.0, 8388609.5,
|
||||
];
|
||||
for x in cases {
|
||||
let got = cvt(x);
|
||||
assert!(same_f32(got, x as f32), "{x:e}: got {got:#010x}, want {:#010x}", (x as f32).to_bits());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn f32_from_f64_random() {
|
||||
let mut r = Rng(0x1234_5678_9abc_def1);
|
||||
for i in 0..400_000u32 {
|
||||
let bits = r.next();
|
||||
// spread over exponents near the f32 range as well as everywhere
|
||||
let bits = if i % 2 == 0 { bits } else { (bits & !(0x7ff << 52)) | ((896 - 30 + (r.next() % 330)) << 52) };
|
||||
let x = f64::from_bits(bits);
|
||||
let got = cvt(x);
|
||||
assert!(same_f32(got, x as f32), "{bits:#018x} {x:e}: got {got:#010x}, want {:#010x}", (x as f32).to_bits());
|
||||
}
|
||||
}
|
||||
|
||||
fn add(a: f64, b: f64) -> u64 {
|
||||
add_f64(&mut Native, a.to_bits(), b.to_bits())
|
||||
}
|
||||
|
||||
fn same_f64(got: u64, want: f64) -> bool {
|
||||
let g = f64::from_bits(got);
|
||||
if want.is_nan() {
|
||||
g.is_nan()
|
||||
} else {
|
||||
got == want.to_bits()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn f64_sums_edges() {
|
||||
let vals = [
|
||||
0.0, -0.0, 1.0, -1.0, 0.5, 3.0, -3.0, 1e300, -1e300, 1.7976931348623157e308, 2.0f64.powi(-1022), 1.5,
|
||||
5e-324, -5e-324, 2.2250738585072014e-308, 1.0 + f64::EPSILON, 1.0 - f64::EPSILON / 2.0, 1e-300, f64::INFINITY, f64::NEG_INFINITY, f64::NAN, 123456.789, 2f64.powi(53),
|
||||
2f64.powi(53) + 2.0, 4.0 / 3.0,
|
||||
];
|
||||
for a in vals {
|
||||
for b in vals {
|
||||
let got = add(a, b);
|
||||
assert!(same_f64(got, a + b), "{a:e} + {b:e}: got {:e} ({got:#x}), want {:e} ({:#x})", f64::from_bits(got), a + b, (a + b).to_bits());
|
||||
}
|
||||
}
|
||||
// signed zeros
|
||||
assert_eq!(add(-0.0, -0.0), (-0.0f64).to_bits());
|
||||
assert_eq!(add(0.0, -0.0), 0.0f64.to_bits());
|
||||
assert_eq!(add(1.0, -1.0), 0.0f64.to_bits());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn f64_sums_random() {
|
||||
let mut r = Rng(0x9e37_79b9_7f4a_7c15);
|
||||
for i in 0..400_000u32 {
|
||||
let (mut x, mut y) = (r.next(), r.next());
|
||||
// exponents within a few bits of each other make cancellation and carries common
|
||||
if i % 3 != 0 {
|
||||
let e = 1000 + (r.next() % 50);
|
||||
x = (x & !(0x7ff << 52)) | (e << 52);
|
||||
y = (y & !(0x7ff << 52)) | ((e + (r.next() % 4) - 1) << 52);
|
||||
}
|
||||
if i % 7 == 0 {
|
||||
// a nearly cancelling pair
|
||||
y = x ^ (1 << 63) ^ (r.next() & 0xfff);
|
||||
}
|
||||
let (a, b) = (f64::from_bits(x), f64::from_bits(y));
|
||||
let got = add(a, b);
|
||||
assert!(same_f64(got, a + b), "{x:#018x} + {y:#018x}: got {got:#018x}, want {:#018x}", (a + b).to_bits());
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,557 @@
|
||||
//! The console's ray-tracing node test, `image_bvh_intersect_ray` and
|
||||
//! `image_bvh64_intersect_ray`, as inline DXIL: the host has no instruction
|
||||
//! that tests one ray against one node of the title's own structures.
|
||||
//!
|
||||
//! [`crate::bvh`] says what the instruction computes and is the reference:
|
||||
//! the code made here does the same float operations in the same order
|
||||
//! (DXIL float operations carry no fast-math flags, so the host may not
|
||||
//! reorder or fuse them), and the tests in `intersect_tests.rs` run it on
|
||||
//! the card against the reference.
|
||||
//!
|
||||
//! The title's nodes are in title memory, named by address: they are read
|
||||
//! through the host's copies of title memory ([`Lower::memory`]), one look
|
||||
//! in its directory per node (two for a 128-byte box node).
|
||||
//!
|
||||
//! Shape of the code, under the instruction's lane guard:
|
||||
//!
|
||||
//! ```text
|
||||
//! kind = pointer & 7
|
||||
//! box (4, 5): 4 child pointers; 24 box floats (kind 5) or 24 halves widened (kind 4);
|
||||
//! four slab tests; the sorting network
|
||||
//! triangle (0-3): the id dword, three vertices at the bytes it names; the watertight test
|
||||
//! other (6, 7): a triangle miss
|
||||
//! ```
|
||||
//!
|
||||
//! Each lane reads only the dwords its node's kind needs: 28 for a 32-bit
|
||||
//! box node, 16 for a 16-bit one, 10 for a triangle.
|
||||
|
||||
use super::{Attr, Bin, Fields, Inst, Lower, Operand, Reg, Term, V, Why, flags, pred};
|
||||
use crate::bvh;
|
||||
use crate::resource::BvhNodes;
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// The tests' stand-in for title memory ([`Lower::bvh_memory`]): a
|
||||
/// heap slot holding a raw buffer, and the title address of its first
|
||||
/// byte. (The card tests have no host to keep copies of title memory
|
||||
/// and their directory.)
|
||||
pub(in crate::emit) static TEST_MEMORY: std::cell::Cell<Option<(u32, u64)>> =
|
||||
const { std::cell::Cell::new(None) };
|
||||
}
|
||||
|
||||
/// Where the instruction's node is.
|
||||
#[derive(Clone, Copy)]
|
||||
enum NodeAt {
|
||||
/// At this byte of a raw buffer of the host.
|
||||
Buffer { handle: V, byte: V },
|
||||
/// In title memory: the raw view of the host copy holding the node's
|
||||
/// first 64 bytes and the node's byte in it ([`Lower::bvh_memory`]),
|
||||
/// and the node's address, for the second half of a 128-byte node.
|
||||
Memory { handle: V, byte: V, low: V, high: V },
|
||||
}
|
||||
|
||||
/// The ray operands, as floats.
|
||||
struct Ray {
|
||||
extent: V,
|
||||
origin: [V; 3],
|
||||
direction: [V; 3],
|
||||
inverse: [V; 3],
|
||||
}
|
||||
|
||||
impl<'a> Lower<'a> {
|
||||
/// `image_bvh_intersect_ray` and `image_bvh64_intersect_ray`.
|
||||
pub(super) fn bvh(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
|
||||
let Fields::Image {
|
||||
data,
|
||||
addr,
|
||||
rsrc,
|
||||
dmask,
|
||||
a16,
|
||||
d16,
|
||||
tfe,
|
||||
lwe,
|
||||
..
|
||||
} = &inst.fields
|
||||
else {
|
||||
unreachable!()
|
||||
};
|
||||
if *a16 || *d16 || *tfe || *lwe || *dmask != 0xf {
|
||||
return Err("a ray-tracing node test with 16-bit operands or a partial result");
|
||||
}
|
||||
let wide = inst.name() == "image_bvh64_intersect_ray";
|
||||
// Operand VGPRs in order: the node pointer (two dwords in the
|
||||
// 64-bit form), the ray's extent, origin, direction and inverse
|
||||
// direction.
|
||||
let mut regs = Vec::new();
|
||||
for a in addr {
|
||||
if let Operand::Vector { reg, dwords } = *a {
|
||||
regs.extend((0..dwords).map(|k| reg + k));
|
||||
}
|
||||
}
|
||||
if regs.len() != if wide { 12 } else { 11 } {
|
||||
return Err("a ray-tracing node test's operands");
|
||||
}
|
||||
let Operand::Vector { reg: dst, .. } = *data else {
|
||||
return Err("a ray-tracing node test's result");
|
||||
};
|
||||
let site = (b, i);
|
||||
let nodes = self
|
||||
.x
|
||||
.res
|
||||
.bvh
|
||||
.iter()
|
||||
.find(|n| n.0 == site)
|
||||
.map(|n| n.1)
|
||||
.ok_or("an untracked ray-tracing structure")?;
|
||||
let (sort, barycentrics) = match nodes {
|
||||
BvhNodes::Resource => (true, true),
|
||||
BvhNodes::Memory { word1, word3 } => (
|
||||
word1 & bvh::BOX_SORT != 0,
|
||||
word3 & bvh::RETURN_BARYCENTRICS != 0,
|
||||
),
|
||||
};
|
||||
if !barycentrics {
|
||||
// Mode 0 returns a triangle id and a hit status in the last two
|
||||
// dwords; no program of the title asks for it.
|
||||
return Err("a ray-tracing structure that returns triangle ids");
|
||||
}
|
||||
let guard = self.guard(b, i)?;
|
||||
let mut x = Vec::with_capacity(regs.len());
|
||||
for &r in ®s {
|
||||
let v = inst.read(Reg::V(r)).ok_or("an unread operand")?;
|
||||
x.push(self.i32_of(v)?);
|
||||
}
|
||||
let pointer = x[0];
|
||||
let pointer_high = wide.then(|| x[1]);
|
||||
let f: Vec<V> = x[1 + usize::from(wide)..]
|
||||
.iter()
|
||||
.map(|&v| self.as_float(v))
|
||||
.collect();
|
||||
let ray = Ray {
|
||||
extent: f[0],
|
||||
origin: [f[1], f[2], f[3]],
|
||||
direction: [f[4], f[5], f[6]],
|
||||
inverse: [f[7], f[8], f[9]],
|
||||
};
|
||||
let c = self.cur;
|
||||
let at = match nodes {
|
||||
BvhNodes::Resource => {
|
||||
let src = self
|
||||
.descriptors
|
||||
.get(&(site, false))
|
||||
.copied()
|
||||
.ok_or("an untracked ray-tracing structure")?;
|
||||
let handle = self.handle(site, src, false, (11, 0))?;
|
||||
// (pointer >> 3) << 6 from the buffer's start.
|
||||
let (kind_bits, k3) = (self.s.m.i32(!7), self.s.m.i32(3));
|
||||
let byte = self.s.m.bin(c, Bin::And, pointer, kind_bits);
|
||||
let byte = self.s.m.bin(c, Bin::Shl, byte, k3);
|
||||
NodeAt::Buffer { handle, byte }
|
||||
}
|
||||
BvhNodes::Memory { .. } => {
|
||||
let Operand::Scalar { code, .. } = *rsrc else {
|
||||
return Err("a ray-tracing structure descriptor not in SGPRs");
|
||||
};
|
||||
let mut words = [pointer; 2];
|
||||
for (k, w) in words.iter_mut().enumerate() {
|
||||
let v = inst
|
||||
.read(Reg::S(code + k as u8))
|
||||
.ok_or("an unread operand")?;
|
||||
*w = self.i32_of(v)?;
|
||||
}
|
||||
let (low, high) = self.bvh_address(words[0], words[1], pointer, pointer_high);
|
||||
// One look for the node's copy, before the branches: a
|
||||
// node is 64 bytes on 64, so its first half lies in one
|
||||
// 64 KiB page whatever its kind.
|
||||
let (handle, byte) = self.bvh_memory(low, high, guard);
|
||||
NodeAt::Memory {
|
||||
handle,
|
||||
byte,
|
||||
low,
|
||||
high,
|
||||
}
|
||||
}
|
||||
};
|
||||
let zero = self.s.m.i32(0);
|
||||
let gate = self.begin_guarded(guard);
|
||||
let head = self.cur;
|
||||
let (k4, k6, k7) = (self.s.m.i32(4), self.s.m.i32(6), self.s.m.i32(7));
|
||||
let kind = self.s.m.bin(head, Bin::And, pointer, k7);
|
||||
let pair = self.s.m.bin(head, Bin::And, pointer, k6);
|
||||
let is_box = self.s.m.cmp(head, pred::EQ, pair, k4);
|
||||
let is_triangle = self.s.m.cmp(head, pred::IULT, kind, k4);
|
||||
let (box_block, leaf_block) = (self.s.m.new_block(), self.s.m.new_block());
|
||||
let (triangle_block, join) = (self.s.m.new_block(), self.s.m.new_block());
|
||||
self.s
|
||||
.m
|
||||
.terminate(head, Term::CondBr(is_box, box_block, leaf_block));
|
||||
self.s
|
||||
.m
|
||||
.terminate(leaf_block, Term::CondBr(is_triangle, triangle_block, join));
|
||||
self.cur = box_block;
|
||||
let boxes = self.bvh_boxes(at, kind, &ray, sort);
|
||||
let box_end = self.cur;
|
||||
self.s.m.terminate(box_end, Term::Br(join));
|
||||
self.cur = triangle_block;
|
||||
let triangle = self.bvh_triangle(at, kind, &ray);
|
||||
let triangle_end = self.cur;
|
||||
self.s.m.terminate(triangle_end, Term::Br(join));
|
||||
self.cur = join;
|
||||
// Kinds 6 and 7 (an instance, a procedural primitive): not known
|
||||
// what the console returns; the title's programs do not read it.
|
||||
let other = bvh::MISS.map(|f| self.s.m.i32(f.to_bits()));
|
||||
let i32t = self.s.t.i32;
|
||||
let mut results = Vec::with_capacity(4);
|
||||
for k in 0..4 {
|
||||
let phi = self.s.m.phi(join, i32t);
|
||||
self.s.m.set_phi(
|
||||
phi,
|
||||
vec![
|
||||
(boxes[k], box_end),
|
||||
(triangle[k], triangle_end),
|
||||
(other[k], leaf_block),
|
||||
],
|
||||
);
|
||||
results.push((phi, zero));
|
||||
}
|
||||
let results = self.end_guarded(gate, &results);
|
||||
for (k, &r) in results.iter().enumerate() {
|
||||
self.write(inst, Reg::V(dst + k as u8), r, guard);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Title memory at `low`/`high` for a node's bytes: the raw view of the
|
||||
/// host copy holding the address and the byte in that view
|
||||
/// ([`Lower::memory`]: a page the host has no copy of reads zeros and
|
||||
/// is left for the host to fetch, for lanes that run).
|
||||
fn bvh_memory(&mut self, low: V, high: V, guard: Option<V>) -> (V, V) {
|
||||
#[cfg(test)]
|
||||
if let Some((slot, base)) = TEST_MEMORY.get() {
|
||||
// The buffer at heap slot `slot` holds the bytes from title
|
||||
// address `base` on; any other address reads past its end,
|
||||
// which is zeros.
|
||||
let c = self.cur;
|
||||
let slot = self.s.m.i32(slot);
|
||||
let handle = self.s.heap_handle(c, slot, false, false, (11, 0));
|
||||
let (base_low, base_high) =
|
||||
(self.s.m.i32(base as u32), self.s.m.i32((base >> 32) as u32));
|
||||
let at = self.s.m.bin(c, Bin::Sub, low, base_low);
|
||||
let in_low = self.s.m.cmp(c, pred::IUGE, low, base_low);
|
||||
let in_high = self.s.m.cmp(c, pred::EQ, high, base_high);
|
||||
let inside = self.s.m.bin(c, Bin::And, in_low, in_high);
|
||||
let outside = self.s.m.i32(0xffff_ff00);
|
||||
let at = self.s.m.select(c, inside, at, outside);
|
||||
return (handle, at);
|
||||
}
|
||||
self.memory(low, high, guard)
|
||||
}
|
||||
|
||||
/// `count` dwords of the node from its byte `base` + `offset` (`base`
|
||||
/// computed, `offset` fixed; none of the node's bytes past 127), read
|
||||
/// four at a time.
|
||||
fn bvh_node_words(&mut self, at: NodeAt, base: Option<V>, offset: u32, count: u32) -> Vec<V> {
|
||||
let c = self.cur;
|
||||
let (undef, align) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4));
|
||||
// The second half of a 128-byte node may lie in the next 64 KiB
|
||||
// page, which may be in another copy: its own look, made once.
|
||||
let mut second = None;
|
||||
let mut out = Vec::with_capacity(count as usize);
|
||||
for start in (0..count).step_by(4) {
|
||||
let n = (count - start).min(4);
|
||||
let node_byte = offset + 4 * start;
|
||||
let (handle, mut byte) = match at {
|
||||
NodeAt::Buffer { handle, byte } => (handle, byte),
|
||||
NodeAt::Memory { handle, byte, .. } if node_byte < 64 => (handle, byte),
|
||||
NodeAt::Memory { low, high, .. } => *second.get_or_insert_with(|| {
|
||||
let (low, high) = self.address_plus(low, high, 64);
|
||||
// Every lane in this block runs the instruction.
|
||||
let (handle, byte) = self.bvh_memory(low, high, None);
|
||||
let k64 = self.s.m.i32(64);
|
||||
(handle, self.s.m.bin(c, Bin::Sub, byte, k64))
|
||||
}),
|
||||
};
|
||||
if let Some(b) = base {
|
||||
byte = self.s.m.bin(c, Bin::Add, byte, b);
|
||||
}
|
||||
let k = self.s.m.i32(node_byte);
|
||||
let byte = self.s.m.bin(c, Bin::Add, byte, k);
|
||||
let mask = self.s.m.i8((1u8 << n) - 1);
|
||||
let r = self.s.op(
|
||||
c,
|
||||
"rawBufferLoad.f32",
|
||||
Attr::ReadOnly,
|
||||
self.s.t.res_ret,
|
||||
139,
|
||||
&[handle, byte, undef, mask, align],
|
||||
);
|
||||
for k in 0..n {
|
||||
let f = self.s.m.extract(c, r, k);
|
||||
out.push(self.as_int(f));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The node's title address, [`bvh::node_address`]: the descriptor's
|
||||
/// base (dword 0 and the low byte of dword 1, in 256-byte units) plus
|
||||
/// `(pointer >> 3) << 6`.
|
||||
fn bvh_address(&mut self, word0: V, word1: V, pointer: V, pointer_high: Option<V>) -> (V, V) {
|
||||
let c = self.cur;
|
||||
let i64t = self.s.m.int(64);
|
||||
let (zero, byte) = (self.s.m.i32(0), self.s.m.i32(0xff));
|
||||
let base_high = self.s.m.bin(c, Bin::And, word1, byte);
|
||||
let base = self.join64(word0, base_high);
|
||||
let k8 = self.s.m.int_const(i64t, 8);
|
||||
let base = self.s.m.bin(c, Bin::Shl, base, k8);
|
||||
let p = self.join64(pointer, pointer_high.unwrap_or(zero));
|
||||
let (k3, k6) = (self.s.m.int_const(i64t, 3), self.s.m.int_const(i64t, 6));
|
||||
let p = self.s.m.bin(c, Bin::LShr, p, k3);
|
||||
let p = self.s.m.bin(c, Bin::Shl, p, k6);
|
||||
let a = self.s.m.bin(c, Bin::Add, base, p);
|
||||
self.s.flags |= flags::INT64;
|
||||
self.split64(a)
|
||||
}
|
||||
|
||||
/// The box test ([`bvh::boxes`]): four result dwords. Starts in the
|
||||
/// current block and leaves `self.cur` at the block it ends in.
|
||||
fn bvh_boxes(&mut self, at: NodeAt, kind: V, ray: &Ray, sort: bool) -> [V; 4] {
|
||||
let head = self.cur;
|
||||
let children = self.bvh_node_words(at, None, 0, 4);
|
||||
let k5 = self.s.m.i32(5);
|
||||
let wide = self.s.m.cmp(head, pred::EQ, kind, k5);
|
||||
let (wide_block, half_block) = (self.s.m.new_block(), self.s.m.new_block());
|
||||
let join = self.s.m.new_block();
|
||||
self.s
|
||||
.m
|
||||
.terminate(head, Term::CondBr(wide, wide_block, half_block));
|
||||
// 32-bit floats: 24 dwords from byte 16.
|
||||
self.cur = wide_block;
|
||||
let k16 = self.s.m.i32(16);
|
||||
let words = self.bvh_node_words(at, None, 16, 24);
|
||||
let floats: Vec<V> = words.iter().map(|&w| self.as_float(w)).collect();
|
||||
self.s.m.terminate(wide_block, Term::Br(join));
|
||||
// 16-bit floats: 24 halves in 12 dwords from byte 16, the low half
|
||||
// of a dword first.
|
||||
self.cur = half_block;
|
||||
let words = self.bvh_node_words(at, None, 16, 12);
|
||||
let f32t = self.s.t.f32;
|
||||
let mut halves = Vec::with_capacity(24);
|
||||
for n in 0..24 {
|
||||
let mut h = words[n / 2];
|
||||
if n % 2 == 1 {
|
||||
h = self.s.m.bin(half_block, Bin::LShr, h, k16);
|
||||
}
|
||||
// The conversion reads the low 16 bits.
|
||||
halves.push(self.s.op(
|
||||
half_block,
|
||||
"legacyF16ToF32",
|
||||
Attr::ReadNone,
|
||||
f32t,
|
||||
131,
|
||||
&[h],
|
||||
));
|
||||
}
|
||||
self.s.m.terminate(half_block, Term::Br(join));
|
||||
self.cur = join;
|
||||
let mut coords = Vec::with_capacity(24);
|
||||
for n in 0..24 {
|
||||
let phi = self.s.m.phi(join, f32t);
|
||||
self.s
|
||||
.m
|
||||
.set_phi(phi, vec![(floats[n], wide_block), (halves[n], half_block)]);
|
||||
coords.push(phi);
|
||||
}
|
||||
// The inverse direction held finite ([`bvh::boxes`]).
|
||||
let (most, least) = (
|
||||
self.s.m.f32(f32::MAX.to_bits()),
|
||||
self.s.m.f32((-f32::MAX).to_bits()),
|
||||
);
|
||||
let inverse = ray.inverse.map(|x| {
|
||||
let x = self.binary(35, x, least);
|
||||
self.binary(36, x, most)
|
||||
});
|
||||
let c = join;
|
||||
let (none, infinity, fzero) = (
|
||||
self.s.m.i32(bvh::NONE),
|
||||
self.s.m.f32(f32::INFINITY.to_bits()),
|
||||
self.s.m.f32(0),
|
||||
);
|
||||
let mut ids = [none; 4];
|
||||
let mut distances = [infinity; 4];
|
||||
for n in 0..4 {
|
||||
let bx = &coords[6 * n..6 * n + 6];
|
||||
let (mut near, mut far) = ([fzero; 3], [fzero; 3]);
|
||||
for a in 0..3 {
|
||||
let low = self.s.m.bin(c, Bin::Sub, bx[a], ray.origin[a]);
|
||||
let low = self.s.m.bin(c, Bin::Mul, low, inverse[a]);
|
||||
let high = self.s.m.bin(c, Bin::Sub, bx[3 + a], ray.origin[a]);
|
||||
let high = self.s.m.bin(c, Bin::Mul, high, inverse[a]);
|
||||
near[a] = self.binary(36, low, high);
|
||||
far[a] = self.binary(35, low, high);
|
||||
}
|
||||
let enter = self.binary(35, near[0], near[1]);
|
||||
let enter = self.binary(35, enter, near[2]);
|
||||
let leave = self.binary(36, far[0], far[1]);
|
||||
let leave = self.binary(36, leave, far[2]);
|
||||
let from = self.binary(35, enter, fzero);
|
||||
// Ordered compares: a NaN anywhere is a miss.
|
||||
let through = self.s.m.cmp(c, pred::OGE, leave, from);
|
||||
let before = self.s.m.cmp(c, pred::OLT, enter, ray.extent);
|
||||
let off = self.is_nan_f32(bx[0]);
|
||||
let on = self.s.m.bool(true);
|
||||
let on = self.s.m.bin(c, Bin::Xor, off, on);
|
||||
let hit = self.s.m.bin(c, Bin::And, through, before);
|
||||
let hit = self.s.m.bin(c, Bin::And, hit, on);
|
||||
ids[n] = self.s.m.select(c, hit, children[n], none);
|
||||
distances[n] = self.s.m.select(c, hit, enter, infinity);
|
||||
}
|
||||
if sort {
|
||||
for (a, b) in [(0, 1), (2, 3), (0, 2), (1, 3), (1, 2)] {
|
||||
let swap = self.s.m.cmp(c, pred::OLT, distances[b], distances[a]);
|
||||
let (da, db) = (distances[a], distances[b]);
|
||||
distances[a] = self.s.m.select(c, swap, db, da);
|
||||
distances[b] = self.s.m.select(c, swap, da, db);
|
||||
let (ia, ib) = (ids[a], ids[b]);
|
||||
ids[a] = self.s.m.select(c, swap, ib, ia);
|
||||
ids[b] = self.s.m.select(c, swap, ia, ib);
|
||||
}
|
||||
}
|
||||
ids
|
||||
}
|
||||
|
||||
/// The triangle test ([`bvh::triangle`] of [`bvh::triangle_vertices`]):
|
||||
/// four result dwords, made in the current block.
|
||||
fn bvh_triangle(&mut self, at: NodeAt, kind: V, ray: &Ray) -> [V; 4] {
|
||||
let c = self.cur;
|
||||
let k = |l: &mut Self, v: u32| l.s.m.i32(v);
|
||||
// The triangle's byte of the dword at byte 60: which of its
|
||||
// vertices barycentric I and J weigh.
|
||||
let id = self.bvh_node_words(at, None, 60, 1)[0];
|
||||
let (k2, k3, k12, k15) = (k(self, 2), k(self, 3), k(self, 12), k(self, 15));
|
||||
let shift = self.s.m.bin(c, Bin::Shl, kind, k3);
|
||||
let id = self.s.m.bin(c, Bin::LShr, id, shift);
|
||||
let i = self.s.m.bin(c, Bin::And, id, k3);
|
||||
let j = self.s.m.bin(c, Bin::LShr, id, k2);
|
||||
let j = self.s.m.bin(c, Bin::And, j, k3);
|
||||
let first = self.s.m.bin(c, Bin::Sub, k3, i);
|
||||
let first = self.s.m.bin(c, Bin::Sub, first, j);
|
||||
let first = self.s.m.bin(c, Bin::And, first, k3);
|
||||
// The node's vertices the triangle is made of, four bits each.
|
||||
let (k0, k1) = (k(self, 0), k(self, 1));
|
||||
let maps: [V; 4] = std::array::from_fn(|n| k(self, bvh::vertex_map(n as u32)));
|
||||
let (is0, is1, is2) = (
|
||||
self.s.m.cmp(c, pred::EQ, kind, k0),
|
||||
self.s.m.cmp(c, pred::EQ, kind, k1),
|
||||
self.s.m.cmp(c, pred::EQ, kind, k2),
|
||||
);
|
||||
let map = self.s.m.select(c, is2, maps[2], maps[3]);
|
||||
let map = self.s.m.select(c, is1, maps[1], map);
|
||||
let map = self.s.m.select(c, is0, maps[0], map);
|
||||
let mut p = Vec::with_capacity(3);
|
||||
for n in [first, i, j] {
|
||||
let nibble = self.s.m.bin(c, Bin::Shl, n, k2);
|
||||
let vertex = self.s.m.bin(c, Bin::LShr, map, nibble);
|
||||
let vertex = self.s.m.bin(c, Bin::And, vertex, k15);
|
||||
let byte = self.s.m.bin(c, Bin::Mul, vertex, k12);
|
||||
let words = self.bvh_node_words(at, Some(byte), 0, 3);
|
||||
// Relative to the ray's origin.
|
||||
let r: Vec<V> = (0..3)
|
||||
.map(|a| {
|
||||
let f = self.as_float(words[a]);
|
||||
self.s.m.bin(c, Bin::Sub, f, ray.origin[a])
|
||||
})
|
||||
.collect();
|
||||
p.push([r[0], r[1], r[2]]);
|
||||
}
|
||||
// The ray's largest axis z, and x and y after it in an order that
|
||||
// keeps the winding.
|
||||
let fzero = self.s.m.f32(0);
|
||||
let size = ray.direction.map(|d| self.unary(6, d));
|
||||
let xy = self.s.m.cmp(c, pred::OGE, size[0], size[1]);
|
||||
let xz = self.s.m.cmp(c, pred::OGE, size[0], size[2]);
|
||||
let yz = self.s.m.cmp(c, pred::OGE, size[1], size[2]);
|
||||
let z0 = self.s.m.bin(c, Bin::And, xy, xz);
|
||||
let on = self.s.m.bool(true);
|
||||
let not_xy = self.s.m.bin(c, Bin::Xor, xy, on);
|
||||
let z1 = self.s.m.bin(c, Bin::And, not_xy, yz);
|
||||
// Component (kz + n) % 3 of `q`.
|
||||
let pick = |l: &mut Self, q: [V; 3], n: usize| {
|
||||
let rest = l.s.m.select(c, z1, q[(1 + n) % 3], q[(2 + n) % 3]);
|
||||
l.s.m.select(c, z0, q[n % 3], rest)
|
||||
};
|
||||
let dz = pick(self, ray.direction, 0);
|
||||
let backwards = self.s.m.cmp(c, pred::OLT, dz, fzero);
|
||||
// (x, y, z) of `q`: the two after the largest axis, swapped for a
|
||||
// ray that runs backwards along it.
|
||||
let axes = |l: &mut Self, q: [V; 3]| {
|
||||
let (x, y) = (pick(l, q, 1), pick(l, q, 2));
|
||||
[
|
||||
l.s.m.select(c, backwards, y, x),
|
||||
l.s.m.select(c, backwards, x, y),
|
||||
pick(l, q, 0),
|
||||
]
|
||||
};
|
||||
let d = axes(self, ray.direction);
|
||||
let sz = pick(self, ray.inverse, 0);
|
||||
let sx = self.s.m.bin(c, Bin::Mul, d[0], sz);
|
||||
let sy = self.s.m.bin(c, Bin::Mul, d[1], sz);
|
||||
let mut sheared = Vec::with_capacity(3);
|
||||
for r in p {
|
||||
let r = axes(self, r);
|
||||
let x = self.s.m.bin(c, Bin::Mul, sx, r[2]);
|
||||
let x = self.s.m.bin(c, Bin::Sub, r[0], x);
|
||||
let y = self.s.m.bin(c, Bin::Mul, sy, r[2]);
|
||||
let y = self.s.m.bin(c, Bin::Sub, r[1], y);
|
||||
let z = self.s.m.bin(c, Bin::Mul, sz, r[2]);
|
||||
sheared.push((x, y, z));
|
||||
}
|
||||
let [(ax, ay, az), (bx, by, bz), (cx, cy, cz)] = sheared[..] else {
|
||||
unreachable!()
|
||||
};
|
||||
// p * q - r * s.
|
||||
let cross = |l: &mut Self, p: V, q: V, r: V, s: V| {
|
||||
let a = l.s.m.bin(c, Bin::Mul, p, q);
|
||||
let b = l.s.m.bin(c, Bin::Mul, r, s);
|
||||
l.s.m.bin(c, Bin::Sub, a, b)
|
||||
};
|
||||
let u = cross(self, cx, by, cy, bx);
|
||||
let v = cross(self, ax, cy, ay, cx);
|
||||
let w = cross(self, bx, ay, by, ax);
|
||||
let any = |l: &mut Self, p: u8| {
|
||||
let a = l.s.m.cmp(c, p, u, fzero);
|
||||
let b = l.s.m.cmp(c, p, v, fzero);
|
||||
let d = l.s.m.cmp(c, p, w, fzero);
|
||||
let a = l.s.m.bin(c, Bin::Or, a, b);
|
||||
l.s.m.bin(c, Bin::Or, a, d)
|
||||
};
|
||||
let behind = any(self, pred::OLT);
|
||||
let before = any(self, pred::OGT);
|
||||
let outside = self.s.m.bin(c, Bin::And, behind, before);
|
||||
let inside = self.s.m.bin(c, Bin::Xor, outside, on);
|
||||
let det = self.s.m.bin(c, Bin::Add, v, w);
|
||||
let det = self.s.m.bin(c, Bin::Add, u, det);
|
||||
let t = self.s.m.bin(c, Bin::Mul, u, az);
|
||||
let t2 = self.s.m.bin(c, Bin::Mul, v, bz);
|
||||
let t = self.s.m.bin(c, Bin::Add, t, t2);
|
||||
let t2 = self.s.m.bin(c, Bin::Mul, w, cz);
|
||||
let t = self.s.m.bin(c, Bin::Add, t, t2);
|
||||
// The distance is not negative: the numerator has the
|
||||
// denominator's sign (or is 0). Ordered compares: a denominator
|
||||
// of 0 or a NaN is a miss.
|
||||
let front = self.s.m.cmp(c, pred::OGT, det, fzero);
|
||||
let front_ahead = self.s.m.cmp(c, pred::OGE, t, fzero);
|
||||
let front = self.s.m.bin(c, Bin::And, front, front_ahead);
|
||||
let back = self.s.m.cmp(c, pred::OLT, det, fzero);
|
||||
let back_ahead = self.s.m.cmp(c, pred::OLE, t, fzero);
|
||||
let back = self.s.m.bin(c, Bin::And, back, back_ahead);
|
||||
let ahead = self.s.m.bin(c, Bin::Or, front, back);
|
||||
let hit = self.s.m.bin(c, Bin::And, inside, ahead);
|
||||
let miss = bvh::MISS.map(|f| self.s.m.f32(f.to_bits()));
|
||||
let out = [t, det, v, w];
|
||||
std::array::from_fn(|n| {
|
||||
let f = self.s.m.select(c, hit, out[n], miss[n]);
|
||||
self.as_int(f)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,690 @@
|
||||
//! The ray-tracing node test end to end: a synthetic compute program that
|
||||
//! runs `image_bvh64_intersect_ray` (or the 32-bit form) once per thread,
|
||||
//! lowered to DXIL, validated by `dxil.dll` when present, run on the host
|
||||
//! GPU and WARP, and compared dword for dword with the CPU reference
|
||||
//! ([`crate::bvh`]).
|
||||
//!
|
||||
//! The nodes are in a raw buffer. Two ways to name it are run: the
|
||||
//! buffer's descriptor from the program's table (a resource of the host,
|
||||
//! [`crate::resource::BvhNodes::Resource`]), and the title's way, a
|
||||
//! descriptor of numbers over title memory with the structure's address in
|
||||
//! the node pointer or in the descriptor. These tests have no host that
|
||||
//! keeps copies of title memory and their directory, so for the second
|
||||
//! they put a stand-in under the node reader
|
||||
//! (`lower::intersect::TEST_MEMORY`); without it the same program reads
|
||||
//! through the directory, which is only checked to lower and validate.
|
||||
|
||||
use super::host::{Dispatch, Host, Root, Stride, View};
|
||||
use super::lower::intersect::TEST_MEMORY;
|
||||
use super::{HostShader, lower, validator};
|
||||
use crate::bvh::{self, Ray, tests as nodes};
|
||||
use crate::native::{
|
||||
ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource,
|
||||
};
|
||||
use crate::resource::BvhNodes;
|
||||
use crate::{ShaderError, io, ir, resource, structure};
|
||||
|
||||
/// Threads of one group, each with its own record.
|
||||
const THREADS: u32 = 32;
|
||||
/// Bytes of a thread's record: the node pointer (two dwords), the ray's
|
||||
/// extent, origin, direction and inverse direction, and whether the
|
||||
/// thread runs the instruction.
|
||||
const RECORD: u32 = 64;
|
||||
/// Where the nodes start in the buffer.
|
||||
const NODES: u32 = THREADS * RECORD;
|
||||
/// What the result registers hold before the instruction.
|
||||
const BEFORE: [u32; 4] = [1, 2, 3, 4];
|
||||
|
||||
/// How the program names the nodes' memory.
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum Descriptor {
|
||||
/// The buffer's descriptor from the table.
|
||||
Table,
|
||||
/// Numbers, as the title builds it: dwords 0 and 1 (the base address
|
||||
/// in 256-byte units and the box sorting bit); the size and the rest of
|
||||
/// the flags as the title sets them.
|
||||
Numbers(u32, u32),
|
||||
}
|
||||
|
||||
/// The descriptor the title builds for the 64-bit form: the whole address
|
||||
/// space, sorted boxes, barycentrics returned.
|
||||
const WHOLE: Descriptor = Descriptor::Numbers(0, bvh::BOX_SORT);
|
||||
|
||||
/// The program: per thread, the record's twelve operand dwords in v1-v12,
|
||||
/// the instruction's result in v13-v16 (under a lane mask of the threads
|
||||
/// whose record says so), stored to the UAV at 16 bytes a thread.
|
||||
fn program(wide: bool, descriptor: Descriptor) -> Vec<u32> {
|
||||
let mut w = vec![
|
||||
0xBE85_0380, // s_mov_b32 s5, 0
|
||||
0xF408_0202,
|
||||
0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], 0x0
|
||||
0xF408_0302,
|
||||
0xFA00_0020, // s_load_dwordx4 s[12:15], s[4:5], 0x20
|
||||
0x3428_0086, // v_lshlrev_b32 v20, 6, v0
|
||||
0xE038_1000,
|
||||
0x8002_0114, // buffer_load_dwordx4 v[1:4], v20, s[8:11], 0 offen
|
||||
0xE038_1010,
|
||||
0x8002_0514, // buffer_load_dwordx4 v[5:8], v20, s[8:11], 0 offen offset:16
|
||||
0xE038_1020,
|
||||
0x8002_0914, // buffer_load_dwordx4 v[9:12], v20, s[8:11], 0 offen offset:32
|
||||
0xE030_1030,
|
||||
0x8002_1114, // buffer_load_dword v17, v20, s[8:11], 0 offen offset:48
|
||||
];
|
||||
for k in 0..4u32 {
|
||||
// v_mov_b32 v13+k, 1+k
|
||||
w.push(0x7E00_0200 | (13 + k) << 17 | (0x81 + k));
|
||||
}
|
||||
let rsrc = match descriptor {
|
||||
Descriptor::Table => 8,
|
||||
Descriptor::Numbers(word0, word1) => {
|
||||
// s_mov_b32 s24, word0
|
||||
w.extend([0xBE98_03FF, word0]);
|
||||
if word1 == bvh::BOX_SORT {
|
||||
// As the title makes it.
|
||||
w.push(0xBE99_0B81); // s_brev_b32 s25, 1
|
||||
} else {
|
||||
w.extend([0xBE99_03FF, word1]); // s_mov_b32 s25, word1
|
||||
}
|
||||
w.extend([
|
||||
0xBE9A_03C1, // s_mov_b32 s26, -1
|
||||
0xBE9B_03FF,
|
||||
0x8900_03FF, // s_mov_b32 s27, 0x890003ff
|
||||
]);
|
||||
24
|
||||
}
|
||||
};
|
||||
w.extend([
|
||||
0xBE94_037E, // s_mov_b32 s20, exec_lo
|
||||
0x7DAA_2280, // v_cmpx_ne_u32 exec_lo, 0, v17
|
||||
]);
|
||||
let first = 0x0000_0D01 | (rsrc >> 2) << 16;
|
||||
if wide {
|
||||
// image_bvh64_intersect_ray v[13:16], [v1 .. v12], s[rsrc:rsrc+3]
|
||||
w.extend([0xF19C_9F07, first, 0x0504_0302, 0x0908_0706, 0x000C_0B0A]);
|
||||
} else {
|
||||
// image_bvh_intersect_ray v[13:16], [v1, v3 .. v12], s[rsrc:rsrc+3]
|
||||
w.extend([0xF198_9F07, first, 0x0605_0403, 0x0A09_0807, 0x0000_0C0B]);
|
||||
}
|
||||
w.extend([
|
||||
0xBEFE_0314, // s_mov_b32 exec_lo, s20
|
||||
0x342A_0084, // v_lshlrev_b32 v21, 4, v0
|
||||
0xE078_1000,
|
||||
0x8003_0D15, // buffer_store_dwordx4 v[13:16], v21, s[12:15], 0 offen
|
||||
0xBF81_0000, // s_endpgm
|
||||
]);
|
||||
w
|
||||
}
|
||||
|
||||
fn native(words: &[u32]) -> NativeProgram {
|
||||
let table = |kind, at| UsedResource {
|
||||
kind,
|
||||
root: RootType::Table,
|
||||
table_offset_dwords: at,
|
||||
lower_bound: 0,
|
||||
stride: 4,
|
||||
dwords: 4,
|
||||
user_data: 4,
|
||||
slot: 1,
|
||||
};
|
||||
NativeProgram {
|
||||
stage: HwStage::Cs,
|
||||
wave64: false,
|
||||
vgprs: 22,
|
||||
layout: vec![
|
||||
RootParam {
|
||||
root: RootType::Constants,
|
||||
table_offset_dwords: 0,
|
||||
sgprs: 4,
|
||||
base_register: 0,
|
||||
user_data: 0,
|
||||
slot: 0,
|
||||
},
|
||||
RootParam {
|
||||
root: RootType::Table,
|
||||
table_offset_dwords: 0,
|
||||
sgprs: 1,
|
||||
base_register: 0,
|
||||
user_data: 4,
|
||||
slot: 1,
|
||||
},
|
||||
],
|
||||
used: vec![table(ResourceType::Srv, 0), table(ResourceType::Uav, 8)],
|
||||
io: StageIo::Cs(ComputeIo {
|
||||
rsrc2: 5 << 1,
|
||||
threads: [THREADS, 1, 1],
|
||||
}),
|
||||
code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Lowers the program; the DXIL is validated when the validator is there.
|
||||
fn build(
|
||||
wide: bool,
|
||||
descriptor: Descriptor,
|
||||
) -> Result<(HostShader, resource::Resources), ShaderError> {
|
||||
let native = native(&program(wide, descriptor));
|
||||
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
|
||||
let st = structure::structure(&p).expect("structure");
|
||||
let res = resource::track(&p, &native.layout, native.stage, Some(&st))?;
|
||||
let io = io::raise(&p, &native).expect("io::raise");
|
||||
let lowered = lower::lower(&lower::Parts {
|
||||
native: &native,
|
||||
p: &p,
|
||||
st: &st,
|
||||
io: &io,
|
||||
res: &res,
|
||||
inputs: Vec::new(),
|
||||
outputs: Vec::new(),
|
||||
prims: Vec::new(),
|
||||
mesh_stride: 0,
|
||||
})?;
|
||||
let shader = HostShader {
|
||||
stage: HwStage::Cs,
|
||||
dxil: lowered.dxil,
|
||||
user_data: lowered.user_data,
|
||||
samplers: lowered.samplers,
|
||||
static_samplers: Vec::new(),
|
||||
root_cbvs: lowered.root_cbvs,
|
||||
root_srvs: lowered.root_srvs,
|
||||
root_uavs: lowered.root_uavs,
|
||||
root_indexed_views: res.root_indexed_views.clone(),
|
||||
};
|
||||
if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
|
||||
let mut copy = shader.dxil.clone();
|
||||
v.validate(&mut copy).expect("DXIL validation failed");
|
||||
}
|
||||
Ok((shader, res))
|
||||
}
|
||||
|
||||
/// One thread's test: a node (by its index in the node list), the kind its
|
||||
/// pointer carries, and the ray; `None` leaves the thread masked out.
|
||||
type Case = Option<(usize, u32, Ray)>;
|
||||
|
||||
/// The scene: node dwords (a 32-bit box node takes 32, the others 16) and
|
||||
/// where each node starts, in dwords from the first node.
|
||||
struct Scene {
|
||||
words: Vec<u32>,
|
||||
starts: Vec<usize>,
|
||||
}
|
||||
|
||||
impl Scene {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
words: Vec::new(),
|
||||
starts: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds a node of `dwords` (16 or 32) and returns its index.
|
||||
fn add(&mut self, node: [u32; 28], dwords: usize) -> usize {
|
||||
self.starts.push(self.words.len());
|
||||
let mut padded = [0u32; 32];
|
||||
padded[..28].copy_from_slice(&node);
|
||||
// Bytes the instruction must not read as part of the node: what
|
||||
// follows a 64-byte node, and a box node's last 16 bytes.
|
||||
for w in padded.iter_mut().skip(if dwords == 16 { 16 } else { 28 }) {
|
||||
*w = 0x7fc0_dead;
|
||||
}
|
||||
self.words.extend(&padded[..dwords]);
|
||||
self.starts.len() - 1
|
||||
}
|
||||
|
||||
/// The pointer of node `n` with `kind`, counted from the first node.
|
||||
fn pointer(&self, n: usize, kind: u32) -> u32 {
|
||||
(4 * self.starts[n] as u32) >> 3 | kind
|
||||
}
|
||||
|
||||
/// What the instruction reads of node `n`.
|
||||
fn node(&self, n: usize) -> [u32; 28] {
|
||||
std::array::from_fn(|k| self.words.get(self.starts[n] + k).copied().unwrap_or(0))
|
||||
}
|
||||
}
|
||||
|
||||
/// A small generator of repeatable numbers.
|
||||
struct Numbers(u64);
|
||||
|
||||
impl Numbers {
|
||||
fn next(&mut self) -> u32 {
|
||||
self.0 = self
|
||||
.0
|
||||
.wrapping_mul(6364136223846793005)
|
||||
.wrapping_add(1442695040888963407);
|
||||
(self.0 >> 33) as u32
|
||||
}
|
||||
|
||||
/// A float in -1..1 in steps of 1/4096 (exactly representable).
|
||||
fn unit(&mut self) -> f32 {
|
||||
(self.next() % 8193) as f32 / 4096.0 - 1.0
|
||||
}
|
||||
|
||||
fn vector(&mut self, scale: f32) -> [f32; 3] {
|
||||
[
|
||||
self.unit() * scale,
|
||||
self.unit() * scale,
|
||||
self.unit() * scale,
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
/// The scene and batches of cases over it.
|
||||
fn scene() -> (Scene, Vec<Vec<Case>>) {
|
||||
let mut s = Scene::new();
|
||||
let mut g = Numbers(0x5eed);
|
||||
const UNIT: [f32; 6] = [-1.0, -1.0, -1.0, 1.0, 1.0, 1.0];
|
||||
let moved =
|
||||
|b: [f32; 6], by: [f32; 3]| -> [f32; 6] { std::array::from_fn(|k| b[k] + by[k % 3]) };
|
||||
let off = [f32::NAN; 6];
|
||||
let mut box_nodes = Vec::new();
|
||||
// The boxes of the reference's own tests, in both widths.
|
||||
let lined = [
|
||||
moved(UNIT, [30.0, 0.0, 0.0]),
|
||||
moved(UNIT, [10.0, 0.0, 0.0]),
|
||||
moved(UNIT, [10.0, 5.0, 0.0]),
|
||||
moved(UNIT, [20.0, 0.0, 0.0]),
|
||||
];
|
||||
let ids = [0x105, 0x20c, 0x304, 0x400];
|
||||
box_nodes.push((s.add(nodes::box32(ids, lined), 32), 5));
|
||||
box_nodes.push((s.add(nodes::box16(ids, lined), 16), 4));
|
||||
// Boxes around the origin, one switched off, one child missing.
|
||||
let around = [
|
||||
UNIT,
|
||||
moved(UNIT, [0.5, 0.5, 0.5]),
|
||||
off,
|
||||
[-4.0, -0.25, -0.25, 4.0, 0.25, 0.25],
|
||||
];
|
||||
let ids2 = [8, bvh::NONE, 24, 0x1fff_fffc];
|
||||
box_nodes.push((s.add(nodes::box32(ids2, around), 32), 5));
|
||||
box_nodes.push((s.add(nodes::box16(ids2, around), 16), 4));
|
||||
// Random boxes.
|
||||
for n in 0..6 {
|
||||
let boxes: [[f32; 6]; 4] = std::array::from_fn(|_| {
|
||||
let (c, h) = (g.vector(8.0), g.vector(2.0).map(f32::abs));
|
||||
std::array::from_fn(|k| c[k % 3] + if k < 3 { -h[k] } else { h[k - 3] })
|
||||
});
|
||||
let ids: [u32; 4] = std::array::from_fn(|k| 0x1000 * (n + 1) + 8 * k as u32 + 5);
|
||||
if n % 2 == 0 {
|
||||
box_nodes.push((s.add(nodes::box32(ids, boxes), 32), 5));
|
||||
} else {
|
||||
box_nodes.push((s.add(nodes::box16(ids, boxes), 16), 4));
|
||||
}
|
||||
}
|
||||
// Triangles: one of the reference's tests, a pair as the title's
|
||||
// builder stores it, all four triangles of a full node with turned
|
||||
// ids, random ones.
|
||||
let mut triangle_nodes = Vec::new();
|
||||
let front = [[0.0, 2.0, 5.0], [2.0, -2.0, 5.0], [-2.0, -2.0, 5.0]];
|
||||
triangle_nodes.push((s.add(nodes::triangles(&front, 9), 16), 0));
|
||||
let pair = s.add(
|
||||
nodes::triangles(
|
||||
&[front[0], front[1], front[2], [2.0, 2.0, 5.0]],
|
||||
9 | 0x80 | 6 << 8,
|
||||
),
|
||||
16,
|
||||
);
|
||||
triangle_nodes.extend([(pair, 0), (pair, 1)]);
|
||||
let five = [
|
||||
[-3.0, -1.0, 6.0],
|
||||
[-1.0, 2.0, 6.5],
|
||||
[1.0, -1.0, 6.0],
|
||||
[3.0, 2.0, 6.5],
|
||||
[5.0, -1.0, 7.0],
|
||||
];
|
||||
// I and J per triangle: (1, 2), (2, 0), (0, 1), (1, 2).
|
||||
let full = s.add(nodes::triangles(&five, 9 | 2 << 8 | 4 << 16 | 9 << 24), 16);
|
||||
triangle_nodes.extend((0..4).map(|k| (full, k)));
|
||||
for _ in 0..5 {
|
||||
let c = g.vector(6.0);
|
||||
let v: [[f32; 3]; 3] = std::array::from_fn(|_| {
|
||||
let d = g.vector(3.0);
|
||||
[c[0] + d[0], c[1] + d[1], c[2] + d[2]]
|
||||
});
|
||||
triangle_nodes.push((s.add(nodes::triangles(&v, 9), 16), 0));
|
||||
}
|
||||
let mut cases: Vec<Case> = Vec::new();
|
||||
// Rays of the reference's tests against the lined-up boxes.
|
||||
for &(n, kind) in &box_nodes[..2] {
|
||||
for (origin, direction, extent) in [
|
||||
([0.0; 3], [1.0, 0.0, 0.0], 1000.0),
|
||||
([0.0; 3], [1.0, 0.0, 0.0], 19.5),
|
||||
([0.0; 3], [1.0, 0.0, 0.0], 19.0),
|
||||
([0.0; 3], [-1.0, 0.0, 0.0], 1000.0),
|
||||
([40.0, 0.0, 0.0], [-2.0, 0.0, 0.0], 1000.0),
|
||||
([0.0, -1.0, 0.0], [1.0, 0.0, 0.0], 1000.0),
|
||||
([0.0, 1.0, 0.0], [1.0, 0.0, 0.0], 1000.0),
|
||||
([0.0, 0.5, 0.25], [1.0, -0.0, 0.0], 1000.0),
|
||||
([0.0; 3], [0.0; 3], 1000.0),
|
||||
] {
|
||||
cases.push(Some((n, kind, Ray::new(origin, direction, extent))));
|
||||
}
|
||||
}
|
||||
// Random rays at every box node, half of them aimed at a box.
|
||||
for &(n, kind) in &box_nodes {
|
||||
let words = s.node(n);
|
||||
let boxes = if kind == 5 {
|
||||
bvh::boxes32(&words)
|
||||
} else {
|
||||
bvh::boxes16(&words)
|
||||
};
|
||||
for k in 0..12 {
|
||||
let origin = g.vector(12.0);
|
||||
let direction = if k % 2 == 0 {
|
||||
let b = boxes[(k / 2) % 4];
|
||||
if b[0].is_nan() {
|
||||
g.vector(1.0)
|
||||
} else {
|
||||
std::array::from_fn(|a| (b[a] + b[3 + a]) / 2.0 - origin[a] + g.unit() / 2.0)
|
||||
}
|
||||
} else {
|
||||
g.vector(1.0)
|
||||
};
|
||||
let extent = if k % 3 == 0 { 6.0 } else { 100.0 };
|
||||
cases.push(Some((n, kind, Ray::new(origin, direction, extent))));
|
||||
}
|
||||
}
|
||||
// Rays at every triangle: aimed inside, at an edge, at a vertex, past
|
||||
// it, from both sides, along each axis.
|
||||
for &(n, kind) in &triangle_nodes {
|
||||
let p = bvh::triangle_vertices(&s.node(n), kind);
|
||||
let at = |w: [f32; 3]| -> [f32; 3] {
|
||||
std::array::from_fn(|a| w[0] * p[0][a] + w[1] * p[1][a] + w[2] * p[2][a])
|
||||
};
|
||||
for (k, w) in [
|
||||
[0.5, 0.25, 0.25],
|
||||
[0.125, 0.75, 0.125],
|
||||
[0.5, 0.5, 0.0],
|
||||
[0.0, 0.5, 0.5],
|
||||
[1.0, 0.0, 0.0],
|
||||
[0.75, 0.75, -0.5],
|
||||
[-0.25, 0.5, 0.75],
|
||||
[0.25, 0.25, 0.5],
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
let target = at(w);
|
||||
let origin = if k % 2 == 0 { [0.0; 3] } else { g.vector(16.0) };
|
||||
let mut direction: [f32; 3] = std::array::from_fn(|a| target[a] - origin[a]);
|
||||
if k == 7 {
|
||||
// The triangle lies behind.
|
||||
direction = direction.map(|d| -d);
|
||||
}
|
||||
cases.push(Some((n, kind, Ray::new(origin, direction, 100.0))));
|
||||
}
|
||||
for axis in 0..3 {
|
||||
for sign in [1.0f32, -1.0] {
|
||||
let target = at([0.25, 0.5, 0.25]);
|
||||
let mut origin = target;
|
||||
origin[axis] -= 8.0 * sign;
|
||||
let mut direction = [0.0; 3];
|
||||
direction[axis] = sign;
|
||||
cases.push(Some((n, kind, Ray::new(origin, direction, 100.0))));
|
||||
}
|
||||
}
|
||||
}
|
||||
// Kinds the instruction does not read, and threads masked out.
|
||||
let ray = Ray::new([0.0; 3], [0.0, 0.0, 1.0], 100.0);
|
||||
cases.extend([
|
||||
Some((triangle_nodes[0].0, 6, ray)),
|
||||
Some((triangle_nodes[0].0, 7, ray)),
|
||||
None,
|
||||
Some((
|
||||
box_nodes[0].0,
|
||||
5,
|
||||
Ray::new([0.0; 3], [1.0, 0.0, 0.0], 1000.0),
|
||||
)),
|
||||
None,
|
||||
]);
|
||||
let batches = cases
|
||||
.chunks(THREADS as usize)
|
||||
.map(<[Case]>::to_vec)
|
||||
.collect();
|
||||
(s, batches)
|
||||
}
|
||||
|
||||
/// The buffer for one batch: the threads' records, then the nodes. Node
|
||||
/// pointers count from `base` before the first node, in bytes.
|
||||
fn buffer(scene: &Scene, batch: &[Case], base: u64) -> Vec<u32> {
|
||||
let mut data = vec![0u32; (NODES / 4) as usize];
|
||||
for (t, case) in batch.iter().enumerate() {
|
||||
let Some((n, kind, ray)) = case else { continue };
|
||||
let r = &mut data[t * (RECORD / 4) as usize..][..13];
|
||||
let pointer = (base >> 3) + u64::from(scene.pointer(*n, *kind));
|
||||
(r[0], r[1]) = (pointer as u32, (pointer >> 32) as u32);
|
||||
r[2] = ray.extent.to_bits();
|
||||
for a in 0..3 {
|
||||
r[3 + a] = ray.origin[a].to_bits();
|
||||
r[6 + a] = ray.direction[a].to_bits();
|
||||
r[9 + a] = ray.inverse[a].to_bits();
|
||||
}
|
||||
r[12] = 1;
|
||||
}
|
||||
data.extend(&scene.words);
|
||||
data
|
||||
}
|
||||
|
||||
fn expected(scene: &Scene, case: &Case, sort: bool) -> [u32; 4] {
|
||||
match case {
|
||||
Some((n, kind, ray)) => bvh::intersect(&scene.node(*n), *kind, ray, sort),
|
||||
None => BEFORE,
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the tests' title memory for this thread until dropped.
|
||||
struct Memory;
|
||||
|
||||
impl Memory {
|
||||
fn at(base: u64) -> Self {
|
||||
// Heap slot 0: the buffer of records and nodes.
|
||||
TEST_MEMORY.set(Some((0, base)));
|
||||
Self
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Memory {
|
||||
fn drop(&mut self) {
|
||||
TEST_MEMORY.set(None);
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs every batch on the hardware adapter and WARP and compares with
|
||||
/// the reference. `pointers` is what node pointers count from, in bytes
|
||||
/// before the first node.
|
||||
fn run(wide: bool, descriptor: Descriptor, pointers: u64, sort: bool) {
|
||||
let (shader, res) = build(wide, descriptor).expect("the program lowers");
|
||||
assert_eq!(res.bvh.len(), 1);
|
||||
let (scene, batches) = scene();
|
||||
// The reference must see a bit of everything, or the comparison
|
||||
// proves little.
|
||||
let all: Vec<&Case> = batches.iter().flatten().collect();
|
||||
let results: Vec<[u32; 4]> = all.iter().map(|c| expected(&scene, c, sort)).collect();
|
||||
let boxes = |hits: usize| {
|
||||
all.iter()
|
||||
.zip(&results)
|
||||
.filter(|(c, r)| {
|
||||
matches!(c, Some((_, 4 | 5, _)))
|
||||
&& r.iter().filter(|&&x| x != bvh::NONE).count() == hits
|
||||
})
|
||||
.count()
|
||||
};
|
||||
let triangles = |hit: bool| {
|
||||
all.iter()
|
||||
.zip(&results)
|
||||
.filter(|(c, r)| {
|
||||
matches!(c, Some((_, 0..=3, _))) && (r[0] != f32::INFINITY.to_bits()) == hit
|
||||
})
|
||||
.count()
|
||||
};
|
||||
assert!(
|
||||
boxes(0) > 5 && boxes(1) > 5 && boxes(2) > 5 && boxes(3) > 0,
|
||||
"box cases"
|
||||
);
|
||||
assert!(
|
||||
triangles(true) > 30 && triangles(false) > 30,
|
||||
"triangle cases"
|
||||
);
|
||||
// Sorting must matter to some case, or the unsorted run proves nothing.
|
||||
assert!(
|
||||
all.iter()
|
||||
.any(|c| expected(&scene, c, true) != expected(&scene, c, false)),
|
||||
"no case tells sorted from unsorted"
|
||||
);
|
||||
let _one = super::valu_tests::ONE_AT_A_TIME
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner());
|
||||
let mut ran = 0;
|
||||
for (label, warp) in [("hardware", false), ("warp", true)] {
|
||||
let Ok(host) = Host::new(warp) else {
|
||||
eprintln!("no SM 6.6 {label} device; skipped");
|
||||
continue;
|
||||
};
|
||||
let (root, pso) = host
|
||||
.compute_pipeline(&shader)
|
||||
.unwrap_or_else(|e| panic!("{label}: compute_pipeline failed: {e}"));
|
||||
for (b, batch) in batches.iter().enumerate() {
|
||||
let data = buffer(&scene, batch, pointers);
|
||||
let out = host
|
||||
.dispatch(
|
||||
&root,
|
||||
&pso,
|
||||
&Dispatch {
|
||||
roots: vec![(0, Root::Constants(vec![0; 5]))],
|
||||
views: &[
|
||||
View::Buffer {
|
||||
data: &data,
|
||||
stride: Stride::Raw,
|
||||
},
|
||||
View::RawUav(4 * THREADS),
|
||||
],
|
||||
samplers: &[],
|
||||
groups: [1, 1, 1],
|
||||
},
|
||||
)
|
||||
.unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}"));
|
||||
for t in 0..THREADS as usize {
|
||||
let case = batch.get(t).copied().flatten();
|
||||
let want = match batch.get(t) {
|
||||
Some(c) => expected(&scene, c, sort),
|
||||
// A thread past the batch: its record is zeros, so it
|
||||
// is masked out.
|
||||
None => BEFORE,
|
||||
};
|
||||
let got = &out[0][4 * t..4 * t + 4];
|
||||
assert_eq!(
|
||||
got,
|
||||
want,
|
||||
"{label}, batch {b} thread {t}: {case:x?}\n got {:x?} = {:?}\nwant {:x?} = {:?}",
|
||||
got,
|
||||
got.iter().map(|&x| f32::from_bits(x)).collect::<Vec<_>>(),
|
||||
want,
|
||||
want.map(f32::from_bits),
|
||||
);
|
||||
}
|
||||
}
|
||||
ran += 1;
|
||||
}
|
||||
assert!(ran > 0, "no SM 6.6 device available");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_64_bit_node_test_in_a_host_buffer_matches_the_reference_on_the_card() {
|
||||
// Pointers count from the buffer's start.
|
||||
run(true, Descriptor::Table, u64::from(NODES), true);
|
||||
assert_eq!(
|
||||
build(true, Descriptor::Table).unwrap().1.bvh[0].1,
|
||||
BvhNodes::Resource
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_32_bit_node_test_in_a_host_buffer_matches_the_reference_on_the_card() {
|
||||
run(false, Descriptor::Table, u64::from(NODES), true);
|
||||
}
|
||||
|
||||
/// Where the tests' title memory puts the buffer: past 4 GiB, on 256 bytes.
|
||||
const BASE: u64 = 0x12_3456_7800;
|
||||
|
||||
#[test]
|
||||
fn the_64_bit_node_test_over_title_memory_matches_the_reference_on_the_card() {
|
||||
// The title's way: one descriptor for all of memory, the structure's
|
||||
// address folded into a 64-bit pointer.
|
||||
let _memory = Memory::at(BASE);
|
||||
run(true, WHOLE, BASE + u64::from(NODES), true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_32_bit_node_test_over_title_memory_matches_the_reference_on_the_card() {
|
||||
// The title's other way: the structure's address in the descriptor
|
||||
// (in 256-byte units, 40 bits), a 32-bit pointer from there. Here with
|
||||
// an address past 2^40 bytes, and without box sorting.
|
||||
let base = 0x312_3456_7800u64;
|
||||
let structure = base + u64::from(NODES);
|
||||
let _memory = Memory::at(base);
|
||||
let descriptor = Descriptor::Numbers((structure >> 8) as u32, (structure >> 40) as u32);
|
||||
run(false, descriptor, 0, false);
|
||||
// And sorted.
|
||||
let descriptor = Descriptor::Numbers(
|
||||
(structure >> 8) as u32,
|
||||
(structure >> 40) as u32 | bvh::BOX_SORT,
|
||||
);
|
||||
run(false, descriptor, 0, true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_descriptor_of_numbers_is_title_memory_read_through_the_directory() {
|
||||
for wide in [true, false] {
|
||||
let native = native(&program(wide, WHOLE));
|
||||
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
|
||||
let st = structure::structure(&p).expect("structure");
|
||||
let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("tracked");
|
||||
// The flags the title sets: sorted boxes, barycentrics, a
|
||||
// ray-tracing structure. No resource is taken for it: the buffer
|
||||
// loads' and the store's descriptors are all there is.
|
||||
assert_eq!(res.bvh.len(), 1);
|
||||
assert_eq!(
|
||||
res.bvh[0].1,
|
||||
BvhNodes::Memory {
|
||||
word1: 0x8000_0000,
|
||||
word3: 0x8900_03ff
|
||||
}
|
||||
);
|
||||
assert_eq!(res.descriptors.len(), 5);
|
||||
// Without the tests' stand-in the nodes are read as the title's
|
||||
// programs will read them: through the host's directory of title
|
||||
// memory. The program lowers and validates, and asks the host for
|
||||
// the directory and for the list of pages it found no copy of.
|
||||
let (shader, _) = build(wide, WHOLE).expect("lowers through the directory");
|
||||
assert!(shader.root_srvs.contains(&super::SLOT_MEMORY));
|
||||
assert!(shader.root_uavs.contains(&super::SLOT_FAULTS));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_structure_that_returns_triangle_ids_is_refused_by_name() {
|
||||
// Triangle return mode 0 (bit 24 of dword 3 clear): the last two
|
||||
// result dwords would be a triangle id and a hit status.
|
||||
let mut words = program(true, WHOLE);
|
||||
let flags = words.iter().position(|&w| w == 0x8900_03FF).unwrap();
|
||||
words[flags] = 0x8800_03FF;
|
||||
let native = native(&words);
|
||||
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
|
||||
let st = structure::structure(&p).expect("structure");
|
||||
let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("tracked");
|
||||
let io = io::raise(&p, &native).expect("io::raise");
|
||||
let r = lower::lower(&lower::Parts {
|
||||
native: &native,
|
||||
p: &p,
|
||||
st: &st,
|
||||
io: &io,
|
||||
res: &res,
|
||||
inputs: Vec::new(),
|
||||
outputs: Vec::new(),
|
||||
prims: Vec::new(),
|
||||
mesh_stride: 0,
|
||||
});
|
||||
match r {
|
||||
Err(ShaderError::Unsupported { what, .. }) => {
|
||||
assert_eq!(what, "a ray-tracing structure that returns triangle ids");
|
||||
}
|
||||
other => panic!("{:?}", other.map(|_| ())),
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,914 @@
|
||||
//! Wave ORs that only steer a loop over each lane's own bits.
|
||||
//!
|
||||
//! The title's light loops are "scalarised": the lanes' light masks are ORed over the wave and
|
||||
//! the wave walks the set bits of the result together, each lane working only where its own
|
||||
//! mask has the bit:
|
||||
//!
|
||||
//! ```text
|
||||
//! merged = WaveActiveBitOr(mask); // over the lanes that run
|
||||
//! while (merged != 0) {
|
||||
//! bit = firstbitlow(merged);
|
||||
//! if (mask & (1 << bit)) { ... } // the body
|
||||
//! merged ^= 1 << bit;
|
||||
//! }
|
||||
//! ```
|
||||
//!
|
||||
//! A console wave64 program in two host waves of 32 cannot exchange the halves' ORs where not
|
||||
//! every lane runs (a group barrier must be reached by every thread). It does not have to: as
|
||||
//! one thread runs it, the loop visits the bits of `merged` in rising order and does something
|
||||
//! only at the bits of the thread's own mask, so any `merged` that holds the thread's own bits
|
||||
//! gives that thread the same run. The host wave's own OR is such a value.
|
||||
//!
|
||||
//! That holds only if the OR is used for nothing else, and if a round of the loop at a bit the
|
||||
//! thread does not have leaves nothing behind. [`find`] proves both for each wave OR, with no
|
||||
//! instruction sequence taken on trust:
|
||||
//!
|
||||
//! - the OR and what derives from it as "the bits still to visit" (copies, the loop's join, the
|
||||
//! first-lane read of it, the set less the visited bit) are read only by the loop's own
|
||||
//! steps: the test for an empty set, the lowest set bit, the removal of that bit, the test
|
||||
//! that ends the loop;
|
||||
//! - the lane's test is its own bit of the very value that was ORed, and "the body" is what a
|
||||
//! lane only reaches with that test true in the same round;
|
||||
//! - outside the body the loop has no side effect and no cross-lane step, writes nothing that
|
||||
//! is read after the loop or carried into a later round, and is left only by the test for
|
||||
//! "no bits left";
|
||||
//! - no lane mask that depends on the test is used outside the round that made it.
|
||||
//!
|
||||
//! Anything else is refused there as before ("a wave reduction where not every lane runs") and
|
||||
//! left to the forms of the program in which every lane runs that code (`emit`'s retries: the
|
||||
//! skips left out, the branches around it taken wave-wide), where the halves do exchange.
|
||||
//! `VICTORY_WAVE_OWN_BITS=0` turns this off.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use super::wave::{self, Op, Shape};
|
||||
use crate::gfx10::{Fields, NULL, Operand};
|
||||
use crate::ir::{EXEC, Exit, Inst, Program, Reg, Value};
|
||||
use crate::structure::{Atom, Bool, LaneExit, Structured};
|
||||
|
||||
type Why = &'static str;
|
||||
|
||||
const USED: Why = "a wave OR used as data";
|
||||
const NO_LOOP: Why = "a wave OR that steers no loop over its bits";
|
||||
const SHAPE: Why = "a loop over a wave OR's bits of another shape";
|
||||
const TEST: Why = "a loop over a wave OR's bits whose lanes do not test their own bit";
|
||||
const LEAVES: Why = "a value of a round over a wave OR's bits that outlives the round";
|
||||
const EFFECT: Why = "an effect in a loop over a wave OR's bits outside the lanes' own bits";
|
||||
const CROSS: Why = "a cross-lane step in a loop over a wave OR's bits outside the lanes' own bits";
|
||||
const EXIT: Why = "a loop over a wave OR's bits left another way";
|
||||
const STALE: Why = "a lane's own-bit test used outside its round";
|
||||
const MASK: Why = "a wave OR over a mask a running lane may be outside";
|
||||
|
||||
/// What [`find`] proved.
|
||||
#[derive(Debug, Default)]
|
||||
pub(super) struct OwnBits {
|
||||
/// Wave ORs (the values their sections leave) a host wave may take over its own lanes.
|
||||
pub totals: HashSet<Value>,
|
||||
/// VGPR values of those loops that every lane of a host wave holds alike (the bits still
|
||||
/// to visit): a first-lane read of one is the lane's own value.
|
||||
pub alike: HashSet<Value>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum User {
|
||||
Inst(usize, usize),
|
||||
Phi(usize, usize),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum Arg {
|
||||
Val(Value),
|
||||
K(u32),
|
||||
Other,
|
||||
}
|
||||
|
||||
struct Ctx<'a> {
|
||||
p: &'a Program,
|
||||
st: &'a Structured,
|
||||
users: HashMap<Value, Vec<User>>,
|
||||
/// The instruction writing each value.
|
||||
def: HashMap<Value, (usize, usize)>,
|
||||
/// Values an instruction reads, directly or through joins.
|
||||
live: HashSet<Value>,
|
||||
idom: Vec<usize>,
|
||||
sections: Vec<HashMap<usize, wave::Section>>,
|
||||
}
|
||||
|
||||
/// The values instruction `i` of block `b` uses: what its operands read, without EXEC (lane
|
||||
/// masks are followed as booleans) and without the old value of a VGPR it writes, which only
|
||||
/// lanes outside a guard keep.
|
||||
fn used(p: &Program, st: &Structured, b: usize, i: usize) -> Vec<Value> {
|
||||
let inst = &p.blocks[b].insts[i];
|
||||
let ops = crate::ir::operand_reads(p, inst);
|
||||
let guarded = st.guards[b][i].is_some();
|
||||
inst.reads
|
||||
.iter()
|
||||
.filter(|&&(r, _)| match r {
|
||||
Reg::S(c) if c == EXEC || c == EXEC + 1 => false,
|
||||
Reg::V(_) => ops.contains(&r) || guarded,
|
||||
_ => true,
|
||||
})
|
||||
.map(|r| r.1)
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn value(inst: &Inst, op: &Operand) -> Option<Value> {
|
||||
match *op {
|
||||
Operand::Scalar { code, .. } if code != NULL => inst.read(Reg::S(code)),
|
||||
Operand::Vector { reg, .. } => inst.read(Reg::V(reg)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The sources of a scalar or unmodified vector operation.
|
||||
fn args(inst: &Inst) -> Vec<Arg> {
|
||||
let src: &[Operand] = match &inst.fields {
|
||||
Fields::Sop { src, .. } => src,
|
||||
Fields::Valu(v)
|
||||
if v.dpp.is_none()
|
||||
&& v.sdwa.is_none()
|
||||
&& v.abs == 0
|
||||
&& v.neg == 0
|
||||
&& !v.clamp
|
||||
&& v.omod == 0 =>
|
||||
{
|
||||
&v.src
|
||||
}
|
||||
_ => &[],
|
||||
};
|
||||
src.iter()
|
||||
.map(|o| match (value(inst, o), o) {
|
||||
(Some(v), _) => Arg::Val(v),
|
||||
(None, &Operand::Const(c)) => crate::resource::inline(c).map_or(Arg::Other, Arg::K),
|
||||
(None, &Operand::Literal(x)) => Arg::K(x),
|
||||
_ => Arg::Other,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The other source of a two-source operation that reads `a`.
|
||||
fn other(inst: &Inst, a: Value) -> Option<Arg> {
|
||||
match args(inst)[..] {
|
||||
[Arg::Val(x), o] if x == a => Some(o),
|
||||
[o, Arg::Val(x)] if x == a => Some(o),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The scalar (not SCC) or vector dword an instruction writes, if it writes one.
|
||||
fn result(inst: &Inst) -> Option<Value> {
|
||||
let mut w = inst.writes.iter().filter(|w| w.0 != Reg::Scc);
|
||||
match (w.next(), w.next()) {
|
||||
(Some(&(_, v)), None) => Some(v),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The same test as `wave_local`'s and `Lower::inst`'s `effect`, and the messages a program
|
||||
/// sends.
|
||||
fn effect(inst: &Inst) -> bool {
|
||||
let name = inst.name();
|
||||
matches!(inst.fields, Fields::Exp { .. })
|
||||
|| matches!(inst.fields, Fields::Flat { .. }) && !name.starts_with("global_load_")
|
||||
|| name.contains("store")
|
||||
|| name.contains("atomic")
|
||||
|| matches!(inst.fields, Fields::Ds { .. })
|
||||
&& !(name.starts_with("ds_read") || name.starts_with("ds_swizzle") || name.contains("permute"))
|
||||
|| matches!(name, "s_barrier" | "s_sendmsg" | "s_sendmsghalt")
|
||||
}
|
||||
|
||||
impl Ctx<'_> {
|
||||
fn new<'a>(p: &'a Program, st: &'a Structured) -> Ctx<'a> {
|
||||
let mut users: HashMap<Value, Vec<User>> = HashMap::new();
|
||||
let mut def = HashMap::new();
|
||||
let mut live: HashSet<Value> = HashSet::new();
|
||||
for (b, block) in p.blocks.iter().enumerate() {
|
||||
for (k, phi) in block.phis.iter().enumerate() {
|
||||
for &a in &phi.args {
|
||||
users.entry(a).or_default().push(User::Phi(b, k));
|
||||
}
|
||||
}
|
||||
for (i, inst) in block.insts.iter().enumerate() {
|
||||
for v in used(p, st, b, i) {
|
||||
users.entry(v).or_default().push(User::Inst(b, i));
|
||||
live.insert(v);
|
||||
}
|
||||
for &(_, w) in &inst.writes {
|
||||
def.insert(w, (b, i));
|
||||
}
|
||||
}
|
||||
}
|
||||
// through joins
|
||||
let mut changed = true;
|
||||
while changed {
|
||||
changed = false;
|
||||
for block in &p.blocks {
|
||||
for phi in &block.phis {
|
||||
if live.contains(&phi.value) {
|
||||
for &a in &phi.args {
|
||||
changed |= live.insert(a);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let order = crate::ir::reverse_postorder(&p.blocks);
|
||||
let mut index = vec![usize::MAX; p.blocks.len()];
|
||||
for (n, &b) in order.iter().enumerate() {
|
||||
index[b] = n;
|
||||
}
|
||||
let idom = crate::ir::idoms(&p.blocks, &order, &index);
|
||||
let sections = (0..p.blocks.len()).map(|b| wave::sections(p, b)).collect();
|
||||
Ctx {
|
||||
p,
|
||||
st,
|
||||
users,
|
||||
def,
|
||||
live,
|
||||
idom,
|
||||
sections,
|
||||
}
|
||||
}
|
||||
|
||||
fn inst(&self, u: (usize, usize)) -> &Inst {
|
||||
&self.p.blocks[u.0].insts[u.1]
|
||||
}
|
||||
|
||||
fn at(&self, u: (usize, usize)) -> usize {
|
||||
self.inst(u).machine.offset
|
||||
}
|
||||
|
||||
/// Whether block `a` dominates block `b`.
|
||||
fn dominates(&self, a: usize, mut b: usize) -> bool {
|
||||
loop {
|
||||
if a == b {
|
||||
return true;
|
||||
}
|
||||
let d = self.idom.get(b).copied().unwrap_or(usize::MAX);
|
||||
if d == b || d == usize::MAX {
|
||||
return false;
|
||||
}
|
||||
b = d;
|
||||
}
|
||||
}
|
||||
|
||||
fn readers(&self, v: Value) -> Vec<(usize, usize)> {
|
||||
let mut out: Vec<(usize, usize)> = self
|
||||
.users
|
||||
.get(&v)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|u| match *u {
|
||||
User::Inst(b, i) => Some((b, i)),
|
||||
User::Phi(..) => None,
|
||||
})
|
||||
.collect();
|
||||
out.sort_unstable();
|
||||
out.dedup();
|
||||
out
|
||||
}
|
||||
|
||||
/// The joins reading `v` whose value something reads.
|
||||
fn joins(&self, v: Value) -> Vec<(usize, usize)> {
|
||||
let mut out: Vec<(usize, usize)> = self
|
||||
.users
|
||||
.get(&v)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|u| match *u {
|
||||
User::Phi(b, k) if self.live.contains(&self.p.blocks[b].phis[k].value) => Some((b, k)),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
out.sort_unstable();
|
||||
out.dedup();
|
||||
out
|
||||
}
|
||||
|
||||
/// The loop of header `h`: the blocks that reach one of its back edges without passing it.
|
||||
fn natural_loop(&self, h: usize) -> Vec<bool> {
|
||||
let mut inside = vec![false; self.p.blocks.len()];
|
||||
let mut work: Vec<usize> = self.p.blocks[h]
|
||||
.preds
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|&q| self.dominates(h, q))
|
||||
.collect();
|
||||
if work.is_empty() {
|
||||
return inside;
|
||||
}
|
||||
inside[h] = true;
|
||||
while let Some(b) = work.pop() {
|
||||
if inside[b] {
|
||||
continue;
|
||||
}
|
||||
inside[b] = true;
|
||||
work.extend(self.p.blocks[b].preds.iter().copied());
|
||||
}
|
||||
inside
|
||||
}
|
||||
|
||||
/// Whether `b` holds only in lanes where `a` does.
|
||||
fn implied(&self, b: Bool, a: Atom, memo: &mut HashMap<Bool, bool>) -> bool {
|
||||
if b == Bool::FALSE {
|
||||
return true;
|
||||
}
|
||||
if let Some(&r) = memo.get(&b) {
|
||||
return r;
|
||||
}
|
||||
let r = match self.st.bools.node(b) {
|
||||
None => false,
|
||||
Some((x, lo, _)) if x == a => lo == Bool::FALSE,
|
||||
Some((_, lo, hi)) => self.implied(lo, a, memo) && self.implied(hi, a, memo),
|
||||
};
|
||||
memo.insert(b, r);
|
||||
r
|
||||
}
|
||||
|
||||
/// The conditional branch reading `scc`, as (its place, the block it goes to when SCC is
|
||||
/// set, the other one).
|
||||
fn branch(&self, scc: Value) -> Option<((usize, usize), usize, usize)> {
|
||||
let [u] = self.readers(scc)[..] else {
|
||||
return None;
|
||||
};
|
||||
let Exit::Branch { taken, not_taken } = self.p.blocks[u.0].exit else {
|
||||
return None;
|
||||
};
|
||||
if u.1 + 1 != self.p.blocks[u.0].insts.len() {
|
||||
return None;
|
||||
}
|
||||
match self.inst(u).name() {
|
||||
"s_cbranch_scc1" => Some((u, taken, not_taken)),
|
||||
"s_cbranch_scc0" => Some((u, not_taken, taken)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// One wave OR `t` of `x` over the lanes of `mask`, left by a section of block `sb`: the
|
||||
/// VGPR values its loop keeps alike, or where and why it is not such a loop.
|
||||
fn site(&self, sb: usize, t: Value, x: Value, mask: Value) -> Result<Vec<Value>, (usize, Why)> {
|
||||
let p = self.p;
|
||||
let st = self.st;
|
||||
let n = p.blocks.len();
|
||||
let here = p.blocks[sb].offset;
|
||||
let is_mask = |v: Value| st.masks.contains_key(&v) || st.highs.contains_key(&v);
|
||||
// every lane that runs the section is one of the lanes ORed
|
||||
let &mb = st.masks.get(&mask).ok_or((here, MASK))?;
|
||||
if st.bools.meet(&[(st.reach[sb], true), (mb, false)]) {
|
||||
return Err((here, MASK));
|
||||
}
|
||||
// ---- the bits still to visit, and the loop's own steps ----
|
||||
let mut rem: HashSet<Value> = HashSet::from([t]);
|
||||
let mut pattern: HashSet<(usize, usize)> = HashSet::new();
|
||||
let mut alike: Vec<Value> = Vec::new();
|
||||
// an unguarded copy
|
||||
let copy = |u: (usize, usize)| -> Option<Value> {
|
||||
let i = self.inst(u);
|
||||
(matches!(i.name(), "v_mov_b32" | "s_mov_b32") && args(i).len() == 1 && st.guards[u.0][u.1].is_none())
|
||||
.then(|| result(i))
|
||||
.flatten()
|
||||
};
|
||||
let mut init = vec![t];
|
||||
// (SCC, whether it is set when the OR is empty)
|
||||
let mut zero: Option<(Value, bool)> = None;
|
||||
for u in self.readers(t) {
|
||||
let i = self.inst(u);
|
||||
let name = i.name();
|
||||
if matches!(name, "s_cmp_eq_u32" | "s_cmp_lg_u32" | "s_cmp_eq_i32" | "s_cmp_lg_i32")
|
||||
&& other(i, t) == Some(Arg::K(0))
|
||||
&& zero.is_none()
|
||||
&& let Some(scc) = i.write(Reg::Scc)
|
||||
{
|
||||
zero = Some((scc, name.contains("_eq_")));
|
||||
rem.insert(scc);
|
||||
} else if let Some(w) = copy(u) {
|
||||
init.push(w);
|
||||
rem.insert(w);
|
||||
if matches!(i.writes[0].0, Reg::V(_)) {
|
||||
alike.push(w);
|
||||
}
|
||||
} else {
|
||||
return Err((self.at(u), USED));
|
||||
}
|
||||
pattern.insert(u);
|
||||
}
|
||||
// the loop's join of them
|
||||
let mut join: Option<(usize, usize)> = None;
|
||||
for &v in &init {
|
||||
if v != t
|
||||
&& let Some(&u) = self.readers(v).first()
|
||||
{
|
||||
return Err((self.at(u), USED));
|
||||
}
|
||||
for j in self.joins(v) {
|
||||
if join.is_some_and(|q| q != j) {
|
||||
return Err((p.blocks[j.0].offset, USED));
|
||||
}
|
||||
join = Some(j);
|
||||
}
|
||||
}
|
||||
let (h, k) = join.ok_or((here, NO_LOOP))?;
|
||||
let phi = &p.blocks[h].phis[k];
|
||||
let r = phi.value;
|
||||
rem.insert(r);
|
||||
let head = p.blocks[h].offset;
|
||||
let lp = self.natural_loop(h);
|
||||
if !lp[h] || lp[sb] {
|
||||
return Err((head, NO_LOOP));
|
||||
}
|
||||
// the set as a scalar: the first lane's copy of it
|
||||
let cur = if matches!(phi.reg, Reg::V(_)) {
|
||||
alike.push(r);
|
||||
let [u] = self.readers(r)[..] else {
|
||||
return Err((head, USED));
|
||||
};
|
||||
let i = self.inst(u);
|
||||
if i.name() != "v_readfirstlane_b32" || args(i).len() != 1 || !lp[u.0] {
|
||||
return Err((self.at(u), USED));
|
||||
}
|
||||
pattern.insert(u);
|
||||
let c = result(i).ok_or((self.at(u), SHAPE))?;
|
||||
if !self.joins(r).is_empty() {
|
||||
return Err((head, USED));
|
||||
}
|
||||
c
|
||||
} else {
|
||||
r
|
||||
};
|
||||
rem.insert(cur);
|
||||
// its lowest bit, the set without it, the tests for "that was the last"
|
||||
let mut idx: Option<Value> = None;
|
||||
let mut next: Option<(Value, Value)> = None;
|
||||
// (SCC, whether it is set while bits remain)
|
||||
let mut more: Vec<(Value, bool)> = Vec::new();
|
||||
let mut bits: Vec<Value> = Vec::new();
|
||||
for u in self.readers(cur) {
|
||||
let i = self.inst(u);
|
||||
let name = i.name();
|
||||
if !lp[u.0] {
|
||||
return Err((self.at(u), USED));
|
||||
}
|
||||
match (name, &args(i)[..]) {
|
||||
("s_ff1_i32_b32", [Arg::Val(_)]) if idx.is_none() => idx = result(i),
|
||||
("s_xor_b32", _) | ("s_andn2_b32", [Arg::Val(_), Arg::Val(_)]) if next.is_none() => {
|
||||
let bit = match (name, &args(i)[..]) {
|
||||
("s_andn2_b32", [Arg::Val(c), Arg::Val(b)]) if *c == cur && *b != cur => *b,
|
||||
("s_xor_b32", _) => match other(i, cur) {
|
||||
Some(Arg::Val(b)) if b != cur => b,
|
||||
_ => return Err((self.at(u), USED)),
|
||||
},
|
||||
_ => return Err((self.at(u), USED)),
|
||||
};
|
||||
let w = result(i).ok_or((self.at(u), SHAPE))?;
|
||||
next = Some((w, bit));
|
||||
bits.push(bit);
|
||||
if let Some(scc) = i.write(Reg::Scc) {
|
||||
more.push((scc, true));
|
||||
rem.insert(scc);
|
||||
}
|
||||
}
|
||||
("s_cmp_eq_u32" | "s_cmp_lg_u32" | "s_cmp_eq_i32" | "s_cmp_lg_i32", _) => {
|
||||
let (Some(Arg::Val(b)), Some(scc)) = (other(i, cur), i.write(Reg::Scc)) else {
|
||||
return Err((self.at(u), USED));
|
||||
};
|
||||
bits.push(b);
|
||||
more.push((scc, name.contains("_lg_")));
|
||||
rem.insert(scc);
|
||||
}
|
||||
_ => return Err((self.at(u), USED)),
|
||||
}
|
||||
pattern.insert(u);
|
||||
}
|
||||
if cur != r && !self.joins(cur).is_empty() {
|
||||
return Err((head, USED));
|
||||
}
|
||||
let (Some(idx), Some((nx, bit))) = (idx, next) else {
|
||||
return Err((head, SHAPE));
|
||||
};
|
||||
if bits.iter().any(|&b| b != bit) {
|
||||
return Err((head, SHAPE));
|
||||
}
|
||||
// the bit: 1 shifted by the lowest set bit's number (a shift takes five bits of it)
|
||||
let made = |v: Value| self.def.get(&v).map(|&u| (u, self.inst(u)));
|
||||
let shifted = match made(bit) {
|
||||
Some((u, i)) if i.name() == "s_lshl_b32" && lp[u.0] => match args(i)[..] {
|
||||
[Arg::K(1), Arg::Val(sh)] => Some(sh),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
};
|
||||
let by_idx = shifted.is_some_and(|sh| {
|
||||
sh == idx
|
||||
|| made(sh).is_some_and(|(_, i)| i.name() == "s_and_b32" && other(i, idx) == Some(Arg::K(31)))
|
||||
});
|
||||
if !by_idx {
|
||||
return Err((head, SHAPE));
|
||||
}
|
||||
// the set less the bit: back into the join, or tested for empty
|
||||
rem.insert(nx);
|
||||
let mut nexts = vec![nx];
|
||||
for u in self.readers(nx) {
|
||||
let i = self.inst(u);
|
||||
let name = i.name();
|
||||
if matches!(name, "s_cmp_eq_u32" | "s_cmp_lg_u32" | "s_cmp_eq_i32" | "s_cmp_lg_i32")
|
||||
&& other(i, nx) == Some(Arg::K(0))
|
||||
&& let Some(scc) = i.write(Reg::Scc)
|
||||
{
|
||||
more.push((scc, name.contains("_lg_")));
|
||||
rem.insert(scc);
|
||||
} else if let Some(w) = copy(u) {
|
||||
nexts.push(w);
|
||||
rem.insert(w);
|
||||
if matches!(i.writes[0].0, Reg::V(_)) {
|
||||
alike.push(w);
|
||||
}
|
||||
} else {
|
||||
return Err((self.at(u), USED));
|
||||
}
|
||||
pattern.insert(u);
|
||||
}
|
||||
for &v in &nexts {
|
||||
if v != nx
|
||||
&& let Some(&u) = self.readers(v).first()
|
||||
{
|
||||
return Err((self.at(u), USED));
|
||||
}
|
||||
if self.joins(v).iter().any(|&j| j != (h, k)) {
|
||||
return Err((head, USED));
|
||||
}
|
||||
}
|
||||
for (q, a) in p.blocks[h].preds.iter().zip(&phi.args) {
|
||||
let ok = if lp[*q] { nexts.contains(a) } else { init.contains(a) };
|
||||
if !ok {
|
||||
return Err((head, SHAPE));
|
||||
}
|
||||
}
|
||||
// the loop goes on while bits remain and is left when none does
|
||||
let mut leaves: HashSet<usize> = HashSet::new();
|
||||
for &(scc, set_while_more) in &more {
|
||||
if !self.joins(scc).is_empty() {
|
||||
return Err((head, USED));
|
||||
}
|
||||
if self.readers(scc).is_empty() {
|
||||
continue;
|
||||
}
|
||||
let (u, set, clear) = self.branch(scc).ok_or((head, USED))?;
|
||||
let (on, out) = if set_while_more { (set, clear) } else { (clear, set) };
|
||||
if !lp[u.0] || !lp[on] || lp[out] {
|
||||
return Err((self.at(u), SHAPE));
|
||||
}
|
||||
leaves.insert(u.0);
|
||||
pattern.insert(u);
|
||||
}
|
||||
if leaves.is_empty() {
|
||||
return Err((head, SHAPE));
|
||||
}
|
||||
// "no bit at all" skips the loop; what lies between that test and the loop runs only
|
||||
// when there is one
|
||||
let mut pre = vec![false; n];
|
||||
if let Some((scc, set_when_empty)) = zero {
|
||||
if !self.joins(scc).is_empty() {
|
||||
return Err((here, USED));
|
||||
}
|
||||
if !self.readers(scc).is_empty() {
|
||||
let (u, set, clear) = self.branch(scc).ok_or((here, USED))?;
|
||||
let (none, some) = if set_when_empty { (set, clear) } else { (clear, set) };
|
||||
if none == some || lp[u.0] {
|
||||
return Err((self.at(u), SHAPE));
|
||||
}
|
||||
if some != h {
|
||||
if p.blocks[some].preds[..] != [u.0] || !self.dominates(some, h) {
|
||||
return Err((self.at(u), SHAPE));
|
||||
}
|
||||
for b in 0..n {
|
||||
pre[b] = self.dominates(some, b) && !self.dominates(h, b);
|
||||
}
|
||||
for b in (0..n).filter(|&b| pre[b]) {
|
||||
let inside = match p.blocks[b].exit {
|
||||
Exit::End | Exit::Indirect => false,
|
||||
ref e => e.successors().iter().all(|&s| pre[s] || s == h),
|
||||
};
|
||||
if !inside {
|
||||
return Err((p.blocks[b].offset, SHAPE));
|
||||
}
|
||||
}
|
||||
}
|
||||
pattern.insert(u);
|
||||
}
|
||||
}
|
||||
// ---- the lane's test of its own bit ----
|
||||
// (the atom of the compare, its block, its index)
|
||||
let mut tests: Vec<(Atom, usize, usize)> = Vec::new();
|
||||
for u in self.readers(bit) {
|
||||
let i = self.inst(u);
|
||||
if i.name() != "v_and_b32" || other(i, bit) != Some(Arg::Val(x)) || st.guards[u.0][u.1].is_some() {
|
||||
continue;
|
||||
}
|
||||
let Some(y) = result(i) else { continue };
|
||||
for c in self.readers(y) {
|
||||
let ci = self.inst(c);
|
||||
if matches!(
|
||||
ci.name(),
|
||||
"v_cmp_ne_u32" | "v_cmpx_ne_u32" | "v_cmp_lg_u32" | "v_cmpx_lg_u32" | "v_cmp_ne_i32" | "v_cmpx_ne_i32"
|
||||
| "v_cmp_lg_i32" | "v_cmpx_lg_i32"
|
||||
) && other(ci, y) == Some(Arg::K(0))
|
||||
&& lp[c.0]
|
||||
{
|
||||
tests.extend(ci.writes.iter().map(|w| (Atom::Lane(w.1), c.0, c.1)));
|
||||
}
|
||||
}
|
||||
}
|
||||
if tests.is_empty() {
|
||||
return Err((head, TEST));
|
||||
}
|
||||
let mut memo: Vec<HashMap<Bool, bool>> = vec![HashMap::new(); tests.len()];
|
||||
// what a lane only reaches with its own bit set, in the round of that test
|
||||
let mut body_block = vec![false; n];
|
||||
for b in (0..n).filter(|&b| lp[b]) {
|
||||
body_block[b] = tests.iter().enumerate().any(|(j, &(a, tb, _))| {
|
||||
b != tb && self.dominates(tb, b) && self.implied(st.reach[b], a, &mut memo[j])
|
||||
});
|
||||
}
|
||||
let body_inst = |b: usize, i: usize, memo: &mut Vec<HashMap<Bool, bool>>| {
|
||||
body_block[b]
|
||||
|| lp[b]
|
||||
&& st.guards[b][i].is_some_and(|g| {
|
||||
tests.iter().enumerate().any(|(j, &(a, tb, ti))| {
|
||||
(b == tb && i > ti || b != tb && self.dominates(tb, b)) && self.implied(g, a, &mut memo[j])
|
||||
})
|
||||
})
|
||||
};
|
||||
// ---- a round outside the body leaves nothing behind ----
|
||||
for b in (0..n).filter(|&b| lp[b] || pre[b]) {
|
||||
for (i, inst) in p.blocks[b].insts.iter().enumerate() {
|
||||
if lp[b] && body_inst(b, i, &mut memo) {
|
||||
continue;
|
||||
}
|
||||
let u = (b, i);
|
||||
for &(reg, w) in &inst.writes {
|
||||
if rem.contains(&w) || is_mask(w) || matches!(reg, Reg::S(c) if c == EXEC || c == EXEC + 1) {
|
||||
continue;
|
||||
}
|
||||
for user in self.users.get(&w).into_iter().flatten() {
|
||||
let stays = match *user {
|
||||
User::Inst(b2, _) => lp[b2] || pre[b2],
|
||||
User::Phi(b2, k2) => {
|
||||
body_block[b2] || !self.live.contains(&p.blocks[b2].phis[k2].value)
|
||||
}
|
||||
};
|
||||
if !stays {
|
||||
return Err((self.at(u), LEAVES));
|
||||
}
|
||||
}
|
||||
}
|
||||
if pattern.contains(&u) {
|
||||
continue;
|
||||
}
|
||||
if effect(inst) {
|
||||
return Err((self.at(u), EFFECT));
|
||||
}
|
||||
let name = inst.name();
|
||||
let cross = name.starts_with("ds_swizzle")
|
||||
|| name.contains("permute")
|
||||
|| name.starts_with("v_mbcnt")
|
||||
|| name.contains("lane")
|
||||
|| matches!(&inst.fields, Fields::Valu(v) if v.dpp.is_some())
|
||||
|| super::lower::reads_mask_as_data(st, inst)
|
||||
|| self.sections[b].iter().any(|(&s, sec)| i >= s && i <= sec.end);
|
||||
if cross {
|
||||
return Err((self.at(u), CROSS));
|
||||
}
|
||||
if used(p, st, b, i).iter().any(|v| rem.contains(v)) {
|
||||
return Err((self.at(u), USED));
|
||||
}
|
||||
}
|
||||
// left only by "no bits left"; the body may leave it as it likes
|
||||
if lp[b] && !body_block[b] {
|
||||
let ok = match p.blocks[b].exit {
|
||||
Exit::End | Exit::Indirect => false,
|
||||
ref e => leaves.contains(&b) || e.successors().iter().all(|&s| lp[s]),
|
||||
};
|
||||
if !ok {
|
||||
return Err((p.blocks[b].offset, EXIT));
|
||||
}
|
||||
}
|
||||
}
|
||||
// ---- no mask that depends on the test outlives its round ----
|
||||
let mut dep: HashSet<Atom> = tests.iter().map(|t| t.0).collect();
|
||||
let mut changed = true;
|
||||
while changed {
|
||||
changed = false;
|
||||
for (&id, edges) in &st.phi_masks {
|
||||
if !dep.contains(&Atom::Phi(id))
|
||||
&& edges.iter().any(|&e| st.bools.support(e).iter().any(|a| dep.contains(a)))
|
||||
{
|
||||
dep.insert(Atom::Phi(id));
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut seen: HashMap<Bool, bool> = HashMap::new();
|
||||
let mut tainted = |b: Bool| -> bool {
|
||||
*seen
|
||||
.entry(b)
|
||||
.or_insert_with(|| st.bools.support(b).iter().any(|a| dep.contains(a)))
|
||||
};
|
||||
for b in 0..n {
|
||||
if lp[b] && tests.iter().any(|&(_, tb, _)| self.dominates(tb, b)) {
|
||||
continue;
|
||||
}
|
||||
let stale = st.guards[b].iter().flatten().any(|&g| tainted(g))
|
||||
|| matches!(st.exits[b], LaneExit::Branch { when, .. } if tainted(when));
|
||||
if stale {
|
||||
return Err((p.blocks[b].offset, STALE));
|
||||
}
|
||||
}
|
||||
for (&v, &m) in &st.masks {
|
||||
if !tainted(m) {
|
||||
continue;
|
||||
}
|
||||
for user in self.users.get(&v).into_iter().flatten() {
|
||||
let outside = match *user {
|
||||
User::Inst(b2, _) => !lp[b2],
|
||||
User::Phi(b2, k2) => !lp[b2] && self.live.contains(&p.blocks[b2].phis[k2].value),
|
||||
};
|
||||
if outside {
|
||||
return Err((head, STALE));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(alike)
|
||||
}
|
||||
}
|
||||
|
||||
/// The wave ORs of `p` that only steer a loop over each lane's own bits (see the module
|
||||
/// notes). `why`: one line on stderr for each wave OR that is not one.
|
||||
pub(super) fn find(p: &Program, st: &Structured, why: bool) -> OwnBits {
|
||||
let mut out = OwnBits::default();
|
||||
let mut ctx: Option<Ctx> = None;
|
||||
for b in 0..p.blocks.len() {
|
||||
let sections = wave::sections(p, b);
|
||||
let mut starts: Vec<_> = sections.keys().copied().collect();
|
||||
starts.sort_unstable();
|
||||
for s in starts {
|
||||
let sec = §ions[&s];
|
||||
let mut left: Vec<_> = sec.shapes.iter().collect();
|
||||
left.sort_unstable_by_key(|(v, _)| v.0);
|
||||
for (&t, &shape) in left {
|
||||
let Shape::Active(Op::Or, x, mask, 0) = shape else {
|
||||
continue;
|
||||
};
|
||||
let ctx = ctx.get_or_insert_with(|| Ctx::new(p, st));
|
||||
// (values only the section itself reads are not results)
|
||||
let inside = |u: &User| matches!(*u, User::Inst(b2, i) if b2 == b && i > s && i < sec.end);
|
||||
if ctx.users.get(&t).is_none_or(|us| us.iter().all(inside)) {
|
||||
continue;
|
||||
}
|
||||
match ctx.site(b, t, x, mask) {
|
||||
Ok(alike) => {
|
||||
out.totals.insert(t);
|
||||
out.alike.extend(alike);
|
||||
}
|
||||
Err((offset, what)) => {
|
||||
if why {
|
||||
eprintln!(
|
||||
"WAVE64-OWN-BITS the wave OR at {:#x}: not a loop over the lanes' own bits at {offset:#x}: {what}",
|
||||
p.blocks[b].insts[s].machine.offset
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::emit::wave::WAVE_OR_V7_TO_S7;
|
||||
|
||||
const ADD_BIT_NUMBER: u32 = 0x4A0A_0A0A; // v_add_nc_u32 v5, s10, v5
|
||||
|
||||
/// The title's scalarised light loop (`indirect_light_probes:CS_IrradianceCache_Shade`,
|
||||
/// 0x71f8 on), in small: the wave OR of v7 in s7, a loop over its bits with the lowest
|
||||
/// one's number in s10 and the bit in s11, and `body` for the lanes whose v7 has the bit
|
||||
/// (`own`) or for every lane; `latch` runs in every lane after the body, `after` after
|
||||
/// the loop.
|
||||
fn light_loop(own: bool, body: &[u32], latch: &[u32], after: &[u32]) -> Program {
|
||||
let mut w = WAVE_OR_V7_TO_S7.to_vec();
|
||||
let test: &[u32] = if own {
|
||||
&[
|
||||
0x3608_0E0B, // v_and_b32 v4, s11, v7
|
||||
0xBE8C_047E, // s_mov_b64 s[12:13], exec
|
||||
0x7DAA_0880, // v_cmpx_ne_u32 exec, 0, v4
|
||||
]
|
||||
} else {
|
||||
&[0xBE8C_047E] // s_mov_b64 s[12:13], exec
|
||||
};
|
||||
// from the loop's head to its last branch
|
||||
let head = 3 + test.len() + usize::from(own) + body.len() + 1 + latch.len() + 3;
|
||||
w.extend_from_slice(&[
|
||||
0xBF06_8007, // s_cmp_eq_u32 s7, 0
|
||||
0xBF85_0000 | (3 + head) as u32, // s_cbranch_scc1 past the loop
|
||||
0x7E06_0207, // v_mov_b32 v3, s7
|
||||
0xBF82_0001, // s_branch to the loop's head
|
||||
0x7E06_0209, // again: v_mov_b32 v3, s9
|
||||
0x7E10_0503, // head: v_readfirstlane_b32 s8, v3
|
||||
0xBE8A_1308, // s_ff1_i32_b32 s10, s8
|
||||
0x8F0B_0A81, // s_lshl_b32 s11, 1, s10
|
||||
]);
|
||||
w.extend_from_slice(test);
|
||||
if own {
|
||||
w.push(0xBF88_0000 | body.len() as u32); // s_cbranch_execz past the body
|
||||
}
|
||||
w.extend_from_slice(body);
|
||||
w.push(0xBEFE_040C); // s_mov_b64 exec, s[12:13]
|
||||
w.extend_from_slice(latch);
|
||||
w.extend_from_slice(&[
|
||||
0x8909_080B, // s_xor_b32 s9, s11, s8
|
||||
0xBF06_0B08, // s_cmp_eq_u32 s8, s11
|
||||
0xBF84_0000 | (0x1_0000 - head - 1) as u32, // s_cbranch_scc0 again
|
||||
]);
|
||||
w.extend_from_slice(after);
|
||||
w.push(0xBF81_0000); // s_endpgm
|
||||
let code: Vec<u8> = w.iter().flat_map(|x| x.to_le_bytes()).collect();
|
||||
crate::ir::build(&code, true, 256).unwrap()
|
||||
}
|
||||
|
||||
fn found(p: &Program) -> OwnBits {
|
||||
let st = crate::structure::structure(p).unwrap();
|
||||
find(p, &st, false)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wave_or_that_only_steers_a_loop_over_own_bits_is_found() {
|
||||
let p = light_loop(true, &[ADD_BIT_NUMBER], &[], &[]);
|
||||
let insts = || p.blocks.iter().flat_map(|b| &b.insts);
|
||||
let names: Vec<&str> = insts().map(|i| i.name()).collect();
|
||||
for n in [
|
||||
"s_ff1_i32_b32",
|
||||
"s_lshl_b32",
|
||||
"v_and_b32",
|
||||
"v_cmpx_ne_u32",
|
||||
"s_xor_b32",
|
||||
"v_readfirstlane_b32",
|
||||
"s_cbranch_execz",
|
||||
] {
|
||||
assert!(names.contains(&n), "{n} in {names:?}");
|
||||
}
|
||||
// a loop: its last branch goes back to the copy of the bits still to visit
|
||||
assert!(p.blocks.iter().enumerate().any(|(b, blk)| blk.exit.successors().iter().any(|&s| s < b)));
|
||||
let own = found(&p);
|
||||
// the OR is the section's last lane read, and the bits still to visit (v3) are alike
|
||||
let total = insts()
|
||||
.rfind(|i| i.name() == "v_readlane_b32")
|
||||
.and_then(|i| i.write(Reg::S(7)))
|
||||
.unwrap();
|
||||
assert_eq!(own.totals, HashSet::from([total]));
|
||||
let first = insts().find(|i| i.name() == "v_readfirstlane_b32").unwrap();
|
||||
assert!(own.alike.contains(&first.read(Reg::V(3)).unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_loop_whose_lanes_all_work_at_every_bit_needs_the_whole_waves_or() {
|
||||
// (the same title's volume loops, 0xa668 on: no test of the lane's own mask)
|
||||
let p = light_loop(false, &[ADD_BIT_NUMBER], &[], &[]);
|
||||
assert!(found(&p).totals.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bit_number_read_after_the_loop_is_not_the_lanes_own() {
|
||||
// v_mov_b32 v6, s10: the last bit of the OR, which another lane may have set
|
||||
let p = light_loop(true, &[ADD_BIT_NUMBER], &[], &[0x7E0C_020A]);
|
||||
assert!(found(&p).totals.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_bits_still_to_visit_read_in_the_body_are_not_the_lanes_own() {
|
||||
// v_add_nc_u32 v5, s8, v5: s8 holds the other lanes' bits too
|
||||
let p = light_loop(true, &[0x4A0A_0A08], &[], &[]);
|
||||
assert!(found(&p).totals.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_count_of_the_rounds_is_not_the_lanes_own() {
|
||||
// s_add_i32 s14, s14, 1 where every lane passes, read after the loop
|
||||
// (v_mov_b32 v6, s14): one round for each bit any lane has
|
||||
let p = light_loop(true, &[ADD_BIT_NUMBER], &[0x810E_810E], &[0x7E0C_020E]);
|
||||
assert!(p.blocks.iter().flat_map(|b| &b.insts).any(|i| i.name() == "s_add_i32"));
|
||||
assert!(found(&p).totals.is_empty());
|
||||
// (reading s14 there without counting in it is nothing of the loop's)
|
||||
let p = light_loop(true, &[ADD_BIT_NUMBER], &[], &[0x7E0C_020E]);
|
||||
assert_eq!(found(&p).totals.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_effect_where_every_lane_passes_is_not_the_lanes_own() {
|
||||
// ds_write_b32 v5, v5 after the body: once for each bit any lane has
|
||||
let p = light_loop(true, &[ADD_BIT_NUMBER], &[0xD834_0000, 0x0000_0505], &[]);
|
||||
assert!(p.blocks.iter().flat_map(|b| &b.insts).any(|i| i.name() == "ds_write_b32"));
|
||||
assert!(found(&p).totals.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,484 @@
|
||||
//! The geometry shader that completes the console's rectangle lists (list
|
||||
//! topology 17, pipeline topology type 19). A rectangle comes as three
|
||||
//! vertices, three corners of a screen-aligned rectangle; the hardware
|
||||
//! draws the whole rectangle and continues every vertex shader output
|
||||
//! linearly into the fourth corner. The host has no such topology: the
|
||||
//! draw goes out as a triangle list with this shader behind the translated
|
||||
//! vertex shader, so vertex counts, vertex numbers, indices and indirect
|
||||
//! arguments stay the title's, and each rectangle arrives here as one
|
||||
//! triangle.
|
||||
//!
|
||||
//! Which vertex is the corner between the other two varies:
|
||||
//! the title's full-screen rectangles come as top left, bottom left, bottom
|
||||
//! right (the second), its tiled lighting as top left, bottom left, top
|
||||
//! right (the first). The corner is the vertex that shares x with one of
|
||||
//! the others and y with the other; the fourth vertex lies opposite it,
|
||||
//! `a + b - corner` for the position and every float output. That holds
|
||||
//! for three vertices with one positive w (then it is the same in clip
|
||||
//! space and on the screen, whatever the interpolation mode); three that
|
||||
//! differ in w, or are not such corners, stay the triangle they make.
|
||||
//!
|
||||
//! Flat values are the first vertex's: both triangles start with it (the
|
||||
//! halves on either side of the diagonal through it, turning as the three
|
||||
//! vertices do), which is the vertex the host takes a flat input from, and
|
||||
//! the fourth vertex's integer outputs are the first vertex's.
|
||||
//!
|
||||
//! shortcut: that the console takes a rectangle's flat values from its
|
||||
//! first vertex follows from the hardware's provoking-vertex setting for
|
||||
//! triangles; it is not measured on a rectangle.
|
||||
|
||||
use super::bitcode::{Attr, Bin, Term, V, pred};
|
||||
use super::container::SigElement;
|
||||
use super::shader::{Geometry, Shader};
|
||||
use crate::ShaderError;
|
||||
use crate::dxbc::{Container, FourCC};
|
||||
|
||||
/// Vertices emitted per rectangle: two triangles.
|
||||
const VERTICES: u32 = 6;
|
||||
|
||||
/// The scalars a geometry shader may emit per invocation (vertices times
|
||||
/// output components).
|
||||
const MAX_SCALARS: u32 = 1024;
|
||||
|
||||
/// The geometry shader (a DXIL container) for rectangle lists drawn with
|
||||
/// the translated vertex shader `vs` and, if the pipeline has one, the
|
||||
/// translated pixel shader `ps` (both as [`super::HostShader::dxil`]). Its
|
||||
/// inputs and outputs are the vertex shader's outputs, register for
|
||||
/// register, so it links with both. A pixel shader that declares a
|
||||
/// primitive id gets the rectangle's number, which the host leaves to the
|
||||
/// geometry stage when there is one.
|
||||
pub fn rect_list_gs(vs: &[u8], ps: Option<&[u8]>) -> Result<Vec<u8>, ShaderError> {
|
||||
let sig = |dxil: &[u8], fourcc| -> Result<Vec<SigElement>, ShaderError> {
|
||||
let c = Container::parse(dxil)?;
|
||||
match c.part(fourcc) {
|
||||
Some(part) => super::signature(part.data),
|
||||
None => Ok(Vec::new()),
|
||||
}
|
||||
};
|
||||
let outputs = sig(vs, FourCC::OSG1)?;
|
||||
let wanted = match ps {
|
||||
Some(ps) => sig(ps, FourCC::ISG1)?,
|
||||
None => Vec::new(),
|
||||
};
|
||||
build(outputs, &wanted)
|
||||
}
|
||||
|
||||
/// [`rect_list_gs`] from the vertex shader's outputs and the pixel
|
||||
/// shader's inputs.
|
||||
fn build(mut outputs: Vec<SigElement>, ps_inputs: &[SigElement]) -> Result<Vec<u8>, ShaderError> {
|
||||
let unsupported = |what| ShaderError::Unsupported { offset: 0, what };
|
||||
if outputs.iter().any(|e| e.row.is_none()) {
|
||||
return Err(unsupported("a rectangle list output without a register"));
|
||||
}
|
||||
let Some(position) = outputs
|
||||
.iter()
|
||||
.position(|e| e.kind == 3 && e.comp == 9 && e.cols == 4)
|
||||
else {
|
||||
return Err(unsupported("a rectangle list without a four-component position"));
|
||||
};
|
||||
for e in &mut outputs {
|
||||
// Interpolation as `emit_program` declares a vertex shader's
|
||||
// outputs; a geometry shader's inputs carry the same modes.
|
||||
e.interp = match (e.kind, e.comp) {
|
||||
(3, _) => 4,
|
||||
(0 | 6 | 7, 9) => 2,
|
||||
(0, _) => 1,
|
||||
_ => 0,
|
||||
};
|
||||
e.usage = (1 << e.cols) - 1;
|
||||
}
|
||||
let mut s = Shader::new(false);
|
||||
s.geometry = Some(Geometry {
|
||||
max_vertices: VERTICES,
|
||||
});
|
||||
s.inputs = outputs.clone();
|
||||
// The primitive id the pixel shader declares, as one more output.
|
||||
let wanted = ps_inputs
|
||||
.iter()
|
||||
.find(|e| e.kind == 10 && e.row.is_some())
|
||||
.filter(|_| !outputs.iter().any(|o| o.kind == 10));
|
||||
let primitive = match wanted {
|
||||
Some(e) => {
|
||||
// Alone in its columns, and in a row of constant elements.
|
||||
let clash = outputs.iter().any(|o| {
|
||||
let overlap = o.col < e.col + e.cols && e.col < o.col + o.cols;
|
||||
o.row == e.row && (o.interp != 1 || overlap)
|
||||
});
|
||||
if clash {
|
||||
return Err(unsupported(
|
||||
"a rectangle list whose primitive id shares a register with a vertex output",
|
||||
));
|
||||
}
|
||||
outputs.push(SigElement {
|
||||
interp: 1,
|
||||
usage: (1 << e.cols) - 1,
|
||||
..e.clone()
|
||||
});
|
||||
Some(outputs.len() - 1)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let scalars: u32 = outputs.iter().map(|e| u32::from(e.cols)).sum();
|
||||
if scalars * VERTICES > MAX_SCALARS {
|
||||
return Err(unsupported(
|
||||
"a rectangle list with more output components than a geometry shader emits",
|
||||
));
|
||||
}
|
||||
s.outputs = outputs;
|
||||
let b = s.entry;
|
||||
|
||||
// Every input of the three vertices: [element][column][vertex].
|
||||
let mut corners: Vec<Vec<[V; 3]>> = Vec::new();
|
||||
for id in 0..s.inputs.len() {
|
||||
let mut columns = Vec::new();
|
||||
for col in 0..s.inputs[id].cols {
|
||||
columns.push([0, 1, 2].map(|vertex| load(&mut s, id, col, vertex)));
|
||||
}
|
||||
corners.push(columns);
|
||||
}
|
||||
|
||||
// One positive w, and no two vertices in one place.
|
||||
let (x, y, w) = (
|
||||
corners[position][0],
|
||||
corners[position][1],
|
||||
corners[position][3],
|
||||
);
|
||||
let zero = s.m.f32(0);
|
||||
let mut plain = s.m.cmp(b, pred::OGT, w[0], zero);
|
||||
for &other in &w[1..] {
|
||||
let one_w = same(&mut s, other, w[0]);
|
||||
plain = both(&mut s, plain, one_w);
|
||||
}
|
||||
for (i, j) in [(0, 1), (0, 2), (1, 2)] {
|
||||
let (same_x, same_y) = (same(&mut s, x[i], x[j]), same(&mut s, y[i], y[j]));
|
||||
let together = both(&mut s, same_x, same_y);
|
||||
let apart = not(&mut s, together);
|
||||
plain = both(&mut s, plain, apart);
|
||||
}
|
||||
// corner[i]: vertex i is the corner between the other two (the first
|
||||
// that shares x with one of them and y with the other).
|
||||
let mut corner: Vec<V> = Vec::new();
|
||||
for i in 0..3 {
|
||||
let (a, c) = ((i + 1) % 3, (i + 2) % 3);
|
||||
let (xa, yc) = (same(&mut s, x[i], x[a]), same(&mut s, y[i], y[c]));
|
||||
let (xc, ya) = (same(&mut s, x[i], x[c]), same(&mut s, y[i], y[a]));
|
||||
let (one, other) = (both(&mut s, xa, yc), both(&mut s, xc, ya));
|
||||
let shares = either(&mut s, one, other);
|
||||
let mut here = both(&mut s, shares, plain);
|
||||
for &found in &corner {
|
||||
let earlier = not(&mut s, found);
|
||||
here = both(&mut s, here, earlier);
|
||||
}
|
||||
corner.push(here);
|
||||
}
|
||||
|
||||
// What the six emitted vertices carry: [element][column][vertex].
|
||||
let mut emitted: Vec<Vec<[V; 6]>> = Vec::new();
|
||||
for (id, columns) in corners.iter().enumerate() {
|
||||
let float = s.inputs[id].comp == 9;
|
||||
let mut out = Vec::new();
|
||||
for &[p0, p1, p2] in columns {
|
||||
// The fourth vertex: `a + b - corner`. Integers (flat), and
|
||||
// three vertices without a corner, keep the first vertex's
|
||||
// value; the second triangle of the latter is then empty.
|
||||
let mut fourth = p0;
|
||||
if float {
|
||||
for (k, (a, c, at)) in [(p1, p2, p0), (p2, p0, p1), (p0, p1, p2)]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
let sum = s.m.bin(b, Bin::Add, a, c);
|
||||
let opposite = s.m.bin(b, Bin::Sub, sum, at);
|
||||
fourth = s.m.select(b, corner[k], opposite, fourth);
|
||||
}
|
||||
}
|
||||
// Corner first: (v0, v1, v3), (v0, v3, v2). Second: (v0, v1,
|
||||
// v2), (v0, v2, v3). Third: (v0, v1, v2), (v0, v3, v1).
|
||||
let third = s.m.select(b, corner[0], fourth, p2);
|
||||
let fifth = s.m.select(b, corner[1], p2, fourth);
|
||||
let sixth = s.m.select(b, corner[0], p2, p1);
|
||||
let sixth = s.m.select(b, corner[1], fourth, sixth);
|
||||
out.push([p0, p1, third, p0, fifth, sixth]);
|
||||
}
|
||||
emitted.push(out);
|
||||
}
|
||||
|
||||
// The rectangle's number: the triangle's, three vertices a rectangle.
|
||||
let mut number = None;
|
||||
if let Some(id) = primitive {
|
||||
let n = s.op(b, "primitiveID.i32", Attr::ReadNone, s.t.i32, 108, &[]);
|
||||
number = Some((id, n));
|
||||
}
|
||||
let stream = s.m.i8(0);
|
||||
for vertex in 0..VERTICES as usize {
|
||||
for (id, columns) in emitted.iter().enumerate() {
|
||||
let name = if s.outputs[id].comp == 9 {
|
||||
"storeOutput.f32"
|
||||
} else {
|
||||
"storeOutput.i32"
|
||||
};
|
||||
for (col, values) in columns.iter().enumerate() {
|
||||
let args = [
|
||||
s.m.i32(id as u32),
|
||||
s.m.i32(0),
|
||||
s.m.i8(col as u8),
|
||||
values[vertex],
|
||||
];
|
||||
s.op(b, name, Attr::NoUnwind, s.t.void, 5, &args);
|
||||
}
|
||||
}
|
||||
if let Some((id, n)) = number {
|
||||
let args = [s.m.i32(id as u32), s.m.i32(0), s.m.i8(0), n];
|
||||
s.op(b, "storeOutput.i32", Attr::NoUnwind, s.t.void, 5, &args);
|
||||
}
|
||||
s.op(b, "emitStream", Attr::NoUnwind, s.t.void, 97, &[stream]);
|
||||
// The strip ends after the first triangle.
|
||||
if vertex == 2 {
|
||||
s.op(b, "cutStream", Attr::NoUnwind, s.t.void, 98, &[stream]);
|
||||
}
|
||||
}
|
||||
s.m.terminate(b, Term::Ret);
|
||||
Ok(s.finish())
|
||||
}
|
||||
|
||||
/// Column `col` of input `id` at vertex `vertex` of the triangle.
|
||||
fn load(s: &mut Shader, id: usize, col: u8, vertex: u32) -> V {
|
||||
let (name, ty) = if s.inputs[id].comp == 9 {
|
||||
("loadInput.f32", s.t.f32)
|
||||
} else {
|
||||
("loadInput.i32", s.t.i32)
|
||||
};
|
||||
let args = [
|
||||
s.m.i32(id as u32),
|
||||
s.m.i32(0),
|
||||
s.m.i8(col),
|
||||
s.m.i32(vertex),
|
||||
];
|
||||
let entry = s.entry;
|
||||
s.op(entry, name, Attr::ReadNone, ty, 4, &args)
|
||||
}
|
||||
|
||||
/// Two floats are equal.
|
||||
fn same(s: &mut Shader, a: V, b: V) -> V {
|
||||
let entry = s.entry;
|
||||
s.m.cmp(entry, pred::OEQ, a, b)
|
||||
}
|
||||
|
||||
fn both(s: &mut Shader, a: V, b: V) -> V {
|
||||
let entry = s.entry;
|
||||
s.m.bin(entry, Bin::And, a, b)
|
||||
}
|
||||
|
||||
fn either(s: &mut Shader, a: V, b: V) -> V {
|
||||
let entry = s.entry;
|
||||
s.m.bin(entry, Bin::Or, a, b)
|
||||
}
|
||||
|
||||
fn not(s: &mut Shader, a: V) -> V {
|
||||
let (entry, on) = (s.entry, s.m.bool(true));
|
||||
s.m.bin(entry, Bin::Xor, a, on)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn element(name: &str, index: u32, kind: u8, comp: u8, row: u32, cols: u8) -> SigElement {
|
||||
SigElement {
|
||||
name: name.into(),
|
||||
index,
|
||||
kind,
|
||||
comp,
|
||||
interp: 0,
|
||||
row: Some(row),
|
||||
col: 0,
|
||||
cols,
|
||||
usage: 0,
|
||||
half: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// A position, a float interpolant and an integer one.
|
||||
fn outputs() -> Vec<SigElement> {
|
||||
vec![
|
||||
element("SV_Position", 0, 3, 9, 0, 4),
|
||||
element("TEXCOORD", 0, 0, 9, 1, 4),
|
||||
element("TEXCOORD", 1, 0, 5, 2, 2),
|
||||
]
|
||||
}
|
||||
|
||||
/// The stage is a geometry shader of triangles in and six strip
|
||||
/// vertices out, with the vertex shader's outputs on both sides and
|
||||
/// the primitive id the pixel shader declares; the validator, where
|
||||
/// there is one, accepts it.
|
||||
#[test]
|
||||
fn the_rectangle_stage_is_a_geometry_shader() {
|
||||
let wanted = [element("SV_PrimitiveID", 0, 10, 5, 3, 1)];
|
||||
let gs = build(outputs(), &wanted).unwrap();
|
||||
let c = Container::parse(&gs).unwrap();
|
||||
// Program version: geometry (2), shader model 6.6.
|
||||
assert_eq!(c.part(FourCC::DXIL).unwrap().data[..4], [0x66, 0, 2, 0]);
|
||||
let psv = c.part(FourCC::PSV0).unwrap().data;
|
||||
// Triangles in, triangle strips out, stream 0, a position.
|
||||
assert_eq!(psv[4..17], [3, 0, 0, 0, 5, 0, 0, 0, 1, 0, 0, 0, 1]);
|
||||
// Geometry stage, six vertices, three inputs, four outputs.
|
||||
assert_eq!(psv[28..34], [2, 0, 6, 0, 3, 4]);
|
||||
let sig = |fourcc| super::super::signature(c.part(fourcc).unwrap().data).unwrap();
|
||||
let (ins, outs) = (sig(FourCC::ISG1), sig(FourCC::OSG1));
|
||||
assert_eq!(ins.len(), 3);
|
||||
assert_eq!(outs.len(), 4);
|
||||
for (i, o) in ins.iter().zip(&outs) {
|
||||
assert_eq!((&i.name, i.index, i.row), (&o.name, o.index, o.row));
|
||||
assert_eq!((i.col, i.cols, i.comp), (o.col, o.cols, o.comp));
|
||||
}
|
||||
assert_eq!((outs[3].kind, outs[3].row), (10, Some(3)));
|
||||
#[cfg(windows)]
|
||||
if let Ok(mut v) = super::super::validator::Validator::load(
|
||||
super::super::validator::Validator::default_path().as_deref(),
|
||||
) {
|
||||
v.validate(&mut gs.clone()).unwrap();
|
||||
let plain = build(outputs(), &[]).unwrap();
|
||||
v.validate(&mut plain.clone()).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
/// Refused with a reason: no position, a primitive id in a register a
|
||||
/// vertex output has, more components than six vertices may carry.
|
||||
#[test]
|
||||
fn rectangle_stages_that_cannot_be_made_are_refused() {
|
||||
assert!(build(outputs()[1..].to_vec(), &[]).is_err());
|
||||
let taken = [element("SV_PrimitiveID", 0, 10, 5, 1, 1)];
|
||||
assert!(build(outputs(), &taken).is_err());
|
||||
let mut many = vec![element("SV_Position", 0, 3, 9, 0, 4)];
|
||||
many.extend((1..=43).map(|row| element("TEXCOORD", row - 1, 0, 9, row, 4)));
|
||||
assert!(build(many, &[]).is_err());
|
||||
}
|
||||
|
||||
/// A vertex shader that passes a position and a float4 through, and a
|
||||
/// pixel shader that writes the float4.
|
||||
#[cfg(windows)]
|
||||
fn pass_through() -> (super::super::HostShader, super::super::HostShader) {
|
||||
let position = SigElement {
|
||||
interp: 4,
|
||||
usage: 15,
|
||||
..element("SV_Position", 0, 3, 9, 0, 4)
|
||||
};
|
||||
let coord = SigElement {
|
||||
interp: 2,
|
||||
usage: 15,
|
||||
..element("TEXCOORD", 0, 0, 9, 1, 4)
|
||||
};
|
||||
let mut vs = Shader::new(false);
|
||||
vs.inputs = vec![
|
||||
SigElement {
|
||||
usage: 15,
|
||||
..element("POSITION", 0, 0, 9, 0, 4)
|
||||
},
|
||||
SigElement {
|
||||
interp: 0,
|
||||
..coord.clone()
|
||||
},
|
||||
];
|
||||
vs.outputs = vec![position.clone(), coord.clone()];
|
||||
let mut ps = Shader::new(true);
|
||||
ps.inputs = vec![
|
||||
SigElement {
|
||||
usage: 0,
|
||||
..position
|
||||
},
|
||||
coord,
|
||||
];
|
||||
ps.outputs = vec![SigElement {
|
||||
usage: 15,
|
||||
..element("SV_Target", 0, 16, 9, 0, 4)
|
||||
}];
|
||||
// Vertex: output id from input id. Pixel: target 0 from input 1.
|
||||
for (s, copies) in [(&mut vs, &[(0, 0), (1, 1)][..]), (&mut ps, &[(1, 0)][..])] {
|
||||
let b = s.entry;
|
||||
for &(from, to) in copies {
|
||||
for col in 0..4 {
|
||||
let args = [s.m.i32(from), s.m.i32(0), s.m.i8(col), s.m.undef(s.t.i32)];
|
||||
let v = s.op(b, "loadInput.f32", Attr::ReadNone, s.t.f32, 4, &args);
|
||||
let args = [s.m.i32(to), s.m.i32(0), s.m.i8(col), v];
|
||||
s.op(b, "storeOutput.f32", Attr::NoUnwind, s.t.void, 5, &args);
|
||||
}
|
||||
}
|
||||
s.m.terminate(b, Term::Ret);
|
||||
}
|
||||
let host = |stage, s: Shader| super::super::HostShader {
|
||||
stage,
|
||||
dxil: s.finish(),
|
||||
user_data: Vec::new(),
|
||||
samplers: Vec::new(),
|
||||
static_samplers: Vec::new(),
|
||||
root_cbvs: Vec::new(),
|
||||
root_srvs: Vec::new(),
|
||||
root_uavs: Vec::new(),
|
||||
root_indexed_views: Vec::new(),
|
||||
};
|
||||
(
|
||||
host(crate::native::HwStage::Vs, vs),
|
||||
host(crate::native::HwStage::Ps, ps),
|
||||
)
|
||||
}
|
||||
|
||||
/// Three corners of the whole target, the corner between the other two
|
||||
/// first (as the tiled lighting sends its tiles), second (as
|
||||
/// full-screen rectangles come) or third: with the stage every texel
|
||||
/// is drawn and the interpolant continues into the fourth corner's
|
||||
/// half; without it part of the target is not drawn.
|
||||
#[test]
|
||||
#[cfg(windows)]
|
||||
fn rectangles_are_drawn_whole() {
|
||||
use super::super::host::{Draw, Host};
|
||||
let Ok(host) = Host::new(false) else {
|
||||
eprintln!("no SM 6.6 device; skipped");
|
||||
return;
|
||||
};
|
||||
let (vs, ps) = pass_through();
|
||||
if let Ok(mut v) = super::super::validator::Validator::load(
|
||||
super::super::validator::Validator::default_path().as_deref(),
|
||||
) {
|
||||
v.validate(&mut vs.dxil.clone()).unwrap();
|
||||
v.validate(&mut ps.dxil.clone()).unwrap();
|
||||
}
|
||||
let gs = rect_list_gs(&vs.dxil, Some(&ps.dxil[..])).unwrap();
|
||||
let root = host.root_signature(&vs, &ps).unwrap();
|
||||
// Position (z 0.5, w 1) and an interpolant that is the position.
|
||||
let vertex = |(x, y): (f32, f32)| [x, y, 0.5, 1.0, x, y, 0.0, 1.0];
|
||||
for (name, corners) in [
|
||||
("corner first", [(-1.0, 1.0), (-1.0, -1.0), (1.0, 1.0)]),
|
||||
("corner second", [(-1.0, 1.0), (-1.0, -1.0), (1.0, -1.0)]),
|
||||
("corner third", [(-1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)]),
|
||||
] {
|
||||
let vertices = corners.map(vertex).concat();
|
||||
let draw = |gs: Option<&[u8]>| {
|
||||
let pso = host
|
||||
.pipeline_with_gs(&root, &vs.dxil, gs, &ps.dxil)
|
||||
.unwrap();
|
||||
let d = Draw {
|
||||
roots: Vec::new(),
|
||||
textures: &[],
|
||||
samplers: &[],
|
||||
vertices: &vertices,
|
||||
stride: 32,
|
||||
size: (8, 8),
|
||||
mesh_groups: 0,
|
||||
};
|
||||
host.draw(&root, &pso, &d).unwrap()
|
||||
};
|
||||
let whole = draw(Some(&gs[..]));
|
||||
for (i, texel) in whole.iter().enumerate() {
|
||||
let (x, y) = ((i % 8) as f32, (i / 8) as f32);
|
||||
let want = [(x + 0.5) / 4.0 - 1.0, 1.0 - (y + 0.5) / 4.0, 0.0, 1.0];
|
||||
assert!(
|
||||
texel.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-4),
|
||||
"{name}: texel {i} is {texel:?}, not {want:?}"
|
||||
);
|
||||
}
|
||||
let half = draw(None);
|
||||
let missing = half.iter().zip(&whole).filter(|(a, b)| a != b).count();
|
||||
assert!(missing >= 24, "{name}: only {missing} texels need the stage");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
//! Immediate samplers: the console's four sampler words (the GPU's public
|
||||
//! `SQ_IMG_SAMP_WORD0-3` layout) as a D3D12 static sampler.
|
||||
//!
|
||||
//! Word 0: address modes x, y, z (bits 0-8, 3 each), log2 of the maximum
|
||||
//! anisotropy (9-11), comparison function (12-14), reduction (29-30: 0
|
||||
//! filtering, 1 minimum, 2 maximum). Word 1: minimum and maximum LOD
|
||||
//! (0-11, 12-23, unsigned 4.8). Word 2: LOD bias (0-13, signed 5.8),
|
||||
//! magnification and minification filters (20-21, 22-23: point, linear,
|
||||
//! anisotropic point, anisotropic linear), mip filter (26-27: none, point,
|
||||
//! linear). Word 3: border colour (30-31: transparent black, opaque black,
|
||||
//! opaque white, custom).
|
||||
//!
|
||||
//! Comparison is the sampling instruction's, not the sampler's: the console
|
||||
//! encodes a comparison function in every sampler (D3D's default, less or
|
||||
//! equal, when unused).
|
||||
|
||||
/// A static sampler in D3D12 terms; the integers are the `D3D12_FILTER`,
|
||||
/// `D3D12_TEXTURE_ADDRESS_MODE`, `D3D12_COMPARISON_FUNC` and
|
||||
/// `D3D12_STATIC_BORDER_COLOR` values.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct StaticSampler {
|
||||
pub filter: u32,
|
||||
/// U, V, W.
|
||||
pub address: [u32; 3],
|
||||
pub mip_lod_bias: f32,
|
||||
pub max_anisotropy: u32,
|
||||
pub comparison: u32,
|
||||
pub border: u32,
|
||||
pub min_lod: f32,
|
||||
pub max_lod: f32,
|
||||
}
|
||||
|
||||
// The floats come from fixed-point fields: never NaN.
|
||||
impl Eq for StaticSampler {}
|
||||
|
||||
impl StaticSampler {
|
||||
/// Decodes the four sampler words.
|
||||
pub fn from_words(w: [u32; 4]) -> Self {
|
||||
let bits = |word: u32, at: u32, n: u32| word >> at & ((1 << n) - 1);
|
||||
// wrap, mirror, clamp, mirror once; the half-border modes have no
|
||||
// D3D form and become their nearest.
|
||||
let address = |m: u32| [1, 2, 3, 5, 3, 5, 4, 5][m as usize];
|
||||
let (mag, min, mip) = (bits(w[2], 20, 2), bits(w[2], 22, 2), bits(w[2], 26, 2));
|
||||
let reduction = match bits(w[0], 29, 2) {
|
||||
1 => 2,
|
||||
2 => 3,
|
||||
_ => 0,
|
||||
};
|
||||
let filter = if mag >= 2 || min >= 2 {
|
||||
0x55 | reduction << 7
|
||||
} else {
|
||||
(min & 1) << 4 | (mag & 1) << 2 | u32::from(mip == 2) | reduction << 7
|
||||
};
|
||||
let lod = |v: u32| v as f32 / 256.0;
|
||||
// Without a mip filter the base level is sampled.
|
||||
let (min_lod, max_lod) = if mip == 0 {
|
||||
(0.0, 0.0)
|
||||
} else {
|
||||
(lod(bits(w[1], 0, 12)), lod(bits(w[1], 12, 12)))
|
||||
};
|
||||
StaticSampler {
|
||||
filter,
|
||||
address: [0, 3, 6].map(|at| address(bits(w[0], at, 3))),
|
||||
mip_lod_bias: ((bits(w[2], 0, 14) << 18) as i32 >> 18) as f32 / 256.0,
|
||||
max_anisotropy: 1 << bits(w[0], 9, 3).min(4),
|
||||
comparison: bits(w[0], 12, 3) + 1,
|
||||
// shortcut: a custom border colour (type 3, a table entry) becomes
|
||||
// transparent black; upgrade when a title uses one.
|
||||
border: bits(w[3], 30, 2) % 3,
|
||||
min_lod,
|
||||
max_lod,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn console_compiled_samplers_decode() {
|
||||
// Words the console compiler wrote for static samplers of known
|
||||
// descriptions.
|
||||
let point = StaticSampler::from_words([0x3088, 0x0054_0100, 0x1400_0080, 0x8000_0000]);
|
||||
assert_eq!(
|
||||
point,
|
||||
StaticSampler {
|
||||
filter: 0,
|
||||
address: [1, 2, 3],
|
||||
mip_lod_bias: 0.5,
|
||||
max_anisotropy: 1,
|
||||
comparison: 4,
|
||||
border: 2,
|
||||
min_lod: 1.0,
|
||||
max_lod: 5.25,
|
||||
}
|
||||
);
|
||||
let aniso = StaticSampler::from_words([0x369E, 0x00FF_F000, 0x18F0_3E00, 0x8000_0000]);
|
||||
assert_eq!(
|
||||
(aniso.filter, aniso.address, aniso.max_anisotropy),
|
||||
(0x55, [4, 5, 3], 8)
|
||||
);
|
||||
assert_eq!((aniso.mip_lod_bias, aniso.max_lod), (-2.0, 4095.0 / 256.0));
|
||||
let compare = StaticSampler::from_words([0x3006, 0x00FF_F000, 0x1450_0000, 0x4000_0000]);
|
||||
assert_eq!(
|
||||
(compare.filter, compare.address, compare.border),
|
||||
(0x14, [4, 1, 1], 1)
|
||||
);
|
||||
let minimum =
|
||||
StaticSampler::from_words([0x2000_3003, 0x00FF_F000, 0x1850_0000, 0x8000_0000]);
|
||||
assert_eq!((minimum.filter, minimum.address[0]), (0x115, 5));
|
||||
let mag_mip = StaticSampler::from_words([0x3002, 0, 0x1810_0000, 0x8000_0000]);
|
||||
assert_eq!((mag_mip.filter, mag_mip.max_lod), (0x05, 0.0));
|
||||
let max_aniso =
|
||||
StaticSampler::from_words([0x4000_3800, 0x00FF_F000, 0x18F0_0F00, 0x8000_0000]);
|
||||
assert_eq!(
|
||||
(
|
||||
max_aniso.filter,
|
||||
max_aniso.max_anisotropy,
|
||||
max_aniso.mip_lod_bias
|
||||
),
|
||||
(0x1D5, 16, 15.0)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,908 @@
|
||||
//! A DXIL vertex, pixel, compute or mesh shader under construction: the module,
|
||||
//! the `dx.op` declarations it calls, its signatures and bound resources,
|
||||
//! and the metadata and container that wrap it up (SM 6.6, validator 1.6).
|
||||
|
||||
use super::bitcode::{Attr, Md, Module, Ty, V};
|
||||
use super::container::{self, Binding, Psv, SigElement};
|
||||
|
||||
/// Where the shader reads its user data: `b0` in this space.
|
||||
pub const USER_DATA_SPACE: u32 = 0;
|
||||
/// Where immediate samplers are bound: `s<n>` in this space.
|
||||
pub const SAMPLER_SPACE: u32 = 0;
|
||||
/// Where root CBVs and SRVs are bound: `b<root parameter index>` and
|
||||
/// `t<root parameter index>` in this space.
|
||||
pub const ROOT_CBV_SPACE: u32 = 1;
|
||||
|
||||
/// The root SRV `t<SLOT_STRIDES>` in [`ROOT_CBV_SPACE`] of a shader that
|
||||
/// reads buffers through descriptors it picks from the view heap at an
|
||||
/// index it computes (SM 6.6 dynamic resources): a raw buffer of
|
||||
/// [`SLOT_STRIDES_COUNT`] dwords the host keeps, dword `i` the bytes per
|
||||
/// element of the buffer view at heap slot `i` (0: none or not a buffer).
|
||||
/// The console's descriptor holds that stride and its hardware multiplies
|
||||
/// the element index by it; the program's code does not say it, and the
|
||||
/// used-resource list only names what tables hold. A shader that has this
|
||||
/// root SRV also tells the host that the buffer views of the whole heap
|
||||
/// must be ready when it runs, not only those its tables name.
|
||||
pub const SLOT_STRIDES: u8 = 255;
|
||||
/// Dwords of the [`SLOT_STRIDES`] buffer: heap indices are clamped to it.
|
||||
pub const SLOT_STRIDES_COUNT: u32 = 1 << 21;
|
||||
|
||||
/// Title memory by address (`resource::MEMORY`): console code reads and
|
||||
/// writes through raw 40-bit addresses it takes from root constants,
|
||||
/// descriptors and other memory (the ray-tracing structure builder and the
|
||||
/// programs that walk its structures). The host keeps copies of the title
|
||||
/// memory shaders use; a shader with such an access finds the copy by the
|
||||
/// address:
|
||||
///
|
||||
/// - the root SRV `t<SLOT_MEMORY>` in [`ROOT_CBV_SPACE`] is a directory of
|
||||
/// [`MEMORY_PAGES`] entries of two dwords, one per 64 KiB of title
|
||||
/// address space: the number of the host copy holding that page (0: none
|
||||
/// yet) and the page's byte offset in that copy;
|
||||
/// - copy `n` is the raw buffer view at view-heap slot `base + n`, `base`
|
||||
/// the user-data dword of kind [`USER_MEMORY_BASE`]; slot `base` itself
|
||||
/// reads zeros and drops writes;
|
||||
/// - the root UAV `u<SLOT_FAULTS>` takes the page numbers of accesses that
|
||||
/// found no copy ([`MEMORY_FAULTS`] dwords, dword 0 a sink), which the
|
||||
/// host reads afterwards to make those copies for the frames to come.
|
||||
pub const SLOT_MEMORY: u8 = 254;
|
||||
/// See [`SLOT_MEMORY`].
|
||||
pub const SLOT_FAULTS: u8 = 253;
|
||||
/// Entries of the [`SLOT_MEMORY`] directory: title addresses below 128 GiB.
|
||||
pub const MEMORY_PAGES: u32 = 1 << 21;
|
||||
/// Dwords of the [`SLOT_FAULTS`] buffer.
|
||||
pub const MEMORY_FAULTS: u32 = 4096;
|
||||
/// `RootType::Other` code of a user-data dword the host computes: the view
|
||||
/// heap slot of the memory copies' views ([`SLOT_MEMORY`]).
|
||||
pub const USER_MEMORY_BASE: u32 = 0x100;
|
||||
/// `RootType::Other` code of a user-data dword the host computes: the low
|
||||
/// 32 bits of the title address of the buffer view at dword `dword` of the
|
||||
/// descriptor table of root parameter `slot`; [`USER_VIEW_ADDRESS`] + 1:
|
||||
/// its bits from 32 up. (Console code reads the address out of a buffer
|
||||
/// descriptor and uses it as a pointer.)
|
||||
pub const USER_VIEW_ADDRESS: u32 = 0x101;
|
||||
/// `RootType::Other` code of a user-data dword the host computes: the
|
||||
/// bytes (0 to 15) by which the raw view the host binds for the root view
|
||||
/// of root parameter `slot` begins before the title's address. A raw view
|
||||
/// begins on 16 bytes of its host buffer; the console's root views begin
|
||||
/// anywhere (the structure builder's counters sit at addresses ending in
|
||||
/// 4 and c). The shader adds the dword to every byte offset through that
|
||||
/// view. Asked for every root UAV, and for the root SRVs of programs with
|
||||
/// a spilled user-data table.
|
||||
pub const USER_VIEW_BIAS: u32 = 0x103;
|
||||
|
||||
/// `ShaderFlags` bits (metadata) and their `SFI0` feature bits.
|
||||
pub(crate) mod flags {
|
||||
pub const RAW_BUFFERS: u64 = 1 << 4;
|
||||
pub const DOUBLES: u64 = 1 << 2;
|
||||
pub const STENCIL_REF: u64 = 1 << 11;
|
||||
pub const TYPED_UAV_LOADS: u64 = 1 << 13;
|
||||
pub const WAVE_OPS: u64 = 1 << 19;
|
||||
pub const BARYCENTRICS: u64 = 1 << 22;
|
||||
pub const INT64: u64 = 1 << 20;
|
||||
pub const ATOMIC_TYPED64: u64 = 1 << 27;
|
||||
pub const ATOMIC_HEAP64: u64 = 1 << 32;
|
||||
pub const RESOURCE_HEAP: u64 = 1 << 30;
|
||||
pub const SAMPLER_HEAP: u64 = 1 << 31;
|
||||
pub const ROVS: u64 = 1 << 18;
|
||||
}
|
||||
|
||||
pub(crate) struct Types {
|
||||
pub void: Ty,
|
||||
pub i1: Ty,
|
||||
pub i32: Ty,
|
||||
pub f32: Ty,
|
||||
pub handle: Ty,
|
||||
pub props: Ty,
|
||||
pub bind: Ty,
|
||||
pub cbuf_ret: Ty,
|
||||
pub res_ret: Ty,
|
||||
}
|
||||
|
||||
/// What a mesh shader declares beyond its thread-group size.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) struct Mesh {
|
||||
pub max_vertices: u32,
|
||||
pub max_primitives: u32,
|
||||
/// 1 lines, 2 triangles.
|
||||
pub topology: u8,
|
||||
}
|
||||
|
||||
/// What a geometry shader declares: triangles in, triangle strips out on
|
||||
/// stream 0, one instance.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) struct Geometry {
|
||||
pub max_vertices: u32,
|
||||
}
|
||||
|
||||
/// The null slot every host view heap keeps at its end (0: no limit). Shaders translated while
|
||||
/// it is set read that slot for any view index at or past it. A read past a heap's end is
|
||||
/// undefined: a host that caps its heap (NVIDIA at 1 000 000 views; a retail game's heap is
|
||||
/// larger) hung its GPU (GPU-based validation: "descriptor heap index out of bounds"), and AMD
|
||||
/// RDNA3 took a page fault and removed the device.
|
||||
static VIEW_LIMIT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
|
||||
|
||||
/// See [`VIEW_LIMIT`]: `null_slot` is the last slot of the host's view heap, kept null.
|
||||
pub fn set_view_heap_limit(null_slot: u32) {
|
||||
VIEW_LIMIT.store(null_slot, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// See [`VIEW_LIMIT`]: the null slot shaders translated now clamp view indices to (0: none).
|
||||
pub fn view_heap_limit() -> u32 {
|
||||
VIEW_LIMIT.load(std::sync::atomic::Ordering::Relaxed)
|
||||
}
|
||||
|
||||
pub(crate) struct Shader {
|
||||
pub m: Module,
|
||||
pub t: Types,
|
||||
pub pixel: bool,
|
||||
pub inputs: Vec<SigElement>,
|
||||
pub outputs: Vec<SigElement>,
|
||||
/// A mesh shader's per-primitive outputs.
|
||||
pub prims: Vec<SigElement>,
|
||||
/// A mesh shader (`threads` is its thread-group size).
|
||||
pub mesh: Option<Mesh>,
|
||||
/// A geometry shader (the rectangle stage, `rect.rs`); `pixel` is false.
|
||||
pub geometry: Option<Geometry>,
|
||||
/// Dwords of user data the shader reads (0: no user-data buffer).
|
||||
pub user_data: u32,
|
||||
/// Immediate samplers, bound as `s0..` in [`SAMPLER_SPACE`].
|
||||
pub samplers: u32,
|
||||
/// Bit n: immediate sampler n is a comparison sampler.
|
||||
pub cmp_samplers: u64,
|
||||
/// Root CBVs read, by root parameter index, with their handles.
|
||||
pub root_cbvs: Vec<(u8, V)>,
|
||||
/// Root SRVs (raw buffers) read, likewise.
|
||||
pub root_srvs: Vec<(u8, V)>,
|
||||
/// Root UAVs (raw buffers) read or written, likewise.
|
||||
pub root_uavs: Vec<(u8, V)>,
|
||||
pub flags: u64,
|
||||
/// Every UAV the shader opens is rasterizer ordered ([`Self::annotate`]).
|
||||
pub rov: bool,
|
||||
/// Heap handles made with a non-uniform index.
|
||||
pub nonuniform_handles: u32,
|
||||
/// A compute shader with this thread-group size.
|
||||
pub threads: Option<[u32; 3]>,
|
||||
/// The wave size a compute shader requires (`WaveSize`).
|
||||
pub wave_size: Option<u32>,
|
||||
/// Thread-group shared memory, in dwords.
|
||||
pub lds_dwords: u32,
|
||||
lds: Option<V>,
|
||||
main: V,
|
||||
pub entry: usize,
|
||||
}
|
||||
|
||||
impl Shader {
|
||||
pub fn new(pixel: bool) -> Self {
|
||||
let mut m = Module::default();
|
||||
let void = m.void();
|
||||
let i1 = m.int(1);
|
||||
let i8 = m.int(8);
|
||||
let i32 = m.int(32);
|
||||
let f32 = m.float();
|
||||
let i8p = m.ptr(i8);
|
||||
let handle = m.named_struct("dx.types.Handle", vec![i8p]);
|
||||
let props = m.named_struct("dx.types.ResourceProperties", vec![i32, i32]);
|
||||
let bind = m.named_struct("dx.types.ResBind", vec![i32, i32, i32, i8]);
|
||||
let cbuf_ret = m.named_struct("dx.types.CBufRet.i32", vec![i32, i32, i32, i32]);
|
||||
let res_ret = m.named_struct("dx.types.ResRet.f32", vec![f32, f32, f32, f32, i32]);
|
||||
let main_ty = m.func_ty(void, vec![]);
|
||||
m.ptr(main_ty);
|
||||
let main = m.function("main", main_ty, None, true);
|
||||
let entry = m.new_block();
|
||||
Shader {
|
||||
m,
|
||||
t: Types {
|
||||
void,
|
||||
i1,
|
||||
i32,
|
||||
f32,
|
||||
handle,
|
||||
props,
|
||||
bind,
|
||||
cbuf_ret,
|
||||
res_ret,
|
||||
},
|
||||
pixel,
|
||||
inputs: Vec::new(),
|
||||
outputs: Vec::new(),
|
||||
prims: Vec::new(),
|
||||
mesh: None,
|
||||
geometry: None,
|
||||
user_data: 0,
|
||||
samplers: 0,
|
||||
cmp_samplers: 0,
|
||||
root_cbvs: Vec::new(),
|
||||
root_srvs: Vec::new(),
|
||||
root_uavs: Vec::new(),
|
||||
flags: 0,
|
||||
rov: false,
|
||||
nonuniform_handles: 0,
|
||||
threads: None,
|
||||
wave_size: None,
|
||||
lds_dwords: 0,
|
||||
lds: None,
|
||||
main,
|
||||
entry,
|
||||
}
|
||||
}
|
||||
|
||||
/// The thread-group shared memory: `[lds_dwords x i32]` in address
|
||||
/// space 3.
|
||||
pub fn lds(&mut self) -> V {
|
||||
if let Some(g) = self.lds {
|
||||
return g;
|
||||
}
|
||||
let arr = self.m.array(self.lds_dwords, self.t.i32);
|
||||
let g = self.m.global("lds", arr, 3);
|
||||
self.lds = Some(g);
|
||||
g
|
||||
}
|
||||
|
||||
/// Calls `dx.op.<name>` (class and overload) with `opcode` and `args`.
|
||||
pub fn op(
|
||||
&mut self,
|
||||
block: usize,
|
||||
name: &str,
|
||||
attr: Attr,
|
||||
ret: Ty,
|
||||
opcode: u32,
|
||||
args: &[V],
|
||||
) -> V {
|
||||
let mut params = vec![self.t.i32];
|
||||
params.extend(args.iter().map(|&a| self.m.type_of(a)));
|
||||
let fty = self.m.func_ty(ret, params);
|
||||
self.m.ptr(fty);
|
||||
let f = self
|
||||
.m
|
||||
.function(&format!("dx.op.{name}"), fty, Some(attr), false);
|
||||
let mut all = vec![self.m.i32(opcode)];
|
||||
all.extend(args);
|
||||
self.m.call(block, f, all)
|
||||
}
|
||||
|
||||
/// The handle of the user-data constant buffer, made in the entry block.
|
||||
pub fn user_data_handle(&mut self) -> V {
|
||||
let bind = [
|
||||
self.m.i32(0),
|
||||
self.m.i32(0),
|
||||
self.m.i32(USER_DATA_SPACE),
|
||||
self.m.i8(2), // CBV
|
||||
];
|
||||
let bind = self.m.aggregate(self.t.bind, &bind);
|
||||
let block = self.entry;
|
||||
let (i, f) = (self.m.i32(0), self.m.bool(false));
|
||||
let h = self.op(
|
||||
block,
|
||||
"createHandleFromBinding",
|
||||
Attr::ReadNone,
|
||||
self.t.handle,
|
||||
217,
|
||||
&[bind, i, f],
|
||||
);
|
||||
// The size is known in `finish`, which fixes this placeholder.
|
||||
self.annotate(block, h, 13, u32::MAX)
|
||||
}
|
||||
|
||||
/// The handle of the root CBV of root parameter `slot`, made in the
|
||||
/// entry block.
|
||||
pub fn root_cbv_handle(&mut self, slot: u8) -> V {
|
||||
if let Some(&(_, h)) = self.root_cbvs.iter().find(|r| r.0 == slot) {
|
||||
return h;
|
||||
}
|
||||
let r = self.m.i32(u32::from(slot));
|
||||
let bind = [r, r, self.m.i32(ROOT_CBV_SPACE), self.m.i8(2)];
|
||||
let bind = self.m.aggregate(self.t.bind, &bind);
|
||||
let f = self.m.bool(false);
|
||||
let block = self.entry;
|
||||
let h = self.op(
|
||||
block,
|
||||
"createHandleFromBinding",
|
||||
Attr::ReadNone,
|
||||
self.t.handle,
|
||||
217,
|
||||
&[bind, r, f],
|
||||
);
|
||||
let h = self.annotate(block, h, 13, 65536);
|
||||
self.root_cbvs.push((slot, h));
|
||||
h
|
||||
}
|
||||
|
||||
/// The handle of the root SRV (a raw buffer) of root parameter `slot`.
|
||||
pub fn root_srv_handle(&mut self, slot: u8) -> V {
|
||||
if let Some(&(_, h)) = self.root_srvs.iter().find(|r| r.0 == slot) {
|
||||
return h;
|
||||
}
|
||||
let r = self.m.i32(u32::from(slot));
|
||||
let bind = [r, r, self.m.i32(ROOT_CBV_SPACE), self.m.i8(0)];
|
||||
let bind = self.m.aggregate(self.t.bind, &bind);
|
||||
let f = self.m.bool(false);
|
||||
let block = self.entry;
|
||||
let h = self.op(
|
||||
block,
|
||||
"createHandleFromBinding",
|
||||
Attr::ReadNone,
|
||||
self.t.handle,
|
||||
217,
|
||||
&[bind, r, f],
|
||||
);
|
||||
let h = self.annotate(block, h, 11, 0);
|
||||
self.flags |= flags::RAW_BUFFERS;
|
||||
self.root_srvs.push((slot, h));
|
||||
h
|
||||
}
|
||||
|
||||
/// The handle of the root UAV (a raw buffer) of root parameter `slot`:
|
||||
/// `u<slot>` in [`ROOT_CBV_SPACE`].
|
||||
pub fn root_uav_handle(&mut self, slot: u8) -> V {
|
||||
if let Some(&(_, h)) = self.root_uavs.iter().find(|r| r.0 == slot) {
|
||||
return h;
|
||||
}
|
||||
let r = self.m.i32(u32::from(slot));
|
||||
let bind = [r, r, self.m.i32(ROOT_CBV_SPACE), self.m.i8(1)];
|
||||
let bind = self.m.aggregate(self.t.bind, &bind);
|
||||
let f = self.m.bool(false);
|
||||
let block = self.entry;
|
||||
let h = self.op(
|
||||
block,
|
||||
"createHandleFromBinding",
|
||||
Attr::ReadNone,
|
||||
self.t.handle,
|
||||
217,
|
||||
&[bind, r, f],
|
||||
);
|
||||
let h = self.annotate(block, h, 11 | 0x1000, 0);
|
||||
self.flags |= flags::RAW_BUFFERS;
|
||||
self.root_uavs.push((slot, h));
|
||||
h
|
||||
}
|
||||
|
||||
/// The handle of immediate sampler `n` (a comparison sampler when its
|
||||
/// bit in `cmp_samplers` is set).
|
||||
pub fn sampler_handle(&mut self, block: usize, n: u32) -> V {
|
||||
let bind = [
|
||||
self.m.i32(n),
|
||||
self.m.i32(n),
|
||||
self.m.i32(SAMPLER_SPACE),
|
||||
self.m.i8(3), // sampler
|
||||
];
|
||||
let bind = self.m.aggregate(self.t.bind, &bind);
|
||||
let (i, f) = (self.m.i32(n), self.m.bool(false));
|
||||
let h = self.op(
|
||||
block,
|
||||
"createHandleFromBinding",
|
||||
Attr::ReadNone,
|
||||
self.t.handle,
|
||||
217,
|
||||
&[bind, i, f],
|
||||
);
|
||||
let cmp = if self.cmp_samplers >> n & 1 != 0 {
|
||||
0x8000
|
||||
} else {
|
||||
0
|
||||
};
|
||||
self.annotate(block, h, 14 | cmp, 0)
|
||||
}
|
||||
|
||||
/// Annotates a handle with its resource properties. Bit 12 of `props0` is
|
||||
/// "UAV"; with `rov` set a UAV also gets bit 13, rasterizer ordered.
|
||||
pub fn annotate(&mut self, block: usize, h: V, props0: u32, props1: u32) -> V {
|
||||
let props0 = if self.rov && props0 & 0x1000 != 0 {
|
||||
self.flags |= flags::ROVS;
|
||||
props0 | 0x2000
|
||||
} else {
|
||||
props0
|
||||
};
|
||||
let p = [self.m.i32(props0), self.m.i32(props1)];
|
||||
let p = self.m.aggregate(self.t.props, &p);
|
||||
self.op(
|
||||
block,
|
||||
"annotateHandle",
|
||||
Attr::ReadNone,
|
||||
self.t.handle,
|
||||
216,
|
||||
&[h, p],
|
||||
)
|
||||
}
|
||||
|
||||
/// A descriptor heap handle, annotated with `props`; `nonuniform` when
|
||||
/// the index may differ between lanes (`NonUniformResourceIndex`).
|
||||
pub fn heap_handle(
|
||||
&mut self,
|
||||
block: usize,
|
||||
index: V,
|
||||
sampler: bool,
|
||||
nonuniform: bool,
|
||||
props: (u32, u32),
|
||||
) -> V {
|
||||
// a view index past the host heap (`set_view_heap_limit`) reads its null slot instead
|
||||
let limit = VIEW_LIMIT.load(std::sync::atomic::Ordering::Relaxed);
|
||||
// (as `dx.op.binary` UMin: a compare and select emitted here made the bitcode invalid)
|
||||
let index = if !sampler && limit != 0 {
|
||||
let null = self.m.i32(limit);
|
||||
let i32t = self.t.i32;
|
||||
let v = self.op(block, "binary.i32", Attr::ReadNone, i32t, 40, &[index, null]);
|
||||
self.m.tag(v, super::bitcode::Tag::Clamp);
|
||||
v
|
||||
} else if sampler {
|
||||
// A sampler heap has at most 2,048 samplers on any host: an
|
||||
// index past that (a number read from memory the host has not
|
||||
// got yet) stays inside the largest heap there is.
|
||||
// shortcut: not the bound heap's own count, which a title
|
||||
// heap smaller than 2,048 would need.
|
||||
let last = self.m.i32(2047);
|
||||
let i32t = self.t.i32;
|
||||
let v = self.op(block, "binary.i32", Attr::ReadNone, i32t, 40, &[index, last]);
|
||||
self.m.tag(v, super::bitcode::Tag::Clamp);
|
||||
v
|
||||
} else {
|
||||
index
|
||||
};
|
||||
self.flags |= if sampler {
|
||||
flags::SAMPLER_HEAP
|
||||
} else {
|
||||
flags::RESOURCE_HEAP
|
||||
};
|
||||
self.nonuniform_handles += u32::from(nonuniform);
|
||||
let (s, n) = (self.m.bool(sampler), self.m.bool(nonuniform));
|
||||
let h = self.op(
|
||||
block,
|
||||
"createHandleFromHeap",
|
||||
Attr::ReadNone,
|
||||
self.t.handle,
|
||||
218,
|
||||
&[index, s, n],
|
||||
);
|
||||
self.annotate(block, h, props.0, props.1)
|
||||
}
|
||||
|
||||
/// The finished container.
|
||||
pub fn finish(mut self) -> Vec<u8> {
|
||||
let ud_size = (self.user_data * 4).next_multiple_of(16);
|
||||
self.fix_user_data_size(ud_size);
|
||||
// The clean-up, before anything is declared about the code: a
|
||||
// feature whose last use it removed must not be declared (the
|
||||
// validator compares the flags with what the code uses).
|
||||
let passes = super::shader_opt() & super::bitcode::opt::MODULE;
|
||||
if passes != 0 {
|
||||
self.m.optimise(passes);
|
||||
let used = self.m.usage();
|
||||
for (flag, used) in [
|
||||
(flags::WAVE_OPS, used.wave_ops),
|
||||
(flags::ROVS, used.rov),
|
||||
(flags::INT64, used.int64),
|
||||
(flags::TYPED_UAV_LOADS, used.typed_uav_loads),
|
||||
(flags::RESOURCE_HEAP, used.heap_views),
|
||||
(flags::SAMPLER_HEAP, used.heap_samplers),
|
||||
(flags::ATOMIC_TYPED64 | flags::ATOMIC_HEAP64, used.atomic64),
|
||||
] {
|
||||
if !used {
|
||||
self.flags &= !flag;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut resources = None;
|
||||
let mut bindings = Vec::new();
|
||||
let i32c = |s: &mut Self, v: u32| {
|
||||
let c = s.m.i32(v);
|
||||
s.m.md_value(c)
|
||||
};
|
||||
if self.user_data > 0
|
||||
|| self.samplers > 0
|
||||
|| !self.root_cbvs.is_empty()
|
||||
|| !self.root_srvs.is_empty()
|
||||
|| !self.root_uavs.is_empty()
|
||||
{
|
||||
let empty = self.m.md_str("");
|
||||
let mut cbvs = None;
|
||||
let mut cbv_list = Vec::new();
|
||||
if self.user_data > 0 {
|
||||
let arr = self.m.array(self.user_data.next_multiple_of(4), self.t.i32);
|
||||
let ty = self.m.named_struct("UserData", vec![arr]);
|
||||
let p = self.m.ptr(ty);
|
||||
let u = self.m.undef(p);
|
||||
let ops = vec![
|
||||
Some(i32c(&mut self, 0)),
|
||||
Some(self.m.md_value(u)),
|
||||
Some(empty),
|
||||
Some(i32c(&mut self, USER_DATA_SPACE)),
|
||||
Some(i32c(&mut self, 0)),
|
||||
Some(i32c(&mut self, 1)),
|
||||
Some(i32c(&mut self, ud_size)),
|
||||
None,
|
||||
];
|
||||
cbv_list.push(Some(self.m.md_node(ops)));
|
||||
bindings.push(Binding {
|
||||
kind: 2,
|
||||
space: USER_DATA_SPACE,
|
||||
register: 0,
|
||||
dxil_kind: 13,
|
||||
});
|
||||
}
|
||||
let blob = self.m.array(16384, self.t.i32);
|
||||
let ty = self.m.named_struct("RootCbv", vec![blob]);
|
||||
let p = self.m.ptr(ty);
|
||||
let u = self.m.undef(p);
|
||||
for (slot, _) in self.root_cbvs.clone() {
|
||||
let ops = vec![
|
||||
Some(i32c(&mut self, cbv_list.len() as u32)),
|
||||
Some(self.m.md_value(u)),
|
||||
Some(empty),
|
||||
Some(i32c(&mut self, ROOT_CBV_SPACE)),
|
||||
Some(i32c(&mut self, u32::from(slot))),
|
||||
Some(i32c(&mut self, 1)),
|
||||
Some(i32c(&mut self, 65536)),
|
||||
None,
|
||||
];
|
||||
cbv_list.push(Some(self.m.md_node(ops)));
|
||||
bindings.push(Binding {
|
||||
kind: 2,
|
||||
space: ROOT_CBV_SPACE,
|
||||
register: u32::from(slot),
|
||||
dxil_kind: 13,
|
||||
});
|
||||
}
|
||||
if !cbv_list.is_empty() {
|
||||
cbvs = Some(self.m.md_node(cbv_list));
|
||||
}
|
||||
let mut srvs = None;
|
||||
if !self.root_srvs.is_empty() {
|
||||
let ty = self
|
||||
.m
|
||||
.named_struct("struct.ByteAddressBuffer", vec![self.t.i32]);
|
||||
let p = self.m.ptr(ty);
|
||||
let u = self.m.undef(p);
|
||||
let mut list = Vec::new();
|
||||
for (n, (slot, _)) in self.root_srvs.clone().into_iter().enumerate() {
|
||||
let ops = vec![
|
||||
Some(i32c(&mut self, n as u32)),
|
||||
Some(self.m.md_value(u)),
|
||||
Some(empty),
|
||||
Some(i32c(&mut self, ROOT_CBV_SPACE)),
|
||||
Some(i32c(&mut self, u32::from(slot))),
|
||||
Some(i32c(&mut self, 1)),
|
||||
Some(i32c(&mut self, 11)),
|
||||
Some(i32c(&mut self, 0)),
|
||||
None,
|
||||
];
|
||||
list.push(Some(self.m.md_node(ops)));
|
||||
bindings.push(Binding {
|
||||
kind: 4,
|
||||
space: ROOT_CBV_SPACE,
|
||||
register: u32::from(slot),
|
||||
dxil_kind: 11,
|
||||
});
|
||||
}
|
||||
srvs = Some(self.m.md_node(list));
|
||||
}
|
||||
let mut uavs = None;
|
||||
if !self.root_uavs.is_empty() {
|
||||
let ty = self
|
||||
.m
|
||||
.named_struct("struct.RWByteAddressBuffer", vec![self.t.i32]);
|
||||
let p = self.m.ptr(ty);
|
||||
let u = self.m.undef(p);
|
||||
let no = self.m.bool(false);
|
||||
let no = self.m.md_value(no);
|
||||
let mut list = Vec::new();
|
||||
for (n, (slot, _)) in self.root_uavs.clone().into_iter().enumerate() {
|
||||
// Id, variable, name, space, lower bound, range size,
|
||||
// shape (11: raw buffer), globally coherent, counter,
|
||||
// rasterizer ordered, no extra properties.
|
||||
let ordered = self.m.bool(self.rov);
|
||||
let ordered = self.m.md_value(ordered);
|
||||
let ops = vec![
|
||||
Some(i32c(&mut self, n as u32)),
|
||||
Some(self.m.md_value(u)),
|
||||
Some(empty),
|
||||
Some(i32c(&mut self, ROOT_CBV_SPACE)),
|
||||
Some(i32c(&mut self, u32::from(slot))),
|
||||
Some(i32c(&mut self, 1)),
|
||||
Some(i32c(&mut self, 11)),
|
||||
Some(no),
|
||||
Some(no),
|
||||
Some(ordered),
|
||||
None,
|
||||
];
|
||||
list.push(Some(self.m.md_node(ops)));
|
||||
bindings.push(Binding {
|
||||
kind: 7,
|
||||
space: ROOT_CBV_SPACE,
|
||||
register: u32::from(slot),
|
||||
dxil_kind: 11,
|
||||
});
|
||||
}
|
||||
uavs = Some(self.m.md_node(list));
|
||||
}
|
||||
let mut samplers = None;
|
||||
if self.samplers > 0 {
|
||||
let ty = self.m.named_struct("struct.SamplerState", vec![self.t.i32]);
|
||||
let p = self.m.ptr(ty);
|
||||
let u = self.m.undef(p);
|
||||
let mut list = Vec::new();
|
||||
for n in 0..self.samplers {
|
||||
let kind = (self.cmp_samplers >> n & 1) as u32;
|
||||
let ops = vec![
|
||||
Some(i32c(&mut self, n)),
|
||||
Some(self.m.md_value(u)),
|
||||
Some(empty),
|
||||
Some(i32c(&mut self, SAMPLER_SPACE)),
|
||||
Some(i32c(&mut self, n)),
|
||||
Some(i32c(&mut self, 1)),
|
||||
// Sampler kind: 1 comparison.
|
||||
Some(i32c(&mut self, kind)),
|
||||
None,
|
||||
];
|
||||
list.push(Some(self.m.md_node(ops)));
|
||||
bindings.push(Binding {
|
||||
kind: 1,
|
||||
space: SAMPLER_SPACE,
|
||||
register: n,
|
||||
dxil_kind: 14,
|
||||
});
|
||||
}
|
||||
samplers = Some(self.m.md_node(list));
|
||||
}
|
||||
resources = Some(self.m.md_node(vec![srvs, uavs, cbvs, samplers]));
|
||||
// PSV0 lists them as the module does: CBVs, samplers, SRVs, UAVs.
|
||||
bindings.sort_by_key(|b| match b.kind {
|
||||
2 => 0,
|
||||
1 => 1,
|
||||
7 => 3,
|
||||
_ => 2,
|
||||
});
|
||||
}
|
||||
if let Some(r) = resources {
|
||||
self.m.named_md("dx.resources", vec![r]);
|
||||
}
|
||||
|
||||
let graphics = self.threads.is_none() || self.mesh.is_some();
|
||||
if graphics {
|
||||
// shortcut: every output is declared to depend on every input; the
|
||||
// exact sets need a dependence pass. Drivers read this state.
|
||||
let scalars = |els: &[SigElement]| {
|
||||
els.iter()
|
||||
.filter_map(|e| e.row.map(|r| r * 4 + u32::from(e.col + e.cols)))
|
||||
.max()
|
||||
.unwrap_or(0)
|
||||
};
|
||||
let (ni, no) = (scalars(&self.inputs), scalars(&self.outputs));
|
||||
let mut view = vec![ni, no];
|
||||
// Mesh shaders have no inputs: then the primitive outputs' count.
|
||||
if self.mesh.is_some() {
|
||||
view.push(scalars(&self.prims));
|
||||
}
|
||||
for _ in 0..ni {
|
||||
for k in 0..no.div_ceil(32) {
|
||||
let bits = (no - 32 * k).min(32);
|
||||
view.push(if bits == 32 {
|
||||
u32::MAX
|
||||
} else {
|
||||
(1 << bits) - 1
|
||||
});
|
||||
}
|
||||
}
|
||||
// A geometry shader lists four streams: the other three have
|
||||
// no outputs.
|
||||
if self.geometry.is_some() {
|
||||
view.extend([0, 0, 0]);
|
||||
}
|
||||
let arr = self.m.array(view.len() as u32, self.t.i32);
|
||||
let elems: Vec<V> = view.iter().map(|&v| self.m.i32(v)).collect();
|
||||
let arr = self.m.aggregate(arr, &elems);
|
||||
let arr = self.m.md_value(arr);
|
||||
let view_node = self.m.md_node(vec![Some(arr)]);
|
||||
self.m.named_md("dx.viewIdState", vec![view_node]);
|
||||
}
|
||||
|
||||
let sigs = if graphics {
|
||||
let ins = self.signature_md(self.inputs.clone());
|
||||
let outs = self.signature_md(self.outputs.clone());
|
||||
let prims = self.signature_md(self.prims.clone());
|
||||
Some(self.m.md_node(vec![ins, outs, prims]))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
// A pixel shader with an SV_StencilRef output (as DXC collects it).
|
||||
if self.pixel && self.outputs.iter().any(|o| o.kind == 20) {
|
||||
self.flags |= flags::STENCIL_REF;
|
||||
}
|
||||
// Entry properties: shader flags (tag 0), geometry state (1),
|
||||
// thread-group size (4), wave size (11).
|
||||
let mut props = Vec::new();
|
||||
if self.flags != 0 {
|
||||
props.push(i32c(&mut self, 0));
|
||||
let i64t = self.m.int(64);
|
||||
let f = self.m.int_const(i64t, self.flags as i64);
|
||||
props.push(self.m.md_value(f));
|
||||
}
|
||||
if let Some(g) = self.geometry {
|
||||
// Input primitive (3: triangles), maximum vertices, stream
|
||||
// mask, output topology (5: triangle strips), instances.
|
||||
props.push(i32c(&mut self, 1));
|
||||
let state = [3, g.max_vertices, 1, 5, 1].map(|n| Some(i32c(&mut self, n)));
|
||||
props.push(self.m.md_node(state.to_vec()));
|
||||
}
|
||||
if let Some(threads) = self.threads {
|
||||
let t = threads.map(|n| Some(i32c(&mut self, n)));
|
||||
let t = self.m.md_node(t.to_vec());
|
||||
match self.mesh {
|
||||
// Mesh state (tag 9): threads, maximum vertices and
|
||||
// primitives, topology, payload bytes.
|
||||
Some(mesh) => {
|
||||
props.push(i32c(&mut self, 9));
|
||||
let state = [
|
||||
mesh.max_vertices,
|
||||
mesh.max_primitives,
|
||||
mesh.topology.into(),
|
||||
0,
|
||||
]
|
||||
.map(|n| Some(i32c(&mut self, n)));
|
||||
let mut node = vec![Some(t)];
|
||||
node.extend(state);
|
||||
props.push(self.m.md_node(node));
|
||||
}
|
||||
None => {
|
||||
props.push(i32c(&mut self, 4));
|
||||
props.push(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(n) = self.wave_size {
|
||||
props.push(i32c(&mut self, 11));
|
||||
let n = Some(i32c(&mut self, n));
|
||||
props.push(self.m.md_node(vec![n]));
|
||||
}
|
||||
let props =
|
||||
(!props.is_empty()).then(|| self.m.md_node(props.into_iter().map(Some).collect()));
|
||||
let main = self.m.md_value(self.main);
|
||||
let name = self.m.md_str("main");
|
||||
let entry = self
|
||||
.m
|
||||
.md_node(vec![Some(main), Some(name), sigs, resources, props]);
|
||||
|
||||
let ident = self.m.md_str("victory");
|
||||
let ident = self.m.md_node(vec![Some(ident)]);
|
||||
self.m.named_md("llvm.ident", vec![ident]);
|
||||
let one = i32c(&mut self, 1);
|
||||
let six = i32c(&mut self, 6);
|
||||
let version = self.m.md_node(vec![Some(one), Some(six)]);
|
||||
self.m.named_md("dx.version", vec![version]);
|
||||
self.m.named_md("dx.valver", vec![version]);
|
||||
// Program kinds: 0 pixel, 1 vertex, 2 geometry, 5 compute, 13 mesh.
|
||||
let (name, kind) = match (self.threads, self.pixel) {
|
||||
_ if self.mesh.is_some() => ("ms", 13u32),
|
||||
_ if self.geometry.is_some() => ("gs", 2),
|
||||
(Some(_), _) => ("cs", 5u32),
|
||||
(None, true) => ("ps", 0),
|
||||
(None, false) => ("vs", 1),
|
||||
};
|
||||
let name = self.m.md_str(name);
|
||||
let sm = self.m.md_node(vec![Some(name), Some(six), Some(six)]);
|
||||
self.m.named_md("dx.shaderModel", vec![sm]);
|
||||
self.m.named_md("dx.entryPoints", vec![entry]);
|
||||
|
||||
let bitcode = self.m.write();
|
||||
super::bitcode::census::note(&self.m, &bitcode);
|
||||
let mut dxil = Vec::with_capacity(24 + bitcode.len());
|
||||
dxil.extend((kind << 16 | 0x66).to_le_bytes());
|
||||
dxil.extend((((24 + bitcode.len()) / 4) as u32).to_le_bytes());
|
||||
dxil.extend(b"DXIL");
|
||||
dxil.extend(0x106u32.to_le_bytes());
|
||||
dxil.extend(16u32.to_le_bytes());
|
||||
dxil.extend((bitcode.len() as u32).to_le_bytes());
|
||||
dxil.extend(&bitcode);
|
||||
|
||||
let mut features = 0u64;
|
||||
if self.flags & flags::DOUBLES != 0 {
|
||||
features |= 0x1;
|
||||
}
|
||||
if self.flags & flags::STENCIL_REF != 0 {
|
||||
features |= 0x200;
|
||||
}
|
||||
if self.flags & flags::TYPED_UAV_LOADS != 0 {
|
||||
features |= 0x800;
|
||||
}
|
||||
if self.flags & flags::ROVS != 0 {
|
||||
features |= 0x1000;
|
||||
}
|
||||
if self.flags & flags::WAVE_OPS != 0 {
|
||||
features |= 0x4000;
|
||||
}
|
||||
if self.flags & flags::INT64 != 0 {
|
||||
features |= 0x8000;
|
||||
}
|
||||
if self.flags & flags::BARYCENTRICS != 0 {
|
||||
features |= 0x2_0000;
|
||||
}
|
||||
if self.flags & flags::RESOURCE_HEAP != 0 {
|
||||
features |= 0x200_0000;
|
||||
}
|
||||
if self.flags & flags::SAMPLER_HEAP != 0 {
|
||||
features |= 0x400_0000;
|
||||
}
|
||||
if self.flags & flags::ATOMIC_TYPED64 != 0 {
|
||||
features |= 0x40_0000;
|
||||
}
|
||||
if self.flags & flags::ATOMIC_HEAP64 != 0 {
|
||||
features |= 0x1000_0000;
|
||||
}
|
||||
let sfi0 = features.to_le_bytes();
|
||||
let isg1 = container::signature(&self.inputs, true);
|
||||
let osg1 = container::signature(&self.outputs, false);
|
||||
let flag = if self.pixel {
|
||||
self.outputs.iter().any(|o| (17..=19).contains(&o.kind))
|
||||
} else {
|
||||
self.outputs.iter().any(|o| o.kind == 3)
|
||||
};
|
||||
let psv0 = container::psv(&Psv {
|
||||
stage: kind as u8,
|
||||
flag: flag && self.threads.is_none(),
|
||||
inputs: &self.inputs,
|
||||
outputs: &self.outputs,
|
||||
prims: &self.prims,
|
||||
mesh: self.mesh.map(|m| (m, self.lds_dwords * 4)),
|
||||
geometry: self.geometry.map(|g| g.max_vertices),
|
||||
bindings: &bindings,
|
||||
threads: self.threads.unwrap_or_default(),
|
||||
wave_size: self.wave_size,
|
||||
});
|
||||
let hash = [0u8; 20];
|
||||
let psg1 = container::signature(&self.prims, false);
|
||||
let mut parts: Vec<(&[u8; 4], &[u8])> =
|
||||
vec![(b"SFI0", &sfi0), (b"ISG1", &isg1), (b"OSG1", &osg1)];
|
||||
if self.mesh.is_some() {
|
||||
parts.push((b"PSG1", &psg1));
|
||||
}
|
||||
parts.extend([(b"PSV0", &psv0[..]), (b"HASH", &hash), (b"DXIL", &dxil)]);
|
||||
container::build(&parts)
|
||||
}
|
||||
|
||||
/// The user-data buffer's annotation carries its size, known only now.
|
||||
fn fix_user_data_size(&mut self, size: u32) {
|
||||
let old = [self.m.i32(13), self.m.i32(u32::MAX)];
|
||||
let old = self.m.aggregate(self.t.props, &old);
|
||||
let new = [self.m.i32(13), self.m.i32(size)];
|
||||
let new = self.m.aggregate(self.t.props, &new);
|
||||
self.m.replace_const(old, new);
|
||||
}
|
||||
|
||||
fn signature_md(&mut self, elements: Vec<SigElement>) -> Option<Md> {
|
||||
if elements.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut list = Vec::new();
|
||||
for (id, e) in elements.iter().enumerate() {
|
||||
let c32 = |s: &mut Self, v: u32| {
|
||||
let c = s.m.i32(v);
|
||||
Some(s.m.md_value(c))
|
||||
};
|
||||
let c8 = |s: &mut Self, v: u8| {
|
||||
let c = s.m.i8(v);
|
||||
Some(s.m.md_value(c))
|
||||
};
|
||||
let idx = c32(self, e.index);
|
||||
let indices = Some(self.m.md_node(vec![idx]));
|
||||
let usage = if e.usage != 0 {
|
||||
let (tag, mask) = (c32(self, 3), c32(self, u32::from(e.usage)));
|
||||
Some(self.m.md_node(vec![tag, mask]))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let ops = vec![
|
||||
c32(self, id as u32),
|
||||
Some(self.m.md_str(&e.name)),
|
||||
c8(self, e.comp),
|
||||
c8(self, e.kind),
|
||||
indices,
|
||||
c8(self, e.interp),
|
||||
c32(self, 1),
|
||||
c8(self, e.cols),
|
||||
c32(self, e.row.unwrap_or(u32::MAX)),
|
||||
c8(self, if e.row.is_some() { e.col } else { u8::MAX }),
|
||||
usage,
|
||||
];
|
||||
list.push(Some(self.m.md_node(ops)));
|
||||
}
|
||||
Some(self.m.md_node(list))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
//! Jump threading for uniform diamonds. One arm can set a flag that fixes
|
||||
//! the join's next branch. Registers recycled on that arm then never reach
|
||||
//! the other successor, even if an ordinary SSA phi joins their values.
|
||||
use crate::gfx10::{Fields, Operand, Valu};
|
||||
use crate::ir::{Exit, Program, Reg, Value};
|
||||
use crate::structure::{Atom, Bool, LaneExit, Structured};
|
||||
use std::collections::HashMap;
|
||||
|
||||
fn plain(v: &Valu) -> bool {
|
||||
v.abs == 0
|
||||
&& v.neg == 0
|
||||
&& v.opsel == 0
|
||||
&& !v.clamp
|
||||
&& v.omod == 0
|
||||
&& v.sdwa.is_none()
|
||||
&& v.dpp.is_none()
|
||||
}
|
||||
|
||||
fn immediate(op: Operand) -> Option<u32> {
|
||||
match op {
|
||||
Operand::Const(c) => crate::resource::inline(c),
|
||||
Operand::Literal(n) => Some(n),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn constant_edges(p: &Program, st: &Structured) -> Vec<(usize, usize, usize)> {
|
||||
let mut constants = HashMap::new();
|
||||
for (b, block) in p.blocks.iter().enumerate() {
|
||||
for (i, inst) in block.insts.iter().enumerate() {
|
||||
if inst.name() == "v_mov_b32"
|
||||
&& st.guards[b][i].is_none()
|
||||
&& let Fields::Valu(v) = &inst.fields
|
||||
&& plain(v)
|
||||
&& let [src] = v.src.as_slice()
|
||||
&& let Some(word) = immediate(*src)
|
||||
&& let [(_, dst)] = inst.writes.as_slice()
|
||||
{
|
||||
constants.insert(*dst, word);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut edges = Vec::new();
|
||||
for (join, block) in p.blocks.iter().enumerate() {
|
||||
let LaneExit::Branch {
|
||||
when,
|
||||
taken,
|
||||
not_taken,
|
||||
} = st.exits[join]
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if when == Bool::TRUE || when == Bool::FALSE {
|
||||
continue;
|
||||
}
|
||||
// Keep memory accesses and wave operations at their original
|
||||
// reconvergence point. Only duplicate scalar ALU and comparisons.
|
||||
if !block.insts.iter().all(|i| match &i.fields {
|
||||
Fields::Sop { .. } => true,
|
||||
Fields::Sopp { .. } => i.name().starts_with("s_cbranch_"),
|
||||
Fields::Valu(_) => i.name().starts_with("v_cmp_"),
|
||||
_ => false,
|
||||
}) {
|
||||
continue;
|
||||
}
|
||||
let [a, b] = block.preds.as_slice() else {
|
||||
continue;
|
||||
};
|
||||
// A triangle has a direct edge from the fork to the join. A full
|
||||
// diamond has an unconditional jump at the end of each arm.
|
||||
let arm_from = |arm: usize| match p.blocks[arm].preds.as_slice() {
|
||||
&[fork] if p.blocks[arm].exit == Exit::Jump(join) => Some(fork),
|
||||
_ => None,
|
||||
};
|
||||
let fork = match (arm_from(*a), arm_from(*b)) {
|
||||
(Some(f), Some(g)) if f == g => f,
|
||||
(_, Some(f)) if f == *a => f,
|
||||
(Some(f), _) if f == *b => f,
|
||||
_ => continue,
|
||||
};
|
||||
if fork == join || a == b {
|
||||
continue;
|
||||
}
|
||||
let LaneExit::Branch { when: entry, .. } = st.exits[fork] else {
|
||||
continue;
|
||||
};
|
||||
if !st
|
||||
.bools
|
||||
.support(entry)
|
||||
.iter()
|
||||
.all(|a| matches!(a, Atom::Uniform(_)))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
for (edge, &pred) in block.preds.iter().enumerate() {
|
||||
let value = |v: Value| {
|
||||
let input = block
|
||||
.phis
|
||||
.iter()
|
||||
.find(|p| p.value == v)
|
||||
.map_or(v, |p| p.args[edge]);
|
||||
constants.get(&input).copied()
|
||||
};
|
||||
// Restrict the branch's decision diagram to known comparisons.
|
||||
// Unknown tests stop the proof. Keep the original join for the
|
||||
// other arm, which may still go either way.
|
||||
let mut cond = when;
|
||||
while let Some((Atom::Lane(id), lo, hi)) = st.bools.node(cond) {
|
||||
let Some(inst) = block
|
||||
.insts
|
||||
.iter()
|
||||
.find(|i| i.writes.iter().any(|&(_, v)| v == id))
|
||||
else {
|
||||
break;
|
||||
};
|
||||
let Fields::Valu(v) = &inst.fields else { break };
|
||||
let [left, right] = v.src.as_slice() else {
|
||||
break;
|
||||
};
|
||||
let operand = |op| match op {
|
||||
Operand::Vector { reg, dwords: 1 } => value(inst.read(Reg::V(reg))?),
|
||||
_ => immediate(op),
|
||||
};
|
||||
let (Some(x), Some(y)) = (operand(*left), operand(*right)) else {
|
||||
break;
|
||||
};
|
||||
if !plain(v) {
|
||||
break;
|
||||
}
|
||||
let yes = match inst.name() {
|
||||
"v_cmp_eq_u32" | "v_cmp_eq_i32" => x == y,
|
||||
"v_cmp_ne_u32" | "v_cmp_ne_i32" => x != y,
|
||||
_ => break,
|
||||
};
|
||||
cond = if yes { hi } else { lo };
|
||||
}
|
||||
if cond == Bool::TRUE || cond == Bool::FALSE {
|
||||
edges.push((
|
||||
pred,
|
||||
join,
|
||||
if cond == Bool::TRUE { taken } else { not_taken },
|
||||
));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
edges
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::ir;
|
||||
use crate::structure;
|
||||
|
||||
// s8 initially holds a descriptor address. One arm overwrites it with
|
||||
// a buffer load and sets v1. Only that arm can use s8 as the stored value.
|
||||
const WORDS: [u32; 19] = [
|
||||
0xbe810380, // s1 = 0 (table address high)
|
||||
0xf4080200, 0xfa000000, // load SRV into s[8:11]
|
||||
0xf4080300, 0xfa000020, // load UAV into s[12:15]
|
||||
0x7e020280, // v1 = 0
|
||||
0xbf068002, 0xbf850003, // if s2 == 0, jump to join
|
||||
0xf4200204, 0xfa00000c, // s8 = buffer.Load(12)
|
||||
0x7e020281, // v1 = 1
|
||||
0x7d840280, 0xbf870002, // join: if v1 == 0, jump to constant
|
||||
0x7e060208, 0xbf820001, // v3 = s8, jump to store
|
||||
0x7e060293, // constant: v3 = 19
|
||||
0xe0700000, 0x80030300, // store v3 at byte 0
|
||||
0xbf810000, // end
|
||||
];
|
||||
|
||||
fn program(words: &[u32]) -> Program {
|
||||
ir::build(
|
||||
&words
|
||||
.iter()
|
||||
.flat_map(|w| w.to_le_bytes())
|
||||
.collect::<Vec<_>>(),
|
||||
false,
|
||||
4,
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_buffer_load_reaches_the_numeric_read() {
|
||||
let p = program(&WORDS);
|
||||
let st = structure::structure(&p).unwrap();
|
||||
let edges = constant_edges(&p, &st);
|
||||
assert_eq!(edges, [(0, 2, 4)]);
|
||||
let p = ir::thread_edges(&p, &edges).unwrap();
|
||||
let load = &p.blocks[1].insts[0];
|
||||
assert_eq!(p.blocks[3].insts[0].read(Reg::S(8)), load.write(Reg::S(8)));
|
||||
assert_eq!(
|
||||
p.blocks[0].exit,
|
||||
Exit::Branch {
|
||||
taken: 6,
|
||||
not_taken: 1
|
||||
}
|
||||
);
|
||||
assert_eq!(p.blocks[6].exit, Exit::Jump(4));
|
||||
assert_eq!(p.blocks[6].insts.len(), p.blocks[2].insts.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn leaves_unknown_flags_and_divergent_forks_alone() {
|
||||
let mut words = WORDS;
|
||||
words[5] = 0x7e020202; // v1 = s2
|
||||
words[10] = 0x7e020203; // v1 = s3
|
||||
let p = program(&words);
|
||||
assert!(constant_edges(&p, &structure::structure(&p).unwrap()).is_empty());
|
||||
let mut words = WORDS;
|
||||
words[6] = 0x7d840080; // compare 0 with lane-dependent v0
|
||||
words[7] = 0xbf870003; // branch on VCC
|
||||
let p = program(&words);
|
||||
assert!(constant_edges(&p, &structure::structure(&p).unwrap()).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
//! The DXIL validator in `dxil.dll` (`IDxcValidator`), for tests and the
|
||||
//! offline batch. Translated shaders do not need it: they carry the
|
||||
//! container hash we compute (`container::hash`).
|
||||
//!
|
||||
//! The DLL is found at `VICTORY_DXIL` if set, else the newest Windows SDK's
|
||||
//! `bin\<version>\x64\dxil.dll`, else wherever `LoadLibrary` finds it.
|
||||
|
||||
use std::ffi::c_void;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryW};
|
||||
|
||||
type Hresult = i32;
|
||||
|
||||
#[repr(C)]
|
||||
struct Guid(u32, u16, u16, [u8; 8]);
|
||||
|
||||
const CLSID_DXC_VALIDATOR: Guid = Guid(
|
||||
0x8ca3_e215,
|
||||
0xf728,
|
||||
0x4cf3,
|
||||
[0x8c, 0xdd, 0x88, 0xaf, 0x91, 0x75, 0x87, 0xa1],
|
||||
);
|
||||
const IID_IDXC_VALIDATOR: Guid = Guid(
|
||||
0xa6e8_2bd2,
|
||||
0x1fd7,
|
||||
0x4826,
|
||||
[0x98, 0x11, 0x28, 0x57, 0xe7, 0x97, 0xf4, 0x9a],
|
||||
);
|
||||
/// `DxcValidatorFlags_InPlaceEdit`: sign the container we pass.
|
||||
const IN_PLACE_EDIT: u32 = 1;
|
||||
|
||||
type CreateInstance =
|
||||
unsafe extern "system" fn(*const Guid, *const Guid, *mut *mut c_void) -> Hresult;
|
||||
|
||||
/// COM object: a pointer to a table of method pointers.
|
||||
type Object = *mut *const usize;
|
||||
|
||||
unsafe fn method<F: Copy>(obj: Object, slot: usize) -> F {
|
||||
// SAFETY: the caller names a slot of the object's interface.
|
||||
unsafe { std::mem::transmute_copy(&*(*obj).add(slot)) }
|
||||
}
|
||||
|
||||
unsafe fn release(obj: Object) {
|
||||
if !obj.is_null() {
|
||||
// SAFETY: slot 2 of every COM interface is Release.
|
||||
unsafe { method::<unsafe extern "system" fn(Object) -> u32>(obj, 2)(obj) };
|
||||
}
|
||||
}
|
||||
|
||||
/// An `IDxcBlob` over our bytes: QueryInterface, AddRef, Release,
|
||||
/// GetBufferPointer, GetBufferSize. Lives on the caller's stack.
|
||||
#[repr(C)]
|
||||
struct Blob {
|
||||
vtable: *const BlobVtable,
|
||||
data: *mut u8,
|
||||
len: usize,
|
||||
}
|
||||
|
||||
/// IUnknown and IDxcBlob, as raw GUID bytes.
|
||||
const IUNKNOWN: [u8; 16] = [0, 0, 0, 0, 0, 0, 0, 0, 0xc0, 0, 0, 0, 0, 0, 0, 0x46];
|
||||
const IDXC_BLOB: [u8; 16] = [
|
||||
0x08, 0xfb, 0xa5, 0x8b, 0x95, 0x51, 0xe2, 0x40, 0xac, 0x58, 0x0d, 0x98, 0x9c, 0x3a, 0x01, 0x02,
|
||||
];
|
||||
|
||||
unsafe extern "system" fn blob_qi(
|
||||
this: *mut Blob,
|
||||
iid: *const [u8; 16],
|
||||
out: *mut *mut c_void,
|
||||
) -> Hresult {
|
||||
// SAFETY: the validator passes valid pointers.
|
||||
unsafe {
|
||||
if *iid == IUNKNOWN || *iid == IDXC_BLOB {
|
||||
*out = this.cast();
|
||||
0
|
||||
} else {
|
||||
*out = std::ptr::null_mut();
|
||||
0x8000_4002_u32 as i32 // E_NOINTERFACE
|
||||
}
|
||||
}
|
||||
}
|
||||
unsafe extern "system" fn blob_ref(_: *mut Blob) -> u32 {
|
||||
1
|
||||
}
|
||||
unsafe extern "system" fn blob_ptr(this: *mut Blob) -> *mut u8 {
|
||||
// SAFETY: `this` is our blob.
|
||||
unsafe { (*this).data }
|
||||
}
|
||||
unsafe extern "system" fn blob_len(this: *mut Blob) -> usize {
|
||||
// SAFETY: `this` is our blob.
|
||||
unsafe { (*this).len }
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct BlobVtable {
|
||||
qi: unsafe extern "system" fn(*mut Blob, *const [u8; 16], *mut *mut c_void) -> Hresult,
|
||||
add_ref: unsafe extern "system" fn(*mut Blob) -> u32,
|
||||
release: unsafe extern "system" fn(*mut Blob) -> u32,
|
||||
ptr: unsafe extern "system" fn(*mut Blob) -> *mut u8,
|
||||
len: unsafe extern "system" fn(*mut Blob) -> usize,
|
||||
}
|
||||
|
||||
static BLOB_VTABLE: BlobVtable = BlobVtable {
|
||||
qi: blob_qi,
|
||||
add_ref: blob_ref,
|
||||
release: blob_ref,
|
||||
ptr: blob_ptr,
|
||||
len: blob_len,
|
||||
};
|
||||
|
||||
pub struct Validator {
|
||||
object: Object,
|
||||
}
|
||||
|
||||
// SAFETY: the validator object is free-threaded (DXC's validator has no
|
||||
// thread affinity); calls are serialised by `&mut self`.
|
||||
unsafe impl Send for Validator {}
|
||||
|
||||
impl Validator {
|
||||
/// Where `dxil.dll` is looked for.
|
||||
pub fn default_path() -> Option<PathBuf> {
|
||||
if let Some(p) = std::env::var_os("VICTORY_DXIL") {
|
||||
return Some(p.into());
|
||||
}
|
||||
let kits = PathBuf::from(r"C:\Program Files (x86)\Windows Kits\10\bin");
|
||||
let mut versions: Vec<PathBuf> = std::fs::read_dir(&kits)
|
||||
.ok()?
|
||||
.filter_map(Result::ok)
|
||||
.map(|e| e.path().join(r"x64\dxil.dll"))
|
||||
.filter(|p| p.exists())
|
||||
.collect();
|
||||
versions.sort();
|
||||
versions.pop()
|
||||
}
|
||||
|
||||
/// Loads `path`'s validator (or `dxil.dll` from the DLL search path).
|
||||
pub fn load(path: Option<&std::path::Path>) -> Result<Self, String> {
|
||||
let name: Vec<u16> = path
|
||||
.map_or_else(|| "dxil.dll".into(), |p| p.as_os_str().to_owned())
|
||||
.to_string_lossy()
|
||||
.encode_utf16()
|
||||
.chain([0])
|
||||
.collect();
|
||||
// SAFETY: plain Win32 calls with a NUL-terminated name.
|
||||
unsafe {
|
||||
let module = LoadLibraryW(name.as_ptr());
|
||||
if module.is_null() {
|
||||
return Err(format!("cannot load {}", String::from_utf16_lossy(&name)));
|
||||
}
|
||||
let create = GetProcAddress(module, c"DxcCreateInstance".as_ptr().cast())
|
||||
.ok_or("dxil.dll lacks DxcCreateInstance")?;
|
||||
let create: CreateInstance = std::mem::transmute(create);
|
||||
let mut object = std::ptr::null_mut();
|
||||
let hr = create(&CLSID_DXC_VALIDATOR, &IID_IDXC_VALIDATOR, &mut object);
|
||||
if hr < 0 || object.is_null() {
|
||||
return Err(format!("DxcCreateInstance(validator) failed: {hr:#x}"));
|
||||
}
|
||||
Ok(Validator {
|
||||
object: object.cast(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Validates `container` and signs it in place; the error text if it
|
||||
/// is rejected.
|
||||
pub fn validate(&mut self, container: &mut [u8]) -> Result<(), String> {
|
||||
let mut blob = Blob {
|
||||
vtable: &BLOB_VTABLE,
|
||||
data: container.as_mut_ptr(),
|
||||
len: container.len(),
|
||||
};
|
||||
// SAFETY: IDxcValidator::Validate (slot 3) with our blob; then
|
||||
// IDxcOperationResult GetStatus (3) and GetErrorBuffer (5), and
|
||||
// IDxcBlob GetBufferPointer (3) / GetBufferSize (4).
|
||||
unsafe {
|
||||
let mut result: Object = std::ptr::null_mut();
|
||||
let validate: unsafe extern "system" fn(
|
||||
Object,
|
||||
*mut Blob,
|
||||
u32,
|
||||
*mut Object,
|
||||
) -> Hresult = method(self.object, 3);
|
||||
let hr = validate(self.object, &mut blob, IN_PLACE_EDIT, &mut result);
|
||||
if hr < 0 || result.is_null() {
|
||||
return Err(format!("Validate failed: {hr:#x}"));
|
||||
}
|
||||
let mut status = 0;
|
||||
let get_status: unsafe extern "system" fn(Object, *mut Hresult) -> Hresult =
|
||||
method(result, 3);
|
||||
get_status(result, &mut status);
|
||||
let mut text = String::new();
|
||||
if status < 0 {
|
||||
let mut errors: Object = std::ptr::null_mut();
|
||||
let get_errors: unsafe extern "system" fn(Object, *mut Object) -> Hresult =
|
||||
method(result, 5);
|
||||
if get_errors(result, &mut errors) >= 0 && !errors.is_null() {
|
||||
let ptr: unsafe extern "system" fn(Object) -> *const u8 = method(errors, 3);
|
||||
let len: unsafe extern "system" fn(Object) -> usize = method(errors, 4);
|
||||
let bytes = std::slice::from_raw_parts(ptr(errors), len(errors));
|
||||
text = String::from_utf8_lossy(bytes)
|
||||
.trim_end_matches('\0')
|
||||
.trim()
|
||||
.into();
|
||||
release(errors);
|
||||
}
|
||||
if text.is_empty() {
|
||||
text = format!("rejected ({status:#x})");
|
||||
}
|
||||
}
|
||||
release(result);
|
||||
if status < 0 { Err(text) } else { Ok(()) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Validator {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: we own one reference.
|
||||
unsafe { release(self.object) };
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,435 @@
|
||||
//! End-to-end tests of waterfall loops over per-lane descriptors: the
|
||||
//! synthetic GFX10 programs of `resource::tests` lowered to DXIL, validated
|
||||
//! by `dxil.dll` when present, and run on the host GPU and WARP, each lane
|
||||
//! reading the resource its own descriptor names.
|
||||
|
||||
use windows::Win32::Graphics::Direct3D12::*;
|
||||
|
||||
use super::host::{Dispatch, Host, Root, Stride, View};
|
||||
use super::{HostShader, lower, validator};
|
||||
use crate::native::{
|
||||
ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource,
|
||||
};
|
||||
use crate::{io, ir, resource, structure};
|
||||
|
||||
/// Lowers a wave32 compute program of 32 threads with the table of views at
|
||||
/// s0 (textures, or with `buffers` structured buffers of dwords, at entries
|
||||
/// 0 and 1, a raw UAV at entry 2) and the table of samplers at s1.
|
||||
fn build(words: &[u32], buffers: bool) -> HostShader {
|
||||
let table = |user_data: u8| RootParam {
|
||||
root: RootType::Table,
|
||||
table_offset_dwords: 0,
|
||||
sgprs: 1,
|
||||
base_register: 0,
|
||||
user_data,
|
||||
slot: user_data,
|
||||
};
|
||||
let range = |kind, table_offset_dwords, dwords, stride, user_data| UsedResource {
|
||||
kind,
|
||||
root: RootType::Table,
|
||||
table_offset_dwords,
|
||||
lower_bound: 0,
|
||||
stride,
|
||||
dwords,
|
||||
user_data,
|
||||
slot: user_data,
|
||||
};
|
||||
let views = if buffers {
|
||||
range(ResourceType::Srv, 0, 4, 4, 0)
|
||||
} else {
|
||||
range(ResourceType::Srv, 0, 8, 0, 0)
|
||||
};
|
||||
let native = NativeProgram {
|
||||
stage: HwStage::Cs,
|
||||
wave64: false,
|
||||
vgprs: 32,
|
||||
layout: vec![table(0), table(1)],
|
||||
used: vec![
|
||||
views,
|
||||
range(ResourceType::Uav, 16, 4, 0, 0),
|
||||
range(ResourceType::Sampler, 0, 4, 0, 1),
|
||||
],
|
||||
io: StageIo::Cs(ComputeIo {
|
||||
rsrc2: 2 << 1,
|
||||
threads: [32, 1, 1],
|
||||
}),
|
||||
code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
|
||||
};
|
||||
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
|
||||
let st = structure::structure(&p).expect("structure");
|
||||
let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("track");
|
||||
let io = io::raise(&p, &native).expect("io::raise");
|
||||
let lowered = lower::lower(&lower::Parts {
|
||||
native: &native,
|
||||
p: &p,
|
||||
st: &st,
|
||||
io: &io,
|
||||
res: &res,
|
||||
inputs: Vec::new(),
|
||||
outputs: Vec::new(),
|
||||
prims: Vec::new(),
|
||||
mesh_stride: 0,
|
||||
})
|
||||
.expect("lower");
|
||||
// One access with each lane's own heap index, no wave operation.
|
||||
assert_eq!(lowered.nonuniform_handles, 1);
|
||||
assert!(!lowered.wave_ops);
|
||||
let shader = HostShader {
|
||||
stage: HwStage::Cs,
|
||||
dxil: lowered.dxil,
|
||||
user_data: lowered.user_data,
|
||||
samplers: lowered.samplers,
|
||||
static_samplers: Vec::new(),
|
||||
root_cbvs: lowered.root_cbvs,
|
||||
root_srvs: lowered.root_srvs,
|
||||
root_uavs: lowered.root_uavs,
|
||||
root_indexed_views: Vec::new(),
|
||||
};
|
||||
if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
|
||||
v.validate(&mut shader.dxil.clone())
|
||||
.expect("DXIL validation failed");
|
||||
} else {
|
||||
eprintln!("no dxil.dll; validation skipped");
|
||||
}
|
||||
shader
|
||||
}
|
||||
|
||||
/// Runs `shader` with `views` at heap indices 0.. (the UAV last) on the
|
||||
/// hardware GPU and on WARP (each skipped without a device) and returns,
|
||||
/// per one that ran, the UAV's 32 dwords.
|
||||
fn run(shader: &HostShader, views: &[View]) -> Vec<(&'static str, Vec<u32>)> {
|
||||
let samplers = [D3D12_SAMPLER_DESC {
|
||||
Filter: D3D12_FILTER_MIN_MAG_MIP_POINT,
|
||||
AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
|
||||
AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
|
||||
AddressW: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
|
||||
MaxAnisotropy: 1,
|
||||
MaxLOD: f32::MAX,
|
||||
..Default::default()
|
||||
}];
|
||||
let mut out = Vec::new();
|
||||
// One GPU test at a time, with the VALU tests: in parallel on the
|
||||
// hardware adapter and WARP the test process sometimes died of an
|
||||
// access violation (7 of 24 runs of these four tests).
|
||||
let _one = super::valu_tests::ONE_AT_A_TIME
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner());
|
||||
for (label, warp) in [("hardware", false), ("warp", true)] {
|
||||
let Ok(host) = Host::new(warp) else {
|
||||
eprintln!("no SM 6.6 {label} device; skipped");
|
||||
continue;
|
||||
};
|
||||
let (root, pso) = match host.compute_pipeline(shader) {
|
||||
Ok(p) => p,
|
||||
Err(e) => panic!("{label}: compute_pipeline failed: {e}"),
|
||||
};
|
||||
// Both tables start at heap index 0.
|
||||
let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize];
|
||||
for u in &shader.user_data {
|
||||
assert_eq!(u.root, RootType::Table, "{u:?}");
|
||||
ud[u.index as usize] = 0;
|
||||
}
|
||||
let words = host
|
||||
.dispatch(
|
||||
&root,
|
||||
&pso,
|
||||
&Dispatch {
|
||||
roots: vec![(0, Root::Constants(ud))],
|
||||
views,
|
||||
samplers: &samplers,
|
||||
groups: [1, 1, 1],
|
||||
},
|
||||
)
|
||||
.unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}"));
|
||||
out.push((label, words[0].clone()));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The red channel each lane sampled from two 1x1 textures, red 1.0 at
|
||||
/// heap index 0 and 2.0 at 1.
|
||||
fn sampled(shader: &HostShader) -> Vec<(&'static str, Vec<f32>)> {
|
||||
let first = [[1.0f32, 0.0, 0.0, 1.0]];
|
||||
let second = [[2.0f32, 0.0, 0.0, 1.0]];
|
||||
let views = [
|
||||
View::Texture(1, 1, &first),
|
||||
View::Texture(1, 1, &second),
|
||||
View::RawUav(32),
|
||||
];
|
||||
run(shader, &views)
|
||||
.into_iter()
|
||||
.map(|(label, words)| (label, words.into_iter().map(f32::from_bits).collect()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lanes_sample_the_texture_their_if_else_arm_chose() {
|
||||
use crate::resource::tests::WATERFALL_JOINED_WAVE32;
|
||||
let shader = build(WATERFALL_JOINED_WAVE32, false);
|
||||
for (label, red) in sampled(&shader) {
|
||||
// Lanes below 16 took the first texture, the others the second.
|
||||
let want: Vec<f32> = (0..32).map(|l| if l < 16 { 1.0 } else { 2.0 }).collect();
|
||||
assert_eq!(red, want, "{label}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lanes_sample_the_texture_their_arm_loaded_or_picked() {
|
||||
use crate::resource::tests::WATERFALL_JOINED_MIXED_WAVE32;
|
||||
let shader = build(WATERFALL_JOINED_MIXED_WAVE32, false);
|
||||
for (label, red) in sampled(&shader) {
|
||||
// Lanes below 16 loaded entry (lane & 1); of the others, lanes
|
||||
// below 24 picked the first, the rest the second.
|
||||
let want: Vec<f32> = (0..32)
|
||||
.map(|l| match l {
|
||||
0..16 => [1.0, 2.0][l & 1],
|
||||
16..24 => 1.0,
|
||||
_ => 2.0,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(red, want, "{label}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lanes_load_from_the_buffer_their_nested_arms_chose() {
|
||||
use crate::resource::tests::WATERFALL_JOINED_BUFFER_WAVE32;
|
||||
let shader = build(WATERFALL_JOINED_BUFFER_WAVE32, true);
|
||||
let first: Vec<u32> = (0..32).map(|i| 100 + i).collect();
|
||||
let second: Vec<u32> = (0..32).map(|i| 200 + i).collect();
|
||||
let views = [
|
||||
View::Buffer {
|
||||
data: &first,
|
||||
stride: Stride::Structured(4),
|
||||
},
|
||||
View::Buffer {
|
||||
data: &second,
|
||||
stride: Stride::Structured(4),
|
||||
},
|
||||
View::RawUav(32),
|
||||
];
|
||||
for (label, got) in run(&shader, &views) {
|
||||
// Dword `lane` of the first buffer below 16, of the second from 16
|
||||
// to 23; lanes from 24 on load and store nothing.
|
||||
let want: Vec<u32> = (0..32)
|
||||
.map(|l| match l {
|
||||
0..16 => 100 + l,
|
||||
16..24 => 200 + l,
|
||||
_ => 0,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(got, want, "{label}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lanes_sample_the_entry_their_offset_names_in_the_console_waterfall() {
|
||||
use crate::resource::tests::WATERFALL_INDEXED_WAVE32;
|
||||
let shader = build(WATERFALL_INDEXED_WAVE32, false);
|
||||
let results = sampled(&shader);
|
||||
assert!(!results.is_empty());
|
||||
for (label, red) in results {
|
||||
// Even lanes hold entry 0's offset, odd lanes entry 1's.
|
||||
let want: Vec<f32> = (0..32).map(|l| [1.0, 2.0][l & 1]).collect();
|
||||
assert_eq!(red, want, "{label}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lanes_sample_their_own_texture_in_a_waterfall_narrowed_by_v_cmpx() {
|
||||
use crate::resource::tests::cmpx_waterfall;
|
||||
// Lanes below 16 hold the first descriptor, the others the second.
|
||||
let want: Vec<f32> = (0..32).map(|l| if l < 16 { 1.0 } else { 2.0 }).collect();
|
||||
for folded in [false, true] {
|
||||
let shader = build(&cmpx_waterfall(false, folded), false);
|
||||
let results = sampled(&shader);
|
||||
assert!(!results.is_empty());
|
||||
for (label, red) in results {
|
||||
assert_eq!(red, want, "{label}, folded {folded}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn immediate_sampler_chosen_by_control_flow() {
|
||||
let s_mov_lit = |dst: u8, lit: u32| [0xBE80_03FF | (dst as u32) << 16, lit];
|
||||
let s_mov_zero = |dst: u8| 0xBE80_0380 | (dst as u32) << 16;
|
||||
let s_load_x8 = |dst: u8, base: u8| [0x3D << 26 | 0x03 << 18 | (dst as u32) << 6 | (base as u32 >> 1), 125 << 25];
|
||||
let s_load_x4_off = |dst: u8, base: u8, off: u32| [0x3D << 26 | 0x02 << 18 | (dst as u32) << 6 | (base as u32 >> 1), 125 << 25 | off];
|
||||
// image_sample_lz v4, v[2:3], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D
|
||||
let image_sample_lz: [u32; 2] = [
|
||||
0x3C << 26 | 0x21 << 18 | 1 << 8 | 1 << 3, // dmask=1, dim=2D(1)
|
||||
(16u32 >> 2) << 21 | (8u32 >> 2) << 16 | 4 << 8 | 2,
|
||||
];
|
||||
// buffer_store_dword v4, off, s[20:23], 0
|
||||
let buf_store: [u32; 2] = [0x38 << 26 | 0x1C << 18, 0x80 << 24 | (20u32 >> 2) << 16 | 4 << 8];
|
||||
|
||||
// Two distinct valid immediate sampler descriptors (different wrap/filter bits).
|
||||
let samp_a: [u32; 4] = [0x0000_0092, 0x00C0_0000, 0x1850_0000, 0];
|
||||
let samp_b: [u32; 4] = [0x0000_0092, 0x00C0_0000, 0x1850_0001, 0];
|
||||
|
||||
for (case_name, alt) in [("same_sampler", samp_a), ("different_samplers", samp_b)] {
|
||||
let mut words = Vec::new();
|
||||
// s[2:3] = view table base (s0, 0).
|
||||
words.push(0xBE80_0300 | (2 << 16)); // s_mov_b32 s2, s0
|
||||
words.push(s_mov_zero(3));
|
||||
words.extend_from_slice(&s_load_x8(8, 2)); // s[8:15] = texture SRV (offset 0)
|
||||
words.extend_from_slice(&s_load_x4_off(20, 2, 64)); // s[20:23] = raw UAV (offset 16 dwords = 64B)
|
||||
// v2 = 0.5, v3 = 0.5 (sample coordinates).
|
||||
words.push(0x7E00_02F0 | (2 << 17)); // v_mov_b32 v2, 0.5
|
||||
words.push(0x7E00_02F0 | (3 << 17)); // v_mov_b32 v3, 0.5
|
||||
// s_cmp_eq_u32 s1, 0; s_cbranch_scc0 else_arm
|
||||
words.push(0xBF00_8001); // s_cmp_eq_u32 s1, 0 (const 128)
|
||||
let br_else = words.len();
|
||||
words.push(0); // placeholder s_cbranch_scc0
|
||||
// then arm: load samp_a into s[16:19]
|
||||
for (i, &w) in samp_a.iter().enumerate() {
|
||||
words.extend_from_slice(&s_mov_lit(16 + i as u8, w));
|
||||
}
|
||||
let br_join = words.len();
|
||||
words.push(0); // placeholder s_branch
|
||||
let else_pc = words.len();
|
||||
// else arm: load alt into s[16:19]
|
||||
for (i, &w) in alt.iter().enumerate() {
|
||||
words.extend_from_slice(&s_mov_lit(16 + i as u8, w));
|
||||
}
|
||||
let join_pc = words.len();
|
||||
words[br_else] = 0xBF84_0000 | ((else_pc - br_else - 1) as u32 & 0xFFFF);
|
||||
words[br_join] = 0xBF82_0000 | ((join_pc - br_join - 1) as u32 & 0xFFFF);
|
||||
words.extend_from_slice(&image_sample_lz);
|
||||
words.extend_from_slice(&buf_store);
|
||||
words.push(0xBF81_0000); // s_endpgm
|
||||
|
||||
let native = NativeProgram {
|
||||
stage: HwStage::Cs,
|
||||
wave64: false,
|
||||
vgprs: 8,
|
||||
layout: vec![
|
||||
RootParam {
|
||||
root: RootType::Table,
|
||||
table_offset_dwords: 0,
|
||||
sgprs: 1,
|
||||
base_register: 0,
|
||||
user_data: 0,
|
||||
slot: 0,
|
||||
},
|
||||
RootParam {
|
||||
root: RootType::Constants,
|
||||
table_offset_dwords: 0,
|
||||
sgprs: 1,
|
||||
base_register: 0,
|
||||
user_data: 1,
|
||||
slot: 1,
|
||||
},
|
||||
],
|
||||
used: vec![
|
||||
UsedResource {
|
||||
kind: ResourceType::Srv,
|
||||
root: RootType::Table,
|
||||
table_offset_dwords: 0,
|
||||
lower_bound: 0,
|
||||
stride: 0,
|
||||
dwords: 8,
|
||||
user_data: 0,
|
||||
slot: 0,
|
||||
},
|
||||
UsedResource {
|
||||
kind: ResourceType::Uav,
|
||||
root: RootType::Table,
|
||||
table_offset_dwords: 16,
|
||||
lower_bound: 0,
|
||||
stride: 0,
|
||||
dwords: 4,
|
||||
user_data: 0,
|
||||
slot: 0,
|
||||
},
|
||||
],
|
||||
io: StageIo::Cs(ComputeIo {
|
||||
rsrc2: 2 << 1,
|
||||
threads: [1, 1, 1],
|
||||
}),
|
||||
code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
|
||||
};
|
||||
|
||||
let p = ir::build(&native.code, false, native.vgprs).expect("ir::build");
|
||||
let st = structure::structure(&p).expect("structure");
|
||||
let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("track");
|
||||
let io = io::raise(&p, &native).expect("io::raise");
|
||||
let lowered = lower::lower(&lower::Parts {
|
||||
native: &native,
|
||||
p: &p,
|
||||
st: &st,
|
||||
io: &io,
|
||||
res: &res,
|
||||
inputs: Vec::new(),
|
||||
outputs: Vec::new(),
|
||||
prims: Vec::new(),
|
||||
mesh_stride: 0,
|
||||
})
|
||||
.unwrap_or_else(|e| panic!("{case_name}: lower failed: {e}"));
|
||||
|
||||
let static_samplers = lowered
|
||||
.samplers
|
||||
.iter()
|
||||
.map(|&w| super::StaticSampler::from_words(w))
|
||||
.collect();
|
||||
let shader = HostShader {
|
||||
stage: HwStage::Cs,
|
||||
dxil: lowered.dxil,
|
||||
user_data: lowered.user_data,
|
||||
samplers: lowered.samplers,
|
||||
static_samplers,
|
||||
root_cbvs: lowered.root_cbvs,
|
||||
root_srvs: lowered.root_srvs,
|
||||
root_uavs: lowered.root_uavs,
|
||||
root_indexed_views: Vec::new(),
|
||||
};
|
||||
if let Ok(mut v) =
|
||||
validator::Validator::load(validator::Validator::default_path().as_deref())
|
||||
{
|
||||
let mut copy = shader.dxil.clone();
|
||||
v.validate(&mut copy).expect("DXIL validation failed");
|
||||
}
|
||||
|
||||
let _one = super::valu_tests::ONE_AT_A_TIME
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner());
|
||||
for (label, warp) in [("hardware", false), ("warp", true)] {
|
||||
let Ok(host) = Host::new(warp) else {
|
||||
continue;
|
||||
};
|
||||
let (root, pso) = host
|
||||
.compute_pipeline(&shader)
|
||||
.unwrap_or_else(|e| panic!("{case_name}/{label}: compute_pipeline failed: {e}"));
|
||||
for branch in [0u32, 1u32] {
|
||||
let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize];
|
||||
for u in &shader.user_data {
|
||||
ud[u.index as usize] = match (u.root, u.slot) {
|
||||
(RootType::Table, 0) => 0,
|
||||
(RootType::Constants, 1) => branch,
|
||||
other => panic!("unexpected user data {other:?}"),
|
||||
};
|
||||
}
|
||||
let texels = [[1.0f32, 0.0, 0.0, 1.0]];
|
||||
let out = host
|
||||
.dispatch(
|
||||
&root,
|
||||
&pso,
|
||||
&Dispatch {
|
||||
roots: vec![(0, Root::Constants(ud))],
|
||||
views: &[
|
||||
View::Texture(1, 1, &texels),
|
||||
View::Texture(1, 1, &texels),
|
||||
View::RawUav(1),
|
||||
],
|
||||
samplers: &[],
|
||||
groups: [1, 1, 1],
|
||||
},
|
||||
)
|
||||
.unwrap_or_else(|e| panic!("{case_name}/{label}: dispatch failed: {e}"));
|
||||
let got = f32::from_bits(out[0][0]);
|
||||
assert_eq!(got, 1.0, "{case_name}/{label} branch={branch}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,549 @@
|
||||
//! A console wave64 compute program on a host of 32-lane waves: a wave reduction inside a
|
||||
//! per-lane branch, with that branch taken wave-wide ([`crate::structure::structure_wide`])
|
||||
//! so that the two host waves can exchange their halves inside it. Lowered, validated by
|
||||
//! `dxil.dll` when present, and run on the host GPU when it takes waves of 32.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use super::host::{Dispatch, Host, Root, View};
|
||||
use super::{HostShader, lower, validator};
|
||||
use crate::native::{
|
||||
ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource,
|
||||
};
|
||||
use crate::{ShaderError, io, ir, resource, structure};
|
||||
|
||||
const S_ENDPGM: u32 = 0xBF81_0000;
|
||||
|
||||
/// 64 threads in one console wave. Each thread t holds the bit `1 << (t >> 1)`; the threads
|
||||
/// below s0 (a root constant) OR theirs over the wave inside `if (t < s0) { ... }` and store
|
||||
/// the result to dword 0 of the raw UAV.
|
||||
/// `skip`: the branch past the body when no thread is below s0: `s_cbranch_execz`, or
|
||||
/// `s_cbranch_scc0` on the SCC `s_and_saveexec` sets ("some lane is left").
|
||||
fn program(skip: u32) -> NativeProgram {
|
||||
let mut words = vec![
|
||||
0x7E0A_0281, // v_mov_b32 v5, 1
|
||||
0x2C0C_0081, // v_lshrrev_b32 v6, 1, v0
|
||||
0x340E_0B06, // v_lshlrev_b32 v7, v6, v5
|
||||
0x7D88_0000, // v_cmp_gt_u32 vcc, s0, v0
|
||||
0xBE8C_246A, // s_and_saveexec_b64 s[12:13], vcc
|
||||
skip | 23, // the branch to the restore of EXEC
|
||||
];
|
||||
words.extend_from_slice(&super::wave::WAVE_OR_V7_TO_S7);
|
||||
words.extend_from_slice(&[
|
||||
0x7E00_0207, // v_mov_b32 v0, s7
|
||||
0x38 << 26 | 0x1C << 18,
|
||||
0x80 << 24 | 2 << 16, // buffer_store_dword v0, off, s[8:11], 0
|
||||
0xBEFE_040C, // s_mov_b64 exec, s[12:13]
|
||||
]);
|
||||
native(&words)
|
||||
}
|
||||
|
||||
/// A wave64 compute program of 64 threads (one console wave; the thread index in v0) with 4
|
||||
/// root constants in s0..s3 and a raw UAV's descriptor in s[8:11], then `body`.
|
||||
fn native(body: &[u32]) -> NativeProgram {
|
||||
native_of(body, true, 64)
|
||||
}
|
||||
|
||||
/// The same for a console of 32-lane waves when `wave64` is not set, with `threads` threads.
|
||||
fn native_of(body: &[u32], wave64: bool, threads: u32) -> NativeProgram {
|
||||
let mut words = vec![
|
||||
0xBE85_0380, // s_mov_b32 s5, 0
|
||||
0x3D << 26 | 0x02 << 18 | 8 << 6 | 2,
|
||||
125 << 25, // s_load_dwordx4 s[8:11], s[4:5], 0
|
||||
];
|
||||
words.extend_from_slice(body);
|
||||
words.push(S_ENDPGM);
|
||||
NativeProgram {
|
||||
stage: HwStage::Cs,
|
||||
wave64,
|
||||
vgprs: 16,
|
||||
layout: vec![
|
||||
RootParam {
|
||||
root: RootType::Constants,
|
||||
table_offset_dwords: 0,
|
||||
sgprs: 4,
|
||||
base_register: 0,
|
||||
user_data: 0,
|
||||
slot: 0,
|
||||
},
|
||||
RootParam {
|
||||
root: RootType::Table,
|
||||
table_offset_dwords: 0,
|
||||
sgprs: 1,
|
||||
base_register: 0,
|
||||
user_data: 4,
|
||||
slot: 1,
|
||||
},
|
||||
],
|
||||
used: vec![UsedResource {
|
||||
kind: ResourceType::Uav,
|
||||
root: RootType::Table,
|
||||
table_offset_dwords: 0,
|
||||
lower_bound: 0,
|
||||
stride: 0,
|
||||
dwords: 4,
|
||||
user_data: 4,
|
||||
slot: 1,
|
||||
}],
|
||||
io: StageIo::Cs(ComputeIo {
|
||||
rsrc2: 5 << 1, // 5 user SGPRs: s0..s4
|
||||
threads: [threads, 1, 1],
|
||||
}),
|
||||
code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// `program()` for a host of 32-lane waves, with the branches closing `wide` taken wave-wide.
|
||||
fn lowered(native: &NativeProgram, p: &ir::Program, wide: &HashSet<usize>) -> Result<HostShader, ShaderError> {
|
||||
lowered_on(native, p, wide, 32)
|
||||
}
|
||||
|
||||
/// [`lowered`] for a host whose waves have at most `host_wave` lanes.
|
||||
fn lowered_on(
|
||||
native: &NativeProgram,
|
||||
p: &ir::Program,
|
||||
wide: &HashSet<usize>,
|
||||
host_wave: u32,
|
||||
) -> Result<HostShader, ShaderError> {
|
||||
let st = structure::structure_wide(p, wide).expect("structure");
|
||||
let res = resource::track(p, &native.layout, native.stage, Some(&st)).expect("resource::track");
|
||||
let io = io::raise(p, native).expect("io::raise");
|
||||
let was = lower::TEST_HOST_WAVE.replace(Some(host_wave));
|
||||
let lowered = lower::lower(&lower::Parts {
|
||||
native,
|
||||
p,
|
||||
st: &st,
|
||||
io: &io,
|
||||
res: &res,
|
||||
inputs: Vec::new(),
|
||||
outputs: Vec::new(),
|
||||
prims: Vec::new(),
|
||||
mesh_stride: 0,
|
||||
});
|
||||
lower::TEST_HOST_WAVE.set(was);
|
||||
let lowered = lowered?;
|
||||
Ok(HostShader {
|
||||
stage: HwStage::Cs,
|
||||
dxil: lowered.dxil,
|
||||
user_data: lowered.user_data,
|
||||
samplers: lowered.samplers,
|
||||
static_samplers: Vec::new(),
|
||||
root_cbvs: lowered.root_cbvs,
|
||||
root_srvs: lowered.root_srvs,
|
||||
root_uavs: lowered.root_uavs,
|
||||
root_indexed_views: res.root_indexed_views,
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sum_of_halves_over_the_wave_is_the_consoles_tree_bit_for_bit() {
|
||||
// thread t holds the 16-bit float with bits 0x3C00 + 37 t (1.0 and up, with odd
|
||||
// mantissas, so that additions round); all of them store the wave's sum
|
||||
let mut words = vec![
|
||||
0x340C_0085, // v_lshlrev_b32 v6, 5, v0
|
||||
0x340E_0082, // v_lshlrev_b32 v7, 2, v0
|
||||
0x4A0E_0F06, // v_add_nc_u32 v7, v6, v7
|
||||
0x4A0E_0F00, // v_add_nc_u32 v7, v0, v7
|
||||
0x4A0E_0EFF,
|
||||
0x0000_3C00, // v_add_nc_u32 v7, 0x3c00, v7
|
||||
];
|
||||
// (the wave OR's words with v_add_f16 for v_or_b32: opcode 50 for 28)
|
||||
words.extend(super::wave::WAVE_OR_V7_TO_S7.iter().map(|&w| if w >> 25 == 28 { w & 0x01FF_FFFF | 50 << 25 } else { w }));
|
||||
words.extend_from_slice(&[
|
||||
0x7E00_0207, // v_mov_b32 v0, s7
|
||||
0x38 << 26 | 0x1C << 18,
|
||||
0x80 << 24 | 2 << 16, // buffer_store_dword v0, off, s[8:11], 0
|
||||
]);
|
||||
let native = native(&words);
|
||||
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
|
||||
assert_eq!(p.blocks.iter().flat_map(|b| &b.insts).filter(|i| i.name() == "v_add_f16").count(), 6);
|
||||
let shader = lowered(&native, &p, &HashSet::new()).expect("lower");
|
||||
if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
|
||||
let mut copy = shader.dxil.clone();
|
||||
v.validate(&mut copy).expect("DXIL validation failed");
|
||||
}
|
||||
// the console's sum: lanes 2k and 2k+1, then pairs, ... each addition rounded to 16 bits
|
||||
// (to nearest, ties to even); values here are normal numbers
|
||||
let wide = |h: u16| f32::from_bits((u32::from(h >> 10) + 112) << 23 | u32::from(h & 0x3FF) << 13);
|
||||
let narrow = |f: f32| {
|
||||
let b = f.to_bits();
|
||||
let h = ((b >> 23) - 112) << 10 | (b >> 13 & 0x3FF);
|
||||
let rest = b & 0x1FFF;
|
||||
(h + u32::from(rest > 0x1000 || rest == 0x1000 && h & 1 == 1)) as u16
|
||||
};
|
||||
let add = |a: u16, b: u16| narrow(wide(a) + wide(b));
|
||||
let terms: Vec<u16> = (0..64u16).map(|t| 0x3C00 + 37 * t).collect();
|
||||
let mut tree = terms.clone();
|
||||
while tree.len() > 1 {
|
||||
tree = tree.chunks(2).map(|c| add(c[0], c[1])).collect();
|
||||
}
|
||||
let in_a_row = terms.iter().copied().reduce(add).unwrap();
|
||||
assert_ne!(tree[0], in_a_row, "these terms tell the tree from another order");
|
||||
let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let Ok(host) = Host::new(false) else {
|
||||
eprintln!("no SM 6.6 hardware device; not run");
|
||||
return;
|
||||
};
|
||||
let (root, pso) = match host.compute_pipeline(&shader) {
|
||||
Ok(x) => x,
|
||||
Err(e) => {
|
||||
eprintln!("the hardware device does not take this program (waves of 32?): {e}; not run");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let ud = vec![0u32; shader.user_data_dwords().max(1) as usize];
|
||||
let out = host
|
||||
.dispatch(
|
||||
&root,
|
||||
&pso,
|
||||
&Dispatch {
|
||||
roots: vec![(0, Root::Constants(ud))],
|
||||
views: &[View::RawUav(1)],
|
||||
samplers: &[],
|
||||
groups: [1, 1, 1],
|
||||
},
|
||||
)
|
||||
.unwrap_or_else(|e| panic!("dispatch failed: {e}"));
|
||||
// (the high half is lane 0's term's: zero)
|
||||
assert_eq!(out[0][0], u32::from(tree[0]), "tree {:#x}, in a row {in_a_row:#x}", tree[0]);
|
||||
eprintln!("ran on the hardware device: the sum {:#x} of the console's tree", tree[0]);
|
||||
}
|
||||
|
||||
/// The console's 16-bit wave sum where the lanes at or past s0 have left the program (a
|
||||
/// thread past the end of the data): on the console they add +0, and after each step of the
|
||||
/// tree they hold their run's partial sum all the same. On a host of 64-lane waves (AMD) the
|
||||
/// lanes that are here read each partner run's sum from a lane of it that is here.
|
||||
#[test]
|
||||
fn a_sum_of_halves_where_lanes_have_left_is_the_consoles_tree_bit_for_bit() {
|
||||
let mut words = vec![
|
||||
0x7DA8_0000, // v_cmpx_gt_u32 exec, s0, v0: the lanes below s0 stay
|
||||
0, // s_cbranch_execz to the end (filled in below)
|
||||
0x340C_0085, // v_lshlrev_b32 v6, 5, v0
|
||||
0x340E_0082, // v_lshlrev_b32 v7, 2, v0
|
||||
0x4A0E_0F06, // v_add_nc_u32 v7, v6, v7
|
||||
0x4A0E_0F00, // v_add_nc_u32 v7, v0, v7
|
||||
0x4A0E_0EFF,
|
||||
0x0000_3C00, // v_add_nc_u32 v7, 0x3c00, v7
|
||||
];
|
||||
words.extend(super::wave::WAVE_OR_V7_TO_S7.iter().map(|&w| if w >> 25 == 28 { w & 0x01FF_FFFF | 50 << 25 } else { w }));
|
||||
words.extend_from_slice(&[
|
||||
0x7E00_0207, // v_mov_b32 v0, s7
|
||||
0x38 << 26 | 0x1C << 18,
|
||||
0x80 << 24 | 2 << 16, // buffer_store_dword v0, off, s[8:11], 0
|
||||
]);
|
||||
// past every word after it, to the program's end
|
||||
words[1] = 0xBF88_0000 | (words.len() as u32 - 2);
|
||||
let native = native(&words);
|
||||
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
|
||||
// BetterXen correction (research/shader-wave-semantics): this program is lowered for a host
|
||||
// of 64-lane waves. A device whose waves are narrower cannot run that lowering: its lanes 32
|
||||
// and up do not exist, and the observed result was 0 instead of the tree. Such a device
|
||||
// must be offered the lowering for its own width instead, which the recompiler refuses for
|
||||
// this program ("a wave sum of 16-bit floats where not every lane runs"): the test then
|
||||
// asserts that refusal, which is the correct behaviour, rather than reporting a failure
|
||||
// or silently skipping.
|
||||
if let Some(w) = Host::hardware().ok().and_then(|h| h.wave_lane_count_max()).filter(|&w| w < 64) {
|
||||
let refused = lowered_on(&native, &p, &HashSet::new(), w);
|
||||
assert!(
|
||||
matches!(&refused, Err(ShaderError::Unsupported { what, .. }) if what.contains("16-bit floats where not every lane runs")),
|
||||
"a {w}-lane device must be refused this program, got {:?}",
|
||||
refused.as_ref().map(|_| "a shader")
|
||||
);
|
||||
eprintln!("device waves are {w} lanes; refused for that width as expected; not run on the device");
|
||||
return;
|
||||
}
|
||||
let shader = lowered_on(&native, &p, &HashSet::new(), 64).expect("lower");
|
||||
if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
|
||||
let mut copy = shader.dxil.clone();
|
||||
v.validate(&mut copy).expect("DXIL validation failed");
|
||||
}
|
||||
let wide = |h: u16| {
|
||||
if h == 0 {
|
||||
0.0
|
||||
} else {
|
||||
f32::from_bits((u32::from(h >> 10) + 112) << 23 | u32::from(h & 0x3FF) << 13)
|
||||
}
|
||||
};
|
||||
let narrow = |f: f32| {
|
||||
if f == 0.0 {
|
||||
return 0;
|
||||
}
|
||||
let b = f.to_bits();
|
||||
let h = ((b >> 23) - 112) << 10 | (b >> 13 & 0x3FF);
|
||||
let rest = b & 0x1FFF;
|
||||
(h + u32::from(rest > 0x1000 || rest == 0x1000 && h & 1 == 1)) as u16
|
||||
};
|
||||
let add = |a: u16, b: u16| narrow(wide(a) + wide(b));
|
||||
let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut ran = false;
|
||||
for stay in [64u32, 63, 40, 33, 32, 17, 5, 1] {
|
||||
let terms: Vec<u16> = (0..64u32)
|
||||
.map(|t| if t < stay { (0x3C00 + 37 * t) as u16 } else { 0 })
|
||||
.collect();
|
||||
let mut tree = terms.clone();
|
||||
while tree.len() > 1 {
|
||||
tree = tree.chunks(2).map(|c| add(c[0], c[1])).collect();
|
||||
}
|
||||
let Some(got) = on_the_card(&shader, [stay, 0]) else {
|
||||
return;
|
||||
};
|
||||
ran = true;
|
||||
// (the high half is lane 0's term's: zero)
|
||||
assert_eq!(got, u32::from(tree[0]), "{stay} lanes stay: got {got:#x}, the console's tree {:#x}", tree[0]);
|
||||
}
|
||||
if ran {
|
||||
eprintln!("ran on the hardware device: the console's tree with lanes gone, in every case");
|
||||
}
|
||||
}
|
||||
|
||||
/// One `v_add_f16` whose exact result lies between two halves: 1 + 3/1024 (0x3C03) plus 2
|
||||
/// (0x4000) is 3 + 1.5 steps of that range, which the console rounds up to 0x4202. The
|
||||
/// host's `f32tof16` may give 0x4201 (toward zero); with `VICTORY_F16_NEAREST=1` the
|
||||
/// translation gives the console's whatever the host does.
|
||||
#[test]
|
||||
fn a_16_bit_sum_rounds_to_nearest_when_asked_to() {
|
||||
let words = [
|
||||
0x7E0E_02FF,
|
||||
0x0000_3C03, // v_mov_b32 v7, 0x3c03
|
||||
0x7E0C_02FF,
|
||||
0x0000_4000, // v_mov_b32 v6, 0x4000
|
||||
0x6400_0D07, // v_add_f16 v0, v7, v6
|
||||
0x38 << 26 | 0x1C << 18,
|
||||
0x80 << 24 | 2 << 16, // buffer_store_dword v0, off, s[8:11], 0
|
||||
];
|
||||
let native = native(&words);
|
||||
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
|
||||
assert!(p.blocks.iter().flat_map(|b| &b.insts).any(|i| i.name() == "v_add_f16"));
|
||||
let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
|
||||
for nearest in [false, true] {
|
||||
let was = lower::TEST_F16_NEAREST.replace(Some(nearest));
|
||||
let shader = lowered(&native, &p, &HashSet::new());
|
||||
lower::TEST_F16_NEAREST.set(was);
|
||||
let shader = shader.expect("lower");
|
||||
if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
|
||||
let mut copy = shader.dxil.clone();
|
||||
v.validate(&mut copy).expect("DXIL validation failed");
|
||||
}
|
||||
let Ok(host) = Host::new(false) else {
|
||||
eprintln!("no SM 6.6 hardware device; not run");
|
||||
return;
|
||||
};
|
||||
let Ok((root, pso)) = host.compute_pipeline(&shader) else {
|
||||
eprintln!("the hardware device does not take this program; not run");
|
||||
return;
|
||||
};
|
||||
let ud = vec![0u32; shader.user_data_dwords().max(1) as usize];
|
||||
let out = host
|
||||
.dispatch(
|
||||
&root,
|
||||
&pso,
|
||||
&Dispatch {
|
||||
roots: vec![(0, Root::Constants(ud))],
|
||||
views: &[View::RawUav(1)],
|
||||
samplers: &[],
|
||||
groups: [1, 1, 1],
|
||||
},
|
||||
)
|
||||
.unwrap_or_else(|e| panic!("dispatch failed: {e}"));
|
||||
let got = out[0][0] & 0xFFFF;
|
||||
eprintln!("v_add_f16 0x3c03 + 0x4000 on the hardware device, nearest {nearest}: {got:#x}");
|
||||
if nearest {
|
||||
assert_eq!(got, 0x4202);
|
||||
} else {
|
||||
assert!(got == 0x4201 || got == 0x4202, "{got:#x}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wave_or_inside_a_lane_branch_needs_the_branch_wave_wide() {
|
||||
for (skip, name) in [(0xBF88_0000, "s_cbranch_execz"), (0xBF84_0000, "s_cbranch_scc0")] {
|
||||
a_wave_or_inside(skip, name);
|
||||
}
|
||||
}
|
||||
|
||||
fn a_wave_or_inside(skip: u32, name: &str) {
|
||||
let native = program(skip);
|
||||
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
|
||||
let branch = (0..p.blocks.len())
|
||||
.find(|&b| p.blocks[b].insts.last().is_some_and(|i| i.name() == name))
|
||||
.expect("the branch");
|
||||
// per lane, the two host waves cannot meet inside the branch
|
||||
lower::take_needs();
|
||||
let per_lane = lowered(&native, &p, &HashSet::new());
|
||||
assert!(
|
||||
matches!(&per_lane, Err(ShaderError::Unsupported { what, .. }) if *what == "a wave reduction where not every lane runs"),
|
||||
"{:?}",
|
||||
per_lane.err()
|
||||
);
|
||||
// ... and the lowering names the block, around which that branch is the one to widen
|
||||
let needs = lower::take_needs();
|
||||
let st = structure::structure(&p).expect("structure");
|
||||
assert_eq!(lower::branches_around(&st, &needs), Some(vec![branch]));
|
||||
// (taken, past the body, when every lane's bit is clear)
|
||||
assert_eq!(st.wave_any[branch], Some(false));
|
||||
// wave-wide, every lane runs the reduction (EXEC stays a guard on what it does there)
|
||||
let wide = HashSet::from([branch]);
|
||||
let st = structure::structure_wide(&p, &wide).expect("structure");
|
||||
let inside = match p.blocks[branch].exit {
|
||||
ir::Exit::Branch { not_taken, .. } => not_taken,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
assert!(st.guards[inside].iter().any(Option::is_some));
|
||||
let shader = lowered(&native, &p, &wide).expect("lower");
|
||||
if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
|
||||
let mut copy = shader.dxil.clone();
|
||||
v.validate(&mut copy).expect("DXIL validation failed");
|
||||
}
|
||||
// On a GPU that takes waves of 32 (two host waves for the console's one): the OR is of
|
||||
// both halves, whichever half's lanes take the branch.
|
||||
let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let Ok(host) = Host::new(false) else {
|
||||
eprintln!("no SM 6.6 hardware device; not run");
|
||||
return;
|
||||
};
|
||||
let (root, pso) = match host.compute_pipeline(&shader) {
|
||||
Ok(x) => x,
|
||||
Err(e) => {
|
||||
eprintln!("the hardware device does not take this program (waves of 32?): {e}; not run");
|
||||
return;
|
||||
}
|
||||
};
|
||||
// (threads below s0 take the branch; thread t gives bit t >> 1)
|
||||
for (below, expected) in [(64u32, u32::MAX), (40, 0x000F_FFFF), (33, 0x0001_FFFF), (10, 0x1F), (1, 1)] {
|
||||
let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize];
|
||||
for u in &shader.user_data {
|
||||
if let (RootType::Constants, 0, 0) = (u.root, u.slot, u.dword) {
|
||||
ud[u.index as usize] = below;
|
||||
}
|
||||
}
|
||||
let out = host
|
||||
.dispatch(
|
||||
&root,
|
||||
&pso,
|
||||
&Dispatch {
|
||||
roots: vec![(0, Root::Constants(ud))],
|
||||
views: &[View::RawUav(1)],
|
||||
samplers: &[],
|
||||
groups: [1, 1, 1],
|
||||
},
|
||||
)
|
||||
.unwrap_or_else(|e| panic!("dispatch failed: {e}"));
|
||||
assert_eq!(out[0][0], expected, "{name}: {below} threads in the branch");
|
||||
}
|
||||
eprintln!("ran on the hardware device ({name}): the OR of both halves in every case");
|
||||
}
|
||||
|
||||
/// Runs `shader` on the hardware device with the root constants `s0`, `s1` and gives dword 0
|
||||
/// of the UAV; None (and a line) without a device that takes it.
|
||||
fn on_the_card(shader: &HostShader, constants: [u32; 2]) -> Option<u32> {
|
||||
let Ok(host) = Host::new(false) else {
|
||||
eprintln!("no SM 6.6 hardware device; not run");
|
||||
return None;
|
||||
};
|
||||
let Ok((root, pso)) = host.compute_pipeline(shader) else {
|
||||
eprintln!("the hardware device does not take this program; not run");
|
||||
return None;
|
||||
};
|
||||
let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize];
|
||||
for u in &shader.user_data {
|
||||
if let (RootType::Constants, 0, d @ 0..=1) = (u.root, u.slot, u.dword) {
|
||||
ud[u.index as usize] = constants[d as usize];
|
||||
}
|
||||
}
|
||||
let out = host
|
||||
.dispatch(
|
||||
&root,
|
||||
&pso,
|
||||
&Dispatch {
|
||||
roots: vec![(0, Root::Constants(ud))],
|
||||
views: &[View::RawUav(1)],
|
||||
samplers: &[],
|
||||
groups: [1, 1, 1],
|
||||
},
|
||||
)
|
||||
.unwrap_or_else(|e| panic!("dispatch failed: {e}"));
|
||||
Some(out[0][0])
|
||||
}
|
||||
|
||||
/// A 32-lane console wave. A register holds a lane mask on one path (the lanes below s0)
|
||||
/// and a number on the other, and is read as a number after the join, as the trace programs
|
||||
/// keep their lanes' masks and their node numbers on one stack
|
||||
/// (`deferred_tiled:CS_LaserLightShadowRaytracing`, s46 at 0x104, 0x75c and 0x188). The
|
||||
/// mask arrives as the ballot of its lanes.
|
||||
#[test]
|
||||
fn a_lane_mask_joined_with_a_number_is_read_as_the_number_it_is() {
|
||||
let words = [
|
||||
0x7D88_0000, // v_cmp_gt_u32 vcc_lo, s0, v0
|
||||
0xBE94_036A, // s_mov_b32 s20, vcc_lo
|
||||
0xBF06_8001, // s_cmp_eq_u32 s1, 0
|
||||
0xBF85_0001, // s_cbranch_scc1 over the next
|
||||
0xBE94_0385, // s_mov_b32 s20, 5
|
||||
0x7E00_0214, // v_mov_b32 v0, s20
|
||||
0x38 << 26 | 0x1C << 18,
|
||||
0x80 << 24 | 2 << 16, // buffer_store_dword v0, off, s[8:11], 0
|
||||
];
|
||||
let native = native_of(&words, false, 32);
|
||||
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
|
||||
let shader = lowered(&native, &p, &HashSet::new()).expect("lower");
|
||||
if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
|
||||
let mut copy = shader.dxil.clone();
|
||||
v.validate(&mut copy).expect("DXIL validation failed");
|
||||
}
|
||||
let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
|
||||
for (below, other, expected) in [(32u32, 0u32, u32::MAX), (10, 0, 0x3FF), (0, 0, 0), (10, 1, 5)] {
|
||||
let Some(got) = on_the_card(&shader, [below, other]) else { return };
|
||||
assert_eq!(got, expected, "{below} lanes in the mask, s1 = {other}");
|
||||
}
|
||||
eprintln!("ran on the hardware device: the mask's bits, or the number");
|
||||
}
|
||||
|
||||
/// A 32-lane console wave. `if (t < s0) { ... SCC = (s1 == 7) }` and a branch on SCC after
|
||||
/// the join: the skip brings the SCC of `s_and_saveexec` ("some lane is left") along
|
||||
/// (`rtdirectionalshadows:CS_RTShadowTrace32HQ_TiledFarOnly`, 0x360-0x39c). On the console
|
||||
/// the skip is taken by the wave, so with some lane inside every lane sees the inner test.
|
||||
/// A lane that skipped on its own would see "some lane is left" instead: refused per lane,
|
||||
/// right with the branch taken wave-wide. Lane 31 stores what it saw.
|
||||
#[test]
|
||||
fn scc_of_a_mask_operation_joined_with_a_scalar_test_needs_the_skip_wave_wide() {
|
||||
let words = [
|
||||
0x7D88_0000, // v_cmp_gt_u32 vcc_lo, s0, v0
|
||||
0xBE8D_3C6A, // s_and_saveexec_b32 s13, vcc_lo
|
||||
0xBF88_0001, // s_cbranch_execz over the next
|
||||
0xBF06_8701, // s_cmp_eq_u32 s1, 7
|
||||
0xBEFE_030D, // s_mov_b32 exec_lo, s13
|
||||
0xBF85_0002, // s_cbranch_scc1 to "seven"
|
||||
0x7E0A_0281, // v_mov_b32 v5, 1
|
||||
0xBF82_0001, // s_branch over the next
|
||||
0x7E0A_0282, // seven: v_mov_b32 v5, 2
|
||||
0x7DA4_009F, // v_cmpx_eq_u32 exec_lo, 31, v0
|
||||
0x38 << 26 | 0x1C << 18,
|
||||
0x80 << 24 | 2 << 16 | 5 << 8, // buffer_store_dword v5, off, s[8:11], 0
|
||||
];
|
||||
let native = native_of(&words, false, 32);
|
||||
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
|
||||
let branch = (0..p.blocks.len())
|
||||
.find(|&b| p.blocks[b].insts.last().is_some_and(|i| i.name() == "s_cbranch_execz"))
|
||||
.expect("the skip");
|
||||
lower::take_needs();
|
||||
let per_lane = lowered(&native, &p, &HashSet::new());
|
||||
assert!(
|
||||
matches!(&per_lane, Err(ShaderError::Unsupported { what, .. }) if *what == "a lane mask read as data"),
|
||||
"{:?}",
|
||||
per_lane.err()
|
||||
);
|
||||
let st = structure::structure(&p).expect("structure");
|
||||
assert_eq!(lower::branches_around(&st, &lower::take_needs()), Some(vec![branch]));
|
||||
let shader = lowered(&native, &p, &HashSet::from([branch])).expect("lower");
|
||||
if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
|
||||
let mut copy = shader.dxil.clone();
|
||||
v.validate(&mut copy).expect("DXIL validation failed");
|
||||
}
|
||||
let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
|
||||
// (lanes below s0 inside, s1) -> what lane 31 stores: 2 if SCC was set at the branch
|
||||
for (below, s1, expected) in [(0u32, 7u32, 1u32), (10, 7, 2), (10, 3, 1), (32, 3, 1), (32, 7, 2)] {
|
||||
let Some(got) = on_the_card(&shader, [below, s1]) else { return };
|
||||
assert_eq!(got, expected, "{below} lanes inside, s1 = {s1}");
|
||||
}
|
||||
eprintln!("ran on the hardware device: the inner test's SCC for every lane once some lane is inside");
|
||||
}
|
||||
@@ -0,0 +1,815 @@
|
||||
//! Operand fields of GFX10 instructions, by encoding.
|
||||
//!
|
||||
//! Layouts follow AMD's RDNA ISA reference. Register ranges carry their size
|
||||
//! in dwords, which depends on the opcode (read from its name) and, for lane
|
||||
//! masks (VCC, EXEC, compare results), on the wave size.
|
||||
|
||||
use super::{Encoding, Instruction};
|
||||
|
||||
/// A source or destination of an instruction.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Operand {
|
||||
/// Scalar registers by operand code: 0-105 `s0`-`s105`, 106/107
|
||||
/// `vcc_lo`/`vcc_hi`, 108-123 `ttmp0`-`ttmp15`, 124 `m0`, 125 `null`,
|
||||
/// 126/127 `exec_lo`/`exec_hi`. The decoder gives no code above 127; the
|
||||
/// IR names scalars parked in VGPR lanes by the codes from 128 up
|
||||
/// (`crate::ir::PARKED`).
|
||||
Scalar {
|
||||
code: u8,
|
||||
dwords: u8,
|
||||
},
|
||||
Vector {
|
||||
reg: u8,
|
||||
dwords: u8,
|
||||
},
|
||||
/// Inline constant or read-only special source, by operand code
|
||||
/// (128-192: 0-64, 193-208: -1 to -16, 240-248: floats, 251-254: vccz,
|
||||
/// execz, scc, lds_direct).
|
||||
Const(u8),
|
||||
/// The 32-bit literal that follows the instruction.
|
||||
Literal(u32),
|
||||
/// Interpolation attribute and channel (0-3 = x-w); `high` selects the
|
||||
/// upper f16 half.
|
||||
Attr {
|
||||
index: u8,
|
||||
chan: u8,
|
||||
high: bool,
|
||||
},
|
||||
}
|
||||
|
||||
/// Operand code of `null` (no register; reads as 0).
|
||||
pub const NULL: u8 = 125;
|
||||
const VCC: u8 = 106;
|
||||
const EXEC: u8 = 126;
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct Cache {
|
||||
pub glc: bool,
|
||||
pub slc: bool,
|
||||
pub dlc: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Fields {
|
||||
/// SOP1, SOP2, SOPC, SOPK; `imm` is SOPK's 16-bit immediate.
|
||||
Sop {
|
||||
dst: Option<Operand>,
|
||||
src: Vec<Operand>,
|
||||
imm: Option<u16>,
|
||||
},
|
||||
/// The 16-bit immediate: branch offset in dwords, wait counts, message...
|
||||
Sopp {
|
||||
imm: u16,
|
||||
},
|
||||
Smem {
|
||||
data: Option<Operand>,
|
||||
base: Operand,
|
||||
/// Signed byte offset, added to `soffset`.
|
||||
offset: i32,
|
||||
soffset: Operand,
|
||||
cache: Cache,
|
||||
},
|
||||
Valu(Valu),
|
||||
Vintrp {
|
||||
dst: Operand,
|
||||
/// The i/j VGPR, or for `v_interp_mov_f32` the parameter (0 `p10`,
|
||||
/// 1 `p20`, 2 `p0`) as [`Operand::Const`].
|
||||
src: Operand,
|
||||
attr: Operand,
|
||||
},
|
||||
Ds {
|
||||
dst: Option<Operand>,
|
||||
addr: Option<Operand>,
|
||||
data: Vec<Operand>,
|
||||
offset0: u8,
|
||||
offset1: u8,
|
||||
gds: bool,
|
||||
},
|
||||
/// MUBUF, and MTBUF with `format` set.
|
||||
Buffer {
|
||||
/// Loaded, stored, or the atomic operand (and result with `glc`).
|
||||
data: Option<Operand>,
|
||||
addr: Operand,
|
||||
rsrc: Operand,
|
||||
soffset: Operand,
|
||||
offset: u16,
|
||||
offen: bool,
|
||||
idxen: bool,
|
||||
format: Option<u8>,
|
||||
lds: bool,
|
||||
tfe: bool,
|
||||
cache: Cache,
|
||||
},
|
||||
Image {
|
||||
data: Operand,
|
||||
/// One range, or one VGPR per address with the NSA form.
|
||||
addr: Vec<Operand>,
|
||||
rsrc: Operand,
|
||||
sampler: Option<Operand>,
|
||||
dmask: u8,
|
||||
dim: u8,
|
||||
unorm: bool,
|
||||
r128: bool,
|
||||
a16: bool,
|
||||
d16: bool,
|
||||
tfe: bool,
|
||||
lwe: bool,
|
||||
cache: Cache,
|
||||
},
|
||||
/// FLAT, GLOBAL and SCRATCH.
|
||||
Flat {
|
||||
dst: Option<Operand>,
|
||||
addr: Option<Operand>,
|
||||
data: Option<Operand>,
|
||||
saddr: Option<Operand>,
|
||||
offset: i16,
|
||||
lds: bool,
|
||||
cache: Cache,
|
||||
},
|
||||
Exp {
|
||||
target: u8,
|
||||
/// Per channel; `None` when disabled.
|
||||
src: [Option<Operand>; 4],
|
||||
compr: bool,
|
||||
done: bool,
|
||||
vm: bool,
|
||||
},
|
||||
}
|
||||
|
||||
/// VOP1, VOP2, VOPC, VOP3 and VOP3P, with their SDWA and DPP forms.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct Valu {
|
||||
/// A VGPR range, an SGPR (`v_readlane_b32`...) or a lane mask (compares).
|
||||
pub dst: Option<Operand>,
|
||||
/// Carry-out or the second result of VOP3B (`v_add_co_u32`, `v_div_scale_f32`...).
|
||||
pub carry: Option<Operand>,
|
||||
/// In operand order, including the implicit VCC of VOP2 `v_cndmask_b32`
|
||||
/// and carry-in, and the literal of `v_madmk`/`v_madak` forms.
|
||||
pub src: Vec<Operand>,
|
||||
/// Bit i applies to `src[i]`. For VOP3P, `neg` is the low half's.
|
||||
pub neg: u8,
|
||||
pub abs: u8,
|
||||
/// VOP3P: negate the high half (`v_fma_mix*`: absolute value).
|
||||
pub neg_hi: u8,
|
||||
/// VOP3: bit 3 is the destination. VOP3P with `opsel_hi`: the halves used.
|
||||
pub opsel: u8,
|
||||
pub opsel_hi: u8,
|
||||
pub clamp: bool,
|
||||
/// Output modifier: 1 ×2, 2 ×4, 3 ÷2.
|
||||
pub omod: u8,
|
||||
pub sdwa: Option<Sdwa>,
|
||||
pub dpp: Option<Dpp>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Sdwa {
|
||||
/// Selects: 0-3 byte, 4-5 word, 6 dword. Compares have no `dst_sel`.
|
||||
pub dst_sel: u8,
|
||||
/// 0 pad with zeros, 1 sign-extend, 2 preserve.
|
||||
pub dst_unused: u8,
|
||||
pub src_sel: [u8; 2],
|
||||
/// Bit i sign-extends `src[i]`.
|
||||
pub sext: u8,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Dpp {
|
||||
/// DPP16: `ctrl` is the 9-bit permutation (quad_perm, row shifts...).
|
||||
Row {
|
||||
ctrl: u16,
|
||||
row_mask: u8,
|
||||
bank_mask: u8,
|
||||
bound_ctrl: bool,
|
||||
fi: bool,
|
||||
},
|
||||
/// DPP8: eight 3-bit lane selects.
|
||||
Lanes { sel: u32, fi: bool },
|
||||
}
|
||||
|
||||
impl Instruction {
|
||||
/// Decodes the operand fields. `wave64` sizes lane masks.
|
||||
pub fn fields(&self, wave64: bool) -> Fields {
|
||||
let name = self.name().unwrap_or("");
|
||||
let w = |i: usize| self.words.get(i).copied().unwrap_or(0);
|
||||
let (w0, w1) = (w(0), w(1));
|
||||
let bit = |word: u32, n: u32| word >> n & 1 != 0;
|
||||
let cache = |glc, slc, dlc| Cache { glc, slc, dlc };
|
||||
match self.encoding {
|
||||
Encoding::Sop2 | Encoding::Sop1 | Encoding::Sopc => {
|
||||
let (dst, src0, src1) = salu_dwords(name);
|
||||
let sdst = scalar((w0 >> 16 & 0x7F) as u8, dst);
|
||||
let ssrc = |shift: u32, dwords| source(w0 >> shift & 0xFF, dwords, w1);
|
||||
let (dst, src) = match self.encoding {
|
||||
Encoding::Sop2 => (Some(sdst), vec![ssrc(0, src0), ssrc(8, src1)]),
|
||||
Encoding::Sopc => (None, vec![ssrc(0, src0), ssrc(8, src1)]),
|
||||
_ => match name {
|
||||
"s_getpc_b64" => (Some(sdst), vec![]),
|
||||
"s_setpc_b64" | "s_rfe_b64" => (None, vec![ssrc(0, src0)]),
|
||||
_ => (Some(sdst), vec![ssrc(0, src0)]),
|
||||
},
|
||||
};
|
||||
Fields::Sop {
|
||||
dst,
|
||||
src,
|
||||
imm: None,
|
||||
}
|
||||
}
|
||||
Encoding::Sopk => {
|
||||
let sdst = scalar((w0 >> 16 & 0x7F) as u8, 1 + u8::from(name == "s_call_b64"));
|
||||
let (dst, src) = match name {
|
||||
"s_setreg_imm32_b32" => (None, vec![Operand::Literal(w1)]),
|
||||
"s_version" => (None, vec![]),
|
||||
n if n.starts_with("s_cmpk_")
|
||||
|| n.starts_with("s_waitcnt_")
|
||||
|| n == "s_setreg_b32" =>
|
||||
{
|
||||
(None, vec![sdst])
|
||||
}
|
||||
_ => (Some(sdst), vec![]),
|
||||
};
|
||||
Fields::Sop {
|
||||
dst,
|
||||
src,
|
||||
imm: Some(w0 as u16),
|
||||
}
|
||||
}
|
||||
Encoding::Sopp => Fields::Sopp { imm: w0 as u16 },
|
||||
Encoding::Smem => {
|
||||
let data = match name {
|
||||
"s_gl1_inv" | "s_dcache_inv" | "s_dcache_wb" => None,
|
||||
n if n.starts_with("s_dcache_discard") => None,
|
||||
"s_memtime" | "s_memrealtime" => Some(2),
|
||||
_ => Some(data_dwords(name)),
|
||||
};
|
||||
let base = 2 + 2 * u8::from(name.starts_with("s_buffer_"));
|
||||
Fields::Smem {
|
||||
data: data.map(|d| scalar((w0 >> 6 & 0x7F) as u8, d)),
|
||||
base: scalar(((w0 & 0x3F) << 1) as u8, base),
|
||||
offset: (w1 << 11) as i32 >> 11,
|
||||
soffset: scalar((w1 >> 25) as u8, 1),
|
||||
cache: cache(bit(w0, 16), false, bit(w0, 14)),
|
||||
}
|
||||
}
|
||||
Encoding::Vop1 | Encoding::Vop2 | Encoding::Vopc | Encoding::Vop3 | Encoding::Vop3p => {
|
||||
Fields::Valu(self.valu(name, if wave64 { 2 } else { 1 }))
|
||||
}
|
||||
Encoding::Vintrp => {
|
||||
let vsrc = (w0 & 0xFF) as u8;
|
||||
Fields::Vintrp {
|
||||
dst: vector(w0 >> 18, 1),
|
||||
src: if name == "v_interp_mov_f32" {
|
||||
Operand::Const(vsrc)
|
||||
} else {
|
||||
vector(vsrc.into(), 1)
|
||||
},
|
||||
attr: Operand::Attr {
|
||||
index: (w0 >> 10 & 0x3F) as u8,
|
||||
chan: (w0 >> 8 & 3) as u8,
|
||||
high: false,
|
||||
},
|
||||
}
|
||||
}
|
||||
Encoding::Ds => {
|
||||
let ty = data_dwords(name);
|
||||
let pair = ds_pair(name);
|
||||
let returns = name.contains("read")
|
||||
|| name.contains("_rtn")
|
||||
|| matches!(
|
||||
name,
|
||||
"ds_swizzle_b32"
|
||||
| "ds_permute_b32"
|
||||
| "ds_bpermute_b32"
|
||||
| "ds_append"
|
||||
| "ds_consume"
|
||||
| "ds_ordered_count"
|
||||
);
|
||||
let no_addr = name.starts_with("ds_gws")
|
||||
|| name.contains("addtid")
|
||||
|| matches!(name, "ds_nop" | "ds_append" | "ds_consume");
|
||||
let data = if name.contains("read")
|
||||
|| name.contains("src2")
|
||||
|| matches!(
|
||||
name,
|
||||
"ds_swizzle_b32"
|
||||
| "ds_nop"
|
||||
| "ds_append"
|
||||
| "ds_consume"
|
||||
| "ds_ordered_count"
|
||||
| "ds_gws_sema_v"
|
||||
| "ds_gws_sema_p"
|
||||
| "ds_gws_sema_release_all"
|
||||
) {
|
||||
0
|
||||
} else if pair || name.contains("cmpst") || name.contains("mskor") {
|
||||
2
|
||||
} else {
|
||||
1
|
||||
};
|
||||
Fields::Ds {
|
||||
dst: returns.then(|| vector(w1 >> 24, ty * (1 + u8::from(pair)))),
|
||||
addr: (!no_addr).then(|| vector(w1 & 0xFF, 1)),
|
||||
data: (0..data)
|
||||
.map(|i| vector(w1 >> (8 + 8 * i) & 0xFF, ty))
|
||||
.collect(),
|
||||
offset0: w0 as u8,
|
||||
offset1: (w0 >> 8) as u8,
|
||||
gds: bit(w0, 17),
|
||||
}
|
||||
}
|
||||
Encoding::Mubuf | Encoding::Mtbuf => {
|
||||
let (offen, idxen, tfe) = (bit(w0, 12), bit(w0, 13), bit(w1, 23));
|
||||
let mtbuf = self.encoding == Encoding::Mtbuf;
|
||||
Fields::Buffer {
|
||||
data: (!name.ends_with("_inv"))
|
||||
.then(|| vector(w1 >> 8 & 0xFF, data_dwords(name) + u8::from(tfe))),
|
||||
addr: vector(w1 & 0xFF, 1 + u8::from(offen && idxen)),
|
||||
rsrc: scalar(((w1 >> 16 & 0x1F) << 2) as u8, 4),
|
||||
soffset: source(w1 >> 24, 1, 0),
|
||||
offset: (w0 & 0xFFF) as u16,
|
||||
offen,
|
||||
idxen,
|
||||
format: mtbuf.then_some((w0 >> 19 & 0x7F) as u8),
|
||||
lds: !mtbuf && bit(w0, 16),
|
||||
tfe,
|
||||
cache: cache(bit(w0, 14), bit(w1, 22), bit(w0, 15)),
|
||||
}
|
||||
}
|
||||
Encoding::Mimg => {
|
||||
let (dim, dmask, a16, d16) = (
|
||||
(w0 >> 3 & 7) as u8,
|
||||
(w0 >> 8 & 0xF) as u8,
|
||||
bit(w1, 30),
|
||||
bit(w1, 31),
|
||||
);
|
||||
let (r128, tfe, lwe) = (bit(w0, 15), bit(w0, 16), bit(w0, 17));
|
||||
let mut data = if name.starts_with("image_gather4") {
|
||||
4
|
||||
} else {
|
||||
dmask.count_ones().max(1) as u8
|
||||
};
|
||||
if d16 {
|
||||
data = data.div_ceil(2);
|
||||
}
|
||||
let count = image_addr_dwords(name, dim, a16);
|
||||
let addr = if w0 >> 1 & 3 == 0 {
|
||||
vec![vector(w1 & 0xFF, count)]
|
||||
} else {
|
||||
// NSA: one VGPR per address, the first in dword 1, the rest
|
||||
// in the extra dwords.
|
||||
(0..usize::from(count))
|
||||
.map(|i| match i {
|
||||
0 => vector(w1 & 0xFF, 1),
|
||||
i => vector(w(2 + (i - 1) / 4) >> (8 * ((i - 1) % 4)) & 0xFF, 1),
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let sampled = ["image_sample", "image_gather4", "image_get_lod"]
|
||||
.iter()
|
||||
.any(|p| name.starts_with(p));
|
||||
Fields::Image {
|
||||
data: vector(w1 >> 8 & 0xFF, data + u8::from(tfe || lwe)),
|
||||
addr,
|
||||
rsrc: scalar(((w1 >> 16 & 0x1F) << 2) as u8, if r128 { 4 } else { 8 }),
|
||||
sampler: sampled.then(|| scalar(((w1 >> 21 & 0x1F) << 2) as u8, 4)),
|
||||
dmask,
|
||||
dim,
|
||||
unorm: bit(w0, 12),
|
||||
r128,
|
||||
a16,
|
||||
d16,
|
||||
tfe,
|
||||
lwe,
|
||||
cache: cache(bit(w0, 13), bit(w0, 25), bit(w0, 7)),
|
||||
}
|
||||
}
|
||||
Encoding::Flat | Encoding::Global | Encoding::Scratch => {
|
||||
let saddr = (w1 >> 16 & 0x7F) as u8;
|
||||
let glc = bit(w0, 16);
|
||||
let n = data_dwords(name);
|
||||
let (load, atomic) = (name.contains("_load_"), name.contains("_atomic_"));
|
||||
let addr = match self.encoding {
|
||||
Encoding::Flat => Some(vector(w1 & 0xFF, 2)),
|
||||
Encoding::Global => Some(vector(w1 & 0xFF, 1 + u8::from(saddr == NULL))),
|
||||
// With an SGPR base, scratch takes no VGPR.
|
||||
_ => (saddr == NULL).then(|| vector(w1 & 0xFF, 1)),
|
||||
};
|
||||
let ret = if atomic && name.contains("cmpswap") {
|
||||
n / 2
|
||||
} else {
|
||||
n
|
||||
};
|
||||
Fields::Flat {
|
||||
dst: (load || atomic && glc).then(|| vector(w1 >> 24, ret)),
|
||||
addr,
|
||||
data: (!load).then(|| vector(w1 >> 8 & 0xFF, n)),
|
||||
saddr: (self.encoding != Encoding::Flat)
|
||||
.then(|| scalar(saddr, 1 + u8::from(self.encoding == Encoding::Global))),
|
||||
offset: match self.encoding {
|
||||
Encoding::Flat => (w0 & 0x7FF) as i16,
|
||||
_ => ((w0 << 4) as i16) >> 4,
|
||||
},
|
||||
lds: bit(w0, 13),
|
||||
cache: cache(glc, bit(w0, 17), bit(w0, 12)),
|
||||
}
|
||||
}
|
||||
Encoding::Exp => {
|
||||
let compr = bit(w0, 10);
|
||||
Fields::Exp {
|
||||
target: (w0 >> 4 & 0x3F) as u8,
|
||||
src: std::array::from_fn(|i| {
|
||||
let slot = if compr { i / 2 } else { i };
|
||||
bit(w0, i as u32).then(|| vector(w1 >> (8 * slot) & 0xFF, 1))
|
||||
}),
|
||||
compr,
|
||||
done: bit(w0, 11),
|
||||
vm: bit(w0, 12),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn valu(&self, name: &str, lanes: u8) -> Valu {
|
||||
// No operands; the console compiler stores a shader hash in their fields.
|
||||
if matches!(name, "v_nop" | "v_pipeflush" | "v_clrexcp") {
|
||||
return Valu::default();
|
||||
}
|
||||
let w = |i: usize| self.words.get(i).copied().unwrap_or(0);
|
||||
let w0 = w(0);
|
||||
let (dst_n, src_n) = valu_dwords(name);
|
||||
let compare = match self.encoding {
|
||||
Encoding::Vopc => true,
|
||||
Encoding::Vop3 => self.opcode < 0x100,
|
||||
_ => false,
|
||||
};
|
||||
let vop3b = VOP3B.contains(&name);
|
||||
let carry_in = name.ends_with("_co_ci_u32") || name == "v_cndmask_b32";
|
||||
let mut v = Valu::default();
|
||||
match self.encoding {
|
||||
Encoding::Vop1 | Encoding::Vop2 | Encoding::Vopc => {
|
||||
let ext = w(1);
|
||||
let mut src0 = w0 & 0x1FF;
|
||||
let vsrc1 = 256 + (w0 >> 9 & 0xFF);
|
||||
let mut src1 = vsrc1;
|
||||
match src0 {
|
||||
0xF9 => {
|
||||
let sdwa = Sdwa {
|
||||
dst_sel: (ext >> 8 & 7) as u8,
|
||||
dst_unused: (ext >> 11 & 3) as u8,
|
||||
src_sel: [(ext >> 16 & 7) as u8, (ext >> 24 & 7) as u8],
|
||||
sext: (ext >> 19 & 1 | ext >> 26 & 2) as u8,
|
||||
};
|
||||
// The s0/s1 bits select an SGPR or constant instead of a VGPR.
|
||||
src0 = (ext & 0xFF) | if ext >> 23 & 1 == 0 { 256 } else { 0 };
|
||||
if ext >> 31 == 1 {
|
||||
src1 = vsrc1 - 256;
|
||||
}
|
||||
v.neg = (ext >> 20 & 1 | ext >> 27 & 2) as u8;
|
||||
v.abs = (ext >> 21 & 1 | ext >> 28 & 2) as u8;
|
||||
if compare {
|
||||
if ext >> 15 & 1 == 1 {
|
||||
v.dst = Some(scalar((ext >> 8 & 0x7F) as u8, lanes));
|
||||
}
|
||||
v.sdwa = Some(Sdwa {
|
||||
dst_sel: 6,
|
||||
dst_unused: 0,
|
||||
..sdwa
|
||||
});
|
||||
} else {
|
||||
v.clamp = ext >> 13 & 1 == 1;
|
||||
v.omod = (ext >> 14 & 3) as u8;
|
||||
v.sdwa = Some(sdwa);
|
||||
}
|
||||
}
|
||||
0xFA => {
|
||||
src0 = 256 + (ext & 0xFF);
|
||||
v.neg = (ext >> 20 & 1 | ext >> 21 & 2) as u8;
|
||||
v.abs = (ext >> 21 & 1 | ext >> 22 & 2) as u8;
|
||||
v.dpp = Some(Dpp::Row {
|
||||
ctrl: (ext >> 8 & 0x1FF) as u16,
|
||||
row_mask: (ext >> 28) as u8,
|
||||
bank_mask: (ext >> 24 & 0xF) as u8,
|
||||
bound_ctrl: ext >> 19 & 1 == 1,
|
||||
fi: ext >> 18 & 1 == 1,
|
||||
});
|
||||
}
|
||||
0xE9 | 0xEA => {
|
||||
v.dpp = Some(Dpp::Lanes {
|
||||
sel: ext >> 8,
|
||||
fi: src0 == 0xEA,
|
||||
});
|
||||
src0 = 256 + (ext & 0xFF);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let op0 = source(src0, src_n[0], ext);
|
||||
let op1 = source(src1, src_n[1], ext);
|
||||
match self.encoding {
|
||||
Encoding::Vopc => {
|
||||
let mask = if name.starts_with("v_cmpx") {
|
||||
EXEC
|
||||
} else {
|
||||
VCC
|
||||
};
|
||||
v.dst = v.dst.or(Some(scalar(mask, lanes)));
|
||||
v.src = vec![op0, op1];
|
||||
}
|
||||
Encoding::Vop1 => {
|
||||
v.dst = Some(valu_dst(name, w0 >> 17 & 0xFF, dst_n));
|
||||
v.src = vec![op0];
|
||||
}
|
||||
_ => {
|
||||
v.dst = Some(vector(w0 >> 17 & 0xFF, dst_n));
|
||||
v.src = match name {
|
||||
n if n.ends_with("mk_f32") || n.ends_with("mk_f16") => {
|
||||
vec![op0, Operand::Literal(ext), op1]
|
||||
}
|
||||
n if n.ends_with("ak_f32") || n.ends_with("ak_f16") => {
|
||||
vec![op0, op1, Operand::Literal(ext)]
|
||||
}
|
||||
_ => vec![op0, op1],
|
||||
};
|
||||
if carry_in {
|
||||
v.src.push(scalar(VCC, lanes));
|
||||
}
|
||||
if name.ends_with("_co_ci_u32") {
|
||||
v.carry = Some(scalar(VCC, lanes));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Encoding::Vop3 | Encoding::Vop3p => {
|
||||
let w1 = w(1);
|
||||
let field = |i: u32| w1 >> (9 * i) & 0x1FF;
|
||||
let count = match self.opcode {
|
||||
_ if self.encoding == Encoding::Vop3p => {
|
||||
if name.starts_with("v_pk_")
|
||||
&& !name.contains("_fma_")
|
||||
&& !name.contains("_mad_")
|
||||
{
|
||||
2
|
||||
} else {
|
||||
3
|
||||
}
|
||||
}
|
||||
0x000..0x100 => 2,
|
||||
0x100..0x140 => 2 + usize::from(carry_in),
|
||||
0x180..0x200 => 1,
|
||||
_ if VOP3_TWO_SOURCES.contains(&name) => 2,
|
||||
_ => 3,
|
||||
};
|
||||
v.src = (0..count)
|
||||
.map(|i| {
|
||||
let code = field(i as u32);
|
||||
if i == 0 && name.starts_with("v_interp_") {
|
||||
Operand::Attr {
|
||||
index: (code & 0x3F) as u8,
|
||||
chan: (code >> 6 & 3) as u8,
|
||||
high: code >> 8 & 1 == 1,
|
||||
}
|
||||
} else if i == 2 && carry_in {
|
||||
source(code, lanes, w(2))
|
||||
} else {
|
||||
source(code, src_n[i], w(2))
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
v.clamp = w0 >> 15 & 1 == 1;
|
||||
v.neg = (w1 >> 29) as u8;
|
||||
if self.encoding == Encoding::Vop3p {
|
||||
v.neg_hi = (w0 >> 8 & 7) as u8;
|
||||
v.opsel = (w0 >> 11 & 7) as u8;
|
||||
v.opsel_hi = (w1 >> 27 & 3 | w0 >> 12 & 4) as u8;
|
||||
} else {
|
||||
v.omod = (w1 >> 27 & 3) as u8;
|
||||
if vop3b {
|
||||
v.carry = Some(scalar((w0 >> 8 & 0x7F) as u8, lanes));
|
||||
} else {
|
||||
v.abs = (w0 >> 8 & 7) as u8;
|
||||
v.opsel = (w0 >> 11 & 0xF) as u8;
|
||||
}
|
||||
}
|
||||
let vdst = w0 & 0xFF;
|
||||
v.dst = Some(if compare {
|
||||
scalar(vdst as u8, lanes)
|
||||
} else {
|
||||
valu_dst(name, vdst, dst_n)
|
||||
});
|
||||
}
|
||||
_ => unreachable!("not a VALU encoding"),
|
||||
}
|
||||
v
|
||||
}
|
||||
}
|
||||
|
||||
/// VOP3-only opcodes that take two sources (the rest take three).
|
||||
const VOP3_TWO_SOURCES: &[&str] = &[
|
||||
"v_add_f64",
|
||||
"v_mul_f64",
|
||||
"v_min_f64",
|
||||
"v_max_f64",
|
||||
"v_ldexp_f64",
|
||||
"v_mul_lo_u32",
|
||||
"v_mul_hi_u32",
|
||||
"v_mul_lo_i32",
|
||||
"v_mul_hi_i32",
|
||||
"v_trig_preop_f64",
|
||||
"v_lshlrev_b64",
|
||||
"v_lshrrev_b64",
|
||||
"v_ashrrev_i64",
|
||||
"v_add_nc_u16",
|
||||
"v_sub_nc_u16",
|
||||
"v_mul_lo_u16",
|
||||
"v_lshrrev_b16",
|
||||
"v_ashrrev_i16",
|
||||
"v_max_u16",
|
||||
"v_max_i16",
|
||||
"v_min_u16",
|
||||
"v_min_i16",
|
||||
"v_add_nc_i16",
|
||||
"v_sub_nc_i16",
|
||||
"v_add_co_u32",
|
||||
"v_sub_co_u32",
|
||||
"v_subrev_co_u32",
|
||||
"v_pack_b32_f16",
|
||||
"v_cvt_pknorm_i16_f16",
|
||||
"v_cvt_pknorm_u16_f16",
|
||||
"v_lshlrev_b16",
|
||||
"v_interp_p1ll_f16",
|
||||
"v_readlane_b32",
|
||||
"v_writelane_b32",
|
||||
"v_ldexp_f32",
|
||||
"v_bfm_b32",
|
||||
"v_bcnt_u32_b32",
|
||||
"v_mbcnt_lo_u32_b32",
|
||||
"v_mbcnt_hi_u32_b32",
|
||||
"v_cvt_pknorm_i16_f32",
|
||||
"v_cvt_pknorm_u16_f32",
|
||||
"v_cvt_pk_u16_u32",
|
||||
"v_cvt_pk_i16_i32",
|
||||
"v_sub_nc_i32",
|
||||
"v_add_nc_i32",
|
||||
];
|
||||
|
||||
/// VOP3 opcodes whose bits 14:8 hold a scalar destination instead of `abs`/`opsel`.
|
||||
const VOP3B: &[&str] = &[
|
||||
"v_add_co_u32",
|
||||
"v_sub_co_u32",
|
||||
"v_subrev_co_u32",
|
||||
"v_add_co_ci_u32",
|
||||
"v_sub_co_ci_u32",
|
||||
"v_subrev_co_ci_u32",
|
||||
"v_div_scale_f32",
|
||||
"v_div_scale_f64",
|
||||
"v_mad_u64_u32",
|
||||
"v_mad_i64_i32",
|
||||
];
|
||||
|
||||
fn scalar(code: u8, dwords: u8) -> Operand {
|
||||
Operand::Scalar { code, dwords }
|
||||
}
|
||||
|
||||
fn vector(reg: u32, dwords: u8) -> Operand {
|
||||
Operand::Vector {
|
||||
reg: reg as u8,
|
||||
dwords,
|
||||
}
|
||||
}
|
||||
|
||||
/// A 9-bit source field (8-bit scalar fields are the same codes below 256).
|
||||
fn source(code: u32, dwords: u8, literal: u32) -> Operand {
|
||||
match code {
|
||||
0..=127 => scalar(code as u8, dwords),
|
||||
255 => Operand::Literal(literal),
|
||||
256.. => vector(code - 256, dwords),
|
||||
_ => Operand::Const(code as u8),
|
||||
}
|
||||
}
|
||||
|
||||
/// VALU destinations that are SGPRs.
|
||||
fn valu_dst(name: &str, field: u32, dwords: u8) -> Operand {
|
||||
match name {
|
||||
"v_readlane_b32" | "v_readfirstlane_b32" => scalar(field as u8, 1),
|
||||
_ => vector(field, dwords),
|
||||
}
|
||||
}
|
||||
|
||||
/// LDS opcodes on two addresses (`ds_read2_b32`...), with `offset0`/`offset1`.
|
||||
pub(super) fn ds_pair(name: &str) -> bool {
|
||||
name.split('_').any(|t| {
|
||||
["read2", "write2", "wrxchg2"]
|
||||
.iter()
|
||||
.any(|p| t.starts_with(p))
|
||||
})
|
||||
}
|
||||
|
||||
/// Dwords of a type suffix such as `b64` or `f32`.
|
||||
fn type_dwords(token: &str) -> u8 {
|
||||
match token {
|
||||
"b64" | "u64" | "i64" | "f64" => 2,
|
||||
_ => 1,
|
||||
}
|
||||
}
|
||||
|
||||
/// (sdst, ssrc0, ssrc1) dwords of a scalar ALU opcode.
|
||||
fn salu_dwords(name: &str) -> (u8, u8, u8) {
|
||||
match name {
|
||||
"s_lshl_b64" | "s_lshr_b64" | "s_ashr_i64" | "s_bfe_u64" | "s_bfe_i64"
|
||||
| "s_bitcmp0_b64" | "s_bitcmp1_b64" => (2, 2, 1),
|
||||
"s_bfm_b64" | "s_bitset0_b64" | "s_bitset1_b64" | "s_bitreplicate_b64_b32" => (2, 1, 1),
|
||||
"s_bcnt0_i32_b64" | "s_bcnt1_i32_b64" | "s_ff0_i32_b64" | "s_ff1_i32_b64"
|
||||
| "s_flbit_i32_b64" | "s_flbit_i32_i64" => (1, 2, 2),
|
||||
_ => {
|
||||
let n = type_dwords(name.rsplit('_').next().unwrap_or(""));
|
||||
(n, n, n)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// (vdst, [src0, src1, src2]) dwords of a VALU opcode.
|
||||
fn valu_dwords(name: &str) -> (u8, [u8; 3]) {
|
||||
let parts: Vec<&str> = name.split('_').collect();
|
||||
match name {
|
||||
"v_lshlrev_b64" | "v_lshrrev_b64" | "v_ashrrev_i64" => (2, [1, 2, 2]),
|
||||
"v_ldexp_f64" | "v_trig_preop_f64" | "v_cmp_class_f64" | "v_cmpx_class_f64" => {
|
||||
(2, [2, 1, 2])
|
||||
}
|
||||
"v_mad_u64_u32" | "v_mad_i64_i32" => (2, [1, 1, 2]),
|
||||
"v_qsad_pk_u16_u8" | "v_mqsad_pk_u16_u8" => (2, [2, 1, 2]),
|
||||
"v_mqsad_u32_u8" => (4, [2, 1, 4]),
|
||||
"v_frexp_exp_i32_f64" => (1, [2; 3]),
|
||||
_ if parts.len() == 4 && parts[1] == "cvt" => {
|
||||
(type_dwords(parts[2]), [type_dwords(parts[3]); 3])
|
||||
}
|
||||
_ => {
|
||||
let n = type_dwords(parts.last().copied().unwrap_or(""));
|
||||
(n, [n; 3])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Dwords of loaded, stored or atomic data, from the opcode name.
|
||||
fn data_dwords(name: &str) -> u8 {
|
||||
let mut n: u8 = 1;
|
||||
for token in name.split('_') {
|
||||
n = match token {
|
||||
"dwordx2" | "x2" | "xy" | "b64" | "u64" | "i64" | "f64" => 2,
|
||||
"dwordx3" | "xyz" | "b96" => 3,
|
||||
"dwordx4" | "xyzw" | "b128" => 4,
|
||||
"dwordx8" => 8,
|
||||
"dwordx16" => 16,
|
||||
_ => n,
|
||||
};
|
||||
}
|
||||
if name.contains("cmpswap") {
|
||||
n *= 2;
|
||||
}
|
||||
if name.contains("format_d16") {
|
||||
n = n.div_ceil(2);
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
/// Address dwords of an image opcode: offset, bias, compare, derivatives,
|
||||
/// coordinates, then LOD/clamp/mip, packed in pairs with `a16`.
|
||||
fn image_addr_dwords(name: &str, dim: u8, a16: bool) -> u8 {
|
||||
// (coordinates, derivatives per direction) for 1D 2D 3D CUBE 1D_ARRAY
|
||||
// 2D_ARRAY 2D_MSAA 2D_MSAA_ARRAY.
|
||||
const DIMS: [(u8, u8); 8] = [
|
||||
(1, 1),
|
||||
(2, 2),
|
||||
(3, 3),
|
||||
(3, 2),
|
||||
(2, 1),
|
||||
(3, 2),
|
||||
(3, 2),
|
||||
(4, 2),
|
||||
];
|
||||
let (coords, grads) = DIMS[usize::from(dim & 7)];
|
||||
match name {
|
||||
"image_bvh_intersect_ray" => return if a16 { 8 } else { 11 },
|
||||
"image_bvh64_intersect_ray" => return if a16 { 9 } else { 12 },
|
||||
"image_get_resinfo" => return 1,
|
||||
_ => {}
|
||||
}
|
||||
let (mut whole, mut derivs, mut packed): (u8, u8, u8) = (0, 0, coords);
|
||||
if let Some(rest) = name
|
||||
.strip_prefix("image_sample")
|
||||
.or_else(|| name.strip_prefix("image_gather4"))
|
||||
{
|
||||
for token in rest.split('_') {
|
||||
match token {
|
||||
"o" | "b" | "c" => whole += 1,
|
||||
"d" | "cd" => derivs = grads,
|
||||
"l" | "cl" => packed += 1,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
} else if name.contains("_mip") {
|
||||
packed += 1;
|
||||
}
|
||||
if a16 {
|
||||
whole + 2 * derivs.div_ceil(2) + packed.div_ceil(2)
|
||||
} else {
|
||||
whole + 2 * derivs + packed
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,496 @@
|
||||
//! GFX10 machine code: instruction boundaries, encodings and opcodes.
|
||||
//!
|
||||
//! Instructions are found by following control flow from offset 0, not by a
|
||||
//! linear sweep: compilers place data (constant tables) in the code region
|
||||
//! after the end of the program. [`Instruction::fields`] decodes the operand
|
||||
//! fields and [`Instruction::text`] prints them in AMD's SP3 syntax.
|
||||
//!
|
||||
//! Encodings by the top bits of the first dword:
|
||||
//!
|
||||
//! ```text
|
||||
//! 0xxxxxxx VOP2; 0111111 VOP1; 0111110 VOPC
|
||||
//! 10 SOP2; 1011 SOPK; 101111101 SOP1; 101111110 SOPC; 101111111 SOPP
|
||||
//! 110010 VINTRP 110011 VOP3P 110101 VOP3 110110 DS 110111 FLAT/GLOBAL/SCRATCH
|
||||
//! 111000 MUBUF 111010 MTBUF 111100 MIMG 111101 SMEM 111110 EXP
|
||||
//! ```
|
||||
|
||||
mod fields;
|
||||
mod opcodes;
|
||||
mod sp3;
|
||||
|
||||
pub use fields::{Cache, Dpp, Fields, NULL, Operand, Sdwa, Valu};
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use crate::ShaderError;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum Encoding {
|
||||
Sop2,
|
||||
Sopk,
|
||||
Sop1,
|
||||
Sopc,
|
||||
Sopp,
|
||||
Smem,
|
||||
Vop2,
|
||||
Vop1,
|
||||
Vopc,
|
||||
Vop3,
|
||||
Vop3p,
|
||||
Vintrp,
|
||||
Ds,
|
||||
Mubuf,
|
||||
Mtbuf,
|
||||
Mimg,
|
||||
Exp,
|
||||
Flat,
|
||||
Global,
|
||||
Scratch,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Instruction {
|
||||
/// Byte offset in the program.
|
||||
pub offset: usize,
|
||||
pub encoding: Encoding,
|
||||
pub opcode: u16,
|
||||
/// Every dword of the instruction, including literals and extra dwords.
|
||||
pub words: Vec<u32>,
|
||||
}
|
||||
|
||||
impl Instruction {
|
||||
/// AMD's name for the opcode, if it is in our table.
|
||||
pub fn name(&self) -> Option<&'static str> {
|
||||
name(self.encoding, self.opcode)
|
||||
}
|
||||
}
|
||||
|
||||
/// Decodes every instruction reachable from offset 0, sorted by offset.
|
||||
pub fn decode(code: &[u8]) -> Result<Vec<Instruction>, ShaderError> {
|
||||
if !code.len().is_multiple_of(4) {
|
||||
return Err(isa(code.len(), "code size is not a multiple of 4"));
|
||||
}
|
||||
let mut found = BTreeMap::new();
|
||||
let mut pending = vec![0usize];
|
||||
while let Some(mut offset) = pending.pop() {
|
||||
while !found.contains_key(&offset) {
|
||||
let inst = instruction(code, offset)?;
|
||||
let next = offset + 4 * inst.words.len();
|
||||
let flow = control(&inst, code.len(), |at| {
|
||||
found.range(..at).next_back().map(|(_, i)| i)
|
||||
})?;
|
||||
found.insert(offset, inst);
|
||||
match flow {
|
||||
Flow::Next => offset = next,
|
||||
Flow::Stop => break,
|
||||
Flow::Jump(target) => offset = target,
|
||||
Flow::Branch(target) => {
|
||||
pending.push(target);
|
||||
offset = next;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let list: Vec<Instruction> = found.into_values().collect();
|
||||
if let Some(w) = list
|
||||
.windows(2)
|
||||
.find(|w| w[0].offset + 4 * w[0].words.len() > w[1].offset)
|
||||
{
|
||||
return Err(isa(w[1].offset, "a branch lands inside an instruction"));
|
||||
}
|
||||
Ok(list)
|
||||
}
|
||||
|
||||
/// Where execution goes after an instruction.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum Flow {
|
||||
Next,
|
||||
/// End of the program, or an indirect jump that is not a far jump.
|
||||
Stop,
|
||||
Jump(usize),
|
||||
/// Conditional: to the target or the next instruction.
|
||||
Branch(usize),
|
||||
}
|
||||
|
||||
/// Control flow after `inst`, resolving far jumps. `before(at)` returns the
|
||||
/// decoded instruction with the highest offset below `at`, if any.
|
||||
pub(crate) fn control<'a>(
|
||||
inst: &Instruction,
|
||||
len: usize,
|
||||
before: impl Fn(usize) -> Option<&'a Instruction>,
|
||||
) -> Result<Flow, ShaderError> {
|
||||
Ok(match flow(inst, inst.offset + 4 * inst.words.len(), len)? {
|
||||
Flow::Stop if inst.name() == Some("s_setpc_b64") => {
|
||||
far_jump(before, inst, len)?.map_or(Flow::Stop, Flow::Jump)
|
||||
}
|
||||
flow => flow,
|
||||
})
|
||||
}
|
||||
|
||||
fn flow(inst: &Instruction, next: usize, len: usize) -> Result<Flow, ShaderError> {
|
||||
let target = || {
|
||||
let delta = 4 * i64::from(inst.words[0] as u16 as i16);
|
||||
usize::try_from(next as i64 + delta)
|
||||
.ok()
|
||||
.filter(|&t| t < len)
|
||||
.ok_or(isa(inst.offset, "branch target outside the code"))
|
||||
};
|
||||
Ok(match (inst.encoding, inst.name().unwrap_or("")) {
|
||||
(
|
||||
Encoding::Sopp,
|
||||
"s_endpgm" | "s_endpgm_saved" | "s_endpgm_ordered_ps_done" | "s_code_end",
|
||||
) => Flow::Stop,
|
||||
(Encoding::Sopp, "s_branch") => Flow::Jump(target()?),
|
||||
(Encoding::Sopp, name) if name.starts_with("s_cbranch_") => Flow::Branch(target()?),
|
||||
(Encoding::Sopk, "s_call_b64") => Flow::Branch(target()?),
|
||||
// Indirect jump; `decode` resolves the compiler's far-jump form.
|
||||
(Encoding::Sop1, "s_setpc_b64") => Flow::Stop,
|
||||
_ => Flow::Next,
|
||||
})
|
||||
}
|
||||
|
||||
/// Resolves the far jump compilers emit beyond the reach of a branch offset:
|
||||
/// `s_getpc_b64 s[n:n+1]`, `s_add_u32|s_sub_u32 sn, sn, literal`, a carry
|
||||
/// into s(n+1), `s_setpc_b64 s[n:n+1]`, looking back over the straight-line
|
||||
/// run just decoded. Any other `s_setpc_b64` (e.g. a handover to the next
|
||||
/// merged stage through registers) gives `None`.
|
||||
fn far_jump<'a>(
|
||||
before: impl Fn(usize) -> Option<&'a Instruction>,
|
||||
setpc: &Instruction,
|
||||
len: usize,
|
||||
) -> Result<Option<usize>, ShaderError> {
|
||||
let n = setpc.words[0] & 0xFF;
|
||||
let mut delta = None;
|
||||
let mut at = setpc.offset;
|
||||
for _ in 0..4 {
|
||||
let Some(prev) = before(at) else {
|
||||
break;
|
||||
};
|
||||
if prev.offset + 4 * prev.words.len() != at {
|
||||
break;
|
||||
}
|
||||
let w = prev.words[0];
|
||||
let (sdst, ssrc0, ssrc1) = ((w >> 16) & 0x7F, w & 0xFF, (w >> 8) & 0xFF);
|
||||
match (prev.encoding, prev.name()) {
|
||||
(Encoding::Sop2, Some(op @ ("s_add_u32" | "s_sub_u32")))
|
||||
if sdst == n && ssrc0 == n && ssrc1 == 0xFF && delta.is_none() =>
|
||||
{
|
||||
// The low dword of a signed 64-bit offset: a backward jump
|
||||
// adds a negative one (its high dword is -1).
|
||||
let literal = i64::from(prev.words[1] as i32);
|
||||
delta = Some(if op == "s_add_u32" { literal } else { -literal });
|
||||
}
|
||||
(Encoding::Sop1, Some("s_getpc_b64")) if sdst == n => {
|
||||
let Some(delta) = delta else { break };
|
||||
// s_getpc_b64 yields the address of the instruction after it.
|
||||
return usize::try_from(prev.offset as i64 + 4 + delta)
|
||||
.ok()
|
||||
.filter(|&t| t < len)
|
||||
.map(Some)
|
||||
.ok_or(isa(setpc.offset, "far jump target outside the code"));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
at = prev.offset;
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn instruction(code: &[u8], offset: usize) -> Result<Instruction, ShaderError> {
|
||||
let word = |i: usize| {
|
||||
code.get(offset + 4 * i..offset + 4 * i + 4)
|
||||
.map(|b| u32::from_le_bytes(b.try_into().expect("4 bytes")))
|
||||
.ok_or(isa(offset, "instruction runs past the end of the code"))
|
||||
};
|
||||
let w = word(0)?;
|
||||
let (encoding, opcode, len) = if w >> 31 == 0 {
|
||||
let src0 = w & 0x1FF;
|
||||
// Literal constant, SDWA, DPP16, DPP8, DPP8 with fetch-inactive.
|
||||
let extra = usize::from(matches!(src0, 0xFF | 0xF9 | 0xFA | 0xE9 | 0xEA));
|
||||
match w >> 25 {
|
||||
0x3F => (Encoding::Vop1, (w >> 9) & 0xFF, 1 + extra),
|
||||
0x3E => (Encoding::Vopc, (w >> 17) & 0xFF, 1 + extra),
|
||||
op => {
|
||||
let mk_ak = name(Encoding::Vop2, op as u16).is_some_and(|n| {
|
||||
matches!(
|
||||
n,
|
||||
"v_madmk_f32"
|
||||
| "v_madak_f32"
|
||||
| "v_fmamk_f32"
|
||||
| "v_fmaak_f32"
|
||||
| "v_madmk_f16"
|
||||
| "v_madak_f16"
|
||||
| "v_fmamk_f16"
|
||||
| "v_fmaak_f16"
|
||||
)
|
||||
});
|
||||
(Encoding::Vop2, op, 1 + extra.max(usize::from(mk_ak)))
|
||||
}
|
||||
}
|
||||
} else if w >> 30 == 0b10 {
|
||||
let literal = |srcs: &[u32]| 1 + usize::from(srcs.contains(&0xFF));
|
||||
match w >> 23 {
|
||||
0x17D => (Encoding::Sop1, (w >> 8) & 0xFF, literal(&[w & 0xFF])),
|
||||
0x17E => (
|
||||
Encoding::Sopc,
|
||||
(w >> 16) & 0x7F,
|
||||
literal(&[w & 0xFF, (w >> 8) & 0xFF]),
|
||||
),
|
||||
0x17F => (Encoding::Sopp, (w >> 16) & 0x7F, 1),
|
||||
_ if w >> 28 == 0b1011 => {
|
||||
let op = (w >> 23) & 0x1F;
|
||||
let imm32 = name(Encoding::Sopk, op as u16) == Some("s_setreg_imm32_b32");
|
||||
(Encoding::Sopk, op, 1 + usize::from(imm32))
|
||||
}
|
||||
_ => (
|
||||
Encoding::Sop2,
|
||||
(w >> 23) & 0x7F,
|
||||
literal(&[w & 0xFF, (w >> 8) & 0xFF]),
|
||||
),
|
||||
}
|
||||
} else {
|
||||
let vop3 =
|
||||
|w1: u32| 2 + usize::from([w1, w1 >> 9, w1 >> 18].iter().any(|s| s & 0x1FF == 0xFF));
|
||||
match w >> 26 {
|
||||
0x32 => (Encoding::Vintrp, (w >> 16) & 0x3, 1),
|
||||
0x33 => (Encoding::Vop3p, (w >> 16) & 0x7F, vop3(word(1)?)),
|
||||
0x35 => (Encoding::Vop3, (w >> 16) & 0x3FF, vop3(word(1)?)),
|
||||
0x36 => (Encoding::Ds, (w >> 18) & 0xFF, 2),
|
||||
0x37 => {
|
||||
let encoding = match (w >> 14) & 3 {
|
||||
0 => Encoding::Flat,
|
||||
1 => Encoding::Scratch,
|
||||
2 => Encoding::Global,
|
||||
_ => return Err(isa(offset, "reserved FLAT segment")),
|
||||
};
|
||||
(encoding, (w >> 18) & 0x7F, 2)
|
||||
}
|
||||
0x38 => (Encoding::Mubuf, (w >> 18) & 0x7F | (w >> 25 & 1) << 7, 2),
|
||||
0x3A => (
|
||||
Encoding::Mtbuf,
|
||||
(w >> 16) & 0x7 | (word(1)? >> 21 & 1) << 3,
|
||||
2,
|
||||
),
|
||||
// Bits 2:1 count extra dwords of non-sequential address registers.
|
||||
0x3C => (
|
||||
Encoding::Mimg,
|
||||
(w >> 18) & 0x7F | (w & 1) << 7,
|
||||
2 + (w as usize >> 1 & 3),
|
||||
),
|
||||
0x3D => (Encoding::Smem, (w >> 18) & 0xFF, 2),
|
||||
0x3E => (Encoding::Exp, 0, 2),
|
||||
_ => return Err(isa(offset, "unknown encoding")),
|
||||
}
|
||||
};
|
||||
Ok(Instruction {
|
||||
offset,
|
||||
encoding,
|
||||
opcode: opcode as u16,
|
||||
words: (0..len).map(word).collect::<Result<_, _>>()?,
|
||||
})
|
||||
}
|
||||
|
||||
fn name(encoding: Encoding, opcode: u16) -> Option<&'static str> {
|
||||
use opcodes as t;
|
||||
let (table, op) = match encoding {
|
||||
Encoding::Sop2 => (t::SOP2, opcode),
|
||||
Encoding::Sopk => (t::SOPK, opcode),
|
||||
Encoding::Sop1 => (t::SOP1, opcode),
|
||||
Encoding::Sopc => (t::SOPC, opcode),
|
||||
Encoding::Sopp => (t::SOPP, opcode),
|
||||
Encoding::Smem => (t::SMEM, opcode),
|
||||
Encoding::Vop2 => (t::VOP2, opcode),
|
||||
Encoding::Vop1 => (t::VOP1, opcode),
|
||||
Encoding::Vopc => (t::VOPC, opcode),
|
||||
// VOP3 also encodes the VOPC, VOP2 and VOP1 opcodes at fixed bases.
|
||||
Encoding::Vop3 => match opcode {
|
||||
0x000..0x100 => (t::VOPC, opcode),
|
||||
0x100..0x140 => (t::VOP2, opcode - 0x100),
|
||||
0x180..0x200 => (t::VOP1, opcode - 0x180),
|
||||
_ => (t::VOP3, opcode),
|
||||
},
|
||||
Encoding::Vop3p => (t::VOP3P, opcode),
|
||||
Encoding::Vintrp => (t::VINTRP, opcode),
|
||||
Encoding::Ds => (t::DS, opcode),
|
||||
Encoding::Mubuf => (t::MUBUF, opcode),
|
||||
Encoding::Mtbuf => (t::MTBUF, opcode),
|
||||
Encoding::Mimg => (t::MIMG, opcode),
|
||||
Encoding::Exp => return Some("exp"),
|
||||
Encoding::Flat => (t::FLAT, opcode),
|
||||
Encoding::Global => (t::GLOBAL, opcode),
|
||||
Encoding::Scratch => (t::SCRATCH, opcode),
|
||||
};
|
||||
table
|
||||
.binary_search_by_key(&op, |&(o, _)| o)
|
||||
.ok()
|
||||
.map(|i| table[i].1)
|
||||
}
|
||||
|
||||
fn isa(offset: usize, reason: &'static str) -> ShaderError {
|
||||
ShaderError::Isa { offset, reason }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const S_ENDPGM: u32 = 0xBF81_0000;
|
||||
/// s_branch / s_cbranch_scc0 with a dword offset relative to the next instruction.
|
||||
const fn sopp(op: u32, simm16: i16) -> u32 {
|
||||
0xBF80_0000 | op << 16 | simm16 as u16 as u32
|
||||
}
|
||||
|
||||
fn bytes(words: &[u32]) -> Vec<u8> {
|
||||
words.iter().flat_map(|w| w.to_le_bytes()).collect()
|
||||
}
|
||||
|
||||
fn summary(code: &[u32]) -> Vec<(usize, usize, &'static str)> {
|
||||
decode(&bytes(code))
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|i| (i.offset, i.words.len(), i.name().unwrap_or("?")))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tables_are_sorted() {
|
||||
for t in [
|
||||
opcodes::SOP2,
|
||||
opcodes::SOPK,
|
||||
opcodes::SOP1,
|
||||
opcodes::SOPC,
|
||||
opcodes::SOPP,
|
||||
opcodes::SMEM,
|
||||
opcodes::VOP2,
|
||||
opcodes::VOP1,
|
||||
opcodes::VOPC,
|
||||
opcodes::VOP3,
|
||||
opcodes::VOP3P,
|
||||
opcodes::VINTRP,
|
||||
opcodes::DS,
|
||||
opcodes::MUBUF,
|
||||
opcodes::MTBUF,
|
||||
opcodes::MIMG,
|
||||
opcodes::FLAT,
|
||||
opcodes::GLOBAL,
|
||||
opcodes::SCRATCH,
|
||||
] {
|
||||
assert!(t.windows(2).all(|w| w[0].0 < w[1].0));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lengths_and_names() {
|
||||
let code = [
|
||||
0xBE80_03FF,
|
||||
0x3F80_0000, // s_mov_b32 s0, literal
|
||||
0x0600_0000, // v_add_f32 v0, s0, v0
|
||||
0xD54B_0000,
|
||||
0x03FE_0000,
|
||||
0x4000_0000, // v_fma_f32 with a literal src2
|
||||
0xF080_0F0A,
|
||||
0,
|
||||
0, // image_sample (2D) with one extra address dword
|
||||
0xF800_080F,
|
||||
0, // exp
|
||||
S_ENDPGM,
|
||||
];
|
||||
assert_eq!(
|
||||
summary(&code),
|
||||
[
|
||||
(0, 2, "s_mov_b32"),
|
||||
(8, 1, "v_add_f32"),
|
||||
(12, 3, "v_fma_f32"),
|
||||
(24, 3, "image_sample"),
|
||||
(36, 2, "exp"),
|
||||
(44, 1, "s_endpgm"),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn follows_branches_and_skips_data() {
|
||||
let code = [
|
||||
sopp(0x04, 1), // s_cbranch_scc0 -> 8
|
||||
sopp(0x02, 1), // s_branch -> 12
|
||||
S_ENDPGM,
|
||||
S_ENDPGM,
|
||||
S_ENDPGM, // data follows the program end
|
||||
0xFFFF_FFFF,
|
||||
];
|
||||
let found: Vec<_> = summary(&code).iter().map(|i| i.0).collect();
|
||||
assert_eq!(found, [0, 4, 8, 12]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn follows_far_jumps() {
|
||||
let code = [
|
||||
0xBE88_1F00, // s_getpc_b64 s[8:9]
|
||||
0x8008_FF08,
|
||||
20, // s_add_u32 s8, s8, 20 -> 4 + 20 = 24
|
||||
0x8209_8009, // s_addc_u32 s9, s9, 0
|
||||
0xBE80_2008, // s_setpc_b64 s[8:9]
|
||||
0xFFFF_FFFF, // not code
|
||||
S_ENDPGM,
|
||||
];
|
||||
let found: Vec<_> = summary(&code).iter().map(|i| (i.0, i.2)).collect();
|
||||
assert_eq!(
|
||||
found,
|
||||
[
|
||||
(0, "s_getpc_b64"),
|
||||
(4, "s_add_u32"),
|
||||
(12, "s_addc_u32"),
|
||||
(16, "s_setpc_b64"),
|
||||
(24, "s_endpgm"),
|
||||
]
|
||||
);
|
||||
// Through other registers (a handover to another stage): the path ends.
|
||||
assert_eq!(summary(&[0xBE80_2018, S_ENDPGM]).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn follows_far_jumps_backward() {
|
||||
// The compiler's backward far jump adds a negative offset: the low
|
||||
// dword as a 32-bit literal, the high dword as -1 with the carry.
|
||||
let code = [
|
||||
sopp(0x02, 1), // s_branch -> 8, past the jump target
|
||||
S_ENDPGM, // the far jump's target: only it reaches here
|
||||
0xBE88_1F00, // s_getpc_b64 s[8:9]
|
||||
0x8008_FF08,
|
||||
0xFFFF_FFF8, // s_add_u32 s8, s8, -8 -> 12 - 8 = 4
|
||||
0x8209_C109, // s_addc_u32 s9, s9, -1
|
||||
0xBE80_2008, // s_setpc_b64 s[8:9]
|
||||
];
|
||||
let found: Vec<_> = summary(&code).iter().map(|i| (i.0, i.2)).collect();
|
||||
assert_eq!(
|
||||
found,
|
||||
[
|
||||
(0, "s_branch"),
|
||||
(4, "s_endpgm"),
|
||||
(8, "s_getpc_b64"),
|
||||
(12, "s_add_u32"),
|
||||
(20, "s_addc_u32"),
|
||||
(24, "s_setpc_b64"),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_bad_code() {
|
||||
assert!(decode(&[0; 3]).is_err(), "size not a multiple of 4");
|
||||
assert!(
|
||||
decode(&bytes(&[sopp(0x02, 100)])).is_err(),
|
||||
"branch out of range"
|
||||
);
|
||||
assert!(
|
||||
decode(&bytes(&[0xBE80_03FF])).is_err(),
|
||||
"literal past the end"
|
||||
);
|
||||
assert!(
|
||||
decode(&bytes(&[0xE400_0000, 0])).is_err(),
|
||||
"unknown encoding"
|
||||
);
|
||||
// s_cbranch_scc0 into the literal of the s_mov_b32 at 4.
|
||||
assert!(decode(&bytes(&[sopp(0x04, 1), 0xBE80_03FF, S_ENDPGM, S_ENDPGM])).is_err());
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,784 @@
|
||||
//! Instruction text in AMD's SP3 assembly syntax.
|
||||
|
||||
use std::fmt::{self, Display, Write};
|
||||
|
||||
use super::fields::{Cache, Dpp, Fields, NULL, Operand, Valu};
|
||||
use super::{Encoding, Instruction};
|
||||
|
||||
impl Instruction {
|
||||
/// The instruction in SP3 syntax, e.g. `v_add_f32 v1, 0.5, v8`.
|
||||
/// Branch targets are written `label_<byte offset>`.
|
||||
pub fn text(&self, wave64: bool) -> String {
|
||||
let name = self.name().unwrap_or("?");
|
||||
let ops = operands(self, name, &self.fields(wave64));
|
||||
if ops.is_empty() {
|
||||
name.to_owned()
|
||||
} else {
|
||||
format!("{name} {ops}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for Operand {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
match *self {
|
||||
Operand::Scalar { code, dwords: 1 } => f.write_str(&scalar_name(code)),
|
||||
Operand::Scalar {
|
||||
code: 106,
|
||||
dwords: 2,
|
||||
} => f.write_str("vcc"),
|
||||
Operand::Scalar {
|
||||
code: 126,
|
||||
dwords: 2,
|
||||
} => f.write_str("exec"),
|
||||
Operand::Scalar { code, dwords } if code < 106 => {
|
||||
write!(f, "s[{code}:{}]", code + dwords - 1)
|
||||
}
|
||||
Operand::Scalar { code, dwords } if (108..124).contains(&code) => {
|
||||
write!(f, "ttmp[{}:{}]", code - 108, code - 108 + dwords - 1)
|
||||
}
|
||||
Operand::Scalar { code, .. } => f.write_str(&scalar_name(code)),
|
||||
Operand::Vector { reg, dwords: 1 } => write!(f, "v{reg}"),
|
||||
Operand::Vector { reg, dwords } => {
|
||||
write!(f, "v[{reg}:{}]", reg as u32 + dwords as u32 - 1)
|
||||
}
|
||||
Operand::Const(code) => f.write_str(&const_name(code)),
|
||||
Operand::Literal(value) => write!(f, "lit(0x{value:08x})"),
|
||||
Operand::Attr { index, chan, .. } => write!(
|
||||
f,
|
||||
"attr{index}.{}",
|
||||
['x', 'y', 'z', 'w'][usize::from(chan & 3)]
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn scalar_name(code: u8) -> String {
|
||||
match code {
|
||||
0..=105 => format!("s{code}"),
|
||||
106 => "vcc_lo".into(),
|
||||
107 => "vcc_hi".into(),
|
||||
108..=123 => format!("ttmp{}", code - 108),
|
||||
124 => "m0".into(),
|
||||
125 => "null".into(),
|
||||
126 => "exec_lo".into(),
|
||||
_ => "exec_hi".into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn const_name(code: u8) -> String {
|
||||
match code {
|
||||
128..=192 => (i32::from(code) - 128).to_string(),
|
||||
193..=208 => (192 - i32::from(code)).to_string(),
|
||||
240 => "0.5".into(),
|
||||
241 => "-0.5".into(),
|
||||
242 => "1.0".into(),
|
||||
243 => "-1.0".into(),
|
||||
244 => "2.0".into(),
|
||||
245 => "-2.0".into(),
|
||||
246 => "4.0".into(),
|
||||
247 => "-4.0".into(),
|
||||
248 => "0.15915494".into(),
|
||||
235 => "src_shared_base".into(),
|
||||
236 => "src_shared_limit".into(),
|
||||
237 => "src_private_base".into(),
|
||||
238 => "src_private_limit".into(),
|
||||
239 => "src_pops_exiting_wave_id".into(),
|
||||
251 => "src_vccz".into(),
|
||||
252 => "src_execz".into(),
|
||||
253 => "src_scc".into(),
|
||||
254 => "src_lds_direct".into(),
|
||||
_ => format!("<src {code}>"),
|
||||
}
|
||||
}
|
||||
|
||||
fn join(ops: impl IntoIterator<Item = String>) -> String {
|
||||
ops.into_iter().collect::<Vec<_>>().join(", ")
|
||||
}
|
||||
|
||||
fn operands(inst: &Instruction, name: &str, fields: &Fields) -> String {
|
||||
let mut out = String::new();
|
||||
match fields {
|
||||
Fields::Sop { dst, src, imm } => {
|
||||
let regs = join(dst.iter().chain(src).map(|o| o.to_string()));
|
||||
out = match (name, imm) {
|
||||
("s_getreg_b32", Some(imm)) => format!("{regs}, {}", hwreg(*imm)),
|
||||
("s_setreg_b32" | "s_setreg_imm32_b32", Some(imm)) => {
|
||||
format!("{}, {regs}", hwreg(*imm))
|
||||
}
|
||||
("s_call_b64", Some(imm)) => format!("{regs}, {}", label(inst, *imm)),
|
||||
(_, Some(imm)) if regs.is_empty() => format!("0x{imm:04x}"),
|
||||
(_, Some(imm)) => format!("{regs}, 0x{imm:04x}"),
|
||||
(_, None) => regs,
|
||||
};
|
||||
}
|
||||
Fields::Sopp { imm } => {
|
||||
out = match name {
|
||||
"s_endpgm"
|
||||
| "s_barrier"
|
||||
| "s_code_end"
|
||||
| "s_endpgm_saved"
|
||||
| "s_endpgm_ordered_ps_done"
|
||||
| "s_wakeup"
|
||||
| "s_icache_inv"
|
||||
| "s_ttracedata" => String::new(),
|
||||
"s_branch" => label(inst, *imm),
|
||||
n if n.starts_with("s_cbranch_") => label(inst, *imm),
|
||||
"s_waitcnt" => waitcnt(*imm),
|
||||
"s_sendmsg" | "s_sendmsghalt" => sendmsg(*imm),
|
||||
_ => format!("0x{imm:04x}"),
|
||||
};
|
||||
}
|
||||
Fields::Smem {
|
||||
data,
|
||||
base,
|
||||
offset,
|
||||
soffset,
|
||||
cache,
|
||||
} => {
|
||||
if let Some(data) = data {
|
||||
let off = match (soffset, offset) {
|
||||
(Operand::Scalar { code: NULL, .. }, 0) => soffset.to_string(),
|
||||
(Operand::Scalar { code: NULL, .. }, _) => {
|
||||
format!("0x{:06x}", offset & 0x1F_FFFF)
|
||||
}
|
||||
(_, 0) => soffset.to_string(),
|
||||
_ => format!("{soffset} offset:0x{:06x}", offset & 0x1F_FFFF),
|
||||
};
|
||||
out = format!("{data}, {base}, {off}");
|
||||
}
|
||||
flags(&mut out, cache, false);
|
||||
}
|
||||
Fields::Valu(v) => out = valu(name, v, inst.encoding),
|
||||
Fields::Vintrp { dst, src, attr } => {
|
||||
let src = match (name, src) {
|
||||
("v_interp_mov_f32", Operand::Const(p)) => ["p10", "p20", "p0"]
|
||||
.get(usize::from(*p))
|
||||
.map_or("p?".into(), |p| p.to_string()),
|
||||
_ => src.to_string(),
|
||||
};
|
||||
out = format!("{dst}, {src}, {attr}");
|
||||
}
|
||||
Fields::Ds {
|
||||
dst,
|
||||
addr,
|
||||
data,
|
||||
offset0,
|
||||
offset1,
|
||||
gds,
|
||||
} => {
|
||||
out = join(dst.iter().chain(addr).chain(data).map(|o| o.to_string()));
|
||||
if super::fields::ds_pair(name) {
|
||||
if *offset0 != 0 {
|
||||
let _ = write!(out, " offset0:{offset0}");
|
||||
}
|
||||
if *offset1 != 0 {
|
||||
let _ = write!(out, " offset1:{offset1}");
|
||||
}
|
||||
} else {
|
||||
let offset = u16::from(*offset1) << 8 | u16::from(*offset0);
|
||||
if offset != 0 {
|
||||
let _ = write!(out, " offset:{offset}");
|
||||
}
|
||||
}
|
||||
if *gds {
|
||||
out.push_str(" gds");
|
||||
}
|
||||
}
|
||||
Fields::Buffer {
|
||||
data,
|
||||
addr,
|
||||
rsrc,
|
||||
soffset,
|
||||
offset,
|
||||
offen,
|
||||
idxen,
|
||||
format,
|
||||
lds,
|
||||
tfe,
|
||||
cache,
|
||||
} => {
|
||||
if let Some(data) = data {
|
||||
out = format!("{data}, {addr}, {rsrc}, {soffset}");
|
||||
if *idxen {
|
||||
out.push_str(" idxen");
|
||||
}
|
||||
if *offen {
|
||||
out.push_str(" offen");
|
||||
}
|
||||
if *offset != 0 {
|
||||
let _ = write!(out, " offset:{offset}");
|
||||
}
|
||||
if let Some(format) = format {
|
||||
let _ = write!(out, " format:[{}]", buffer_format(*format));
|
||||
}
|
||||
}
|
||||
flags(&mut out, cache, false);
|
||||
if *lds {
|
||||
out.push_str(" lds");
|
||||
}
|
||||
if *tfe {
|
||||
out.push_str(" tfe");
|
||||
}
|
||||
}
|
||||
Fields::Image {
|
||||
data,
|
||||
addr,
|
||||
rsrc,
|
||||
sampler,
|
||||
dmask,
|
||||
dim,
|
||||
unorm,
|
||||
r128,
|
||||
a16,
|
||||
d16,
|
||||
tfe,
|
||||
lwe,
|
||||
cache,
|
||||
} => {
|
||||
let addr = match addr.as_slice() {
|
||||
[one] => one.to_string(),
|
||||
many => format!(
|
||||
"[{}]",
|
||||
many.iter()
|
||||
.map(|o| o.to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.join(",")
|
||||
),
|
||||
};
|
||||
out = join(
|
||||
[data.to_string(), addr, rsrc.to_string()]
|
||||
.into_iter()
|
||||
.chain(sampler.map(|s| s.to_string())),
|
||||
);
|
||||
if *dmask != 1 {
|
||||
let _ = write!(out, " dmask:0x{dmask:x}");
|
||||
}
|
||||
let dims = [
|
||||
"1D",
|
||||
"2D",
|
||||
"3D",
|
||||
"CUBE",
|
||||
"1D_ARRAY",
|
||||
"2D_ARRAY",
|
||||
"2D_MSAA",
|
||||
"2D_MSAA_ARRAY",
|
||||
];
|
||||
let _ = write!(out, " dim:SQ_RSRC_IMG_{}", dims[usize::from(*dim & 7)]);
|
||||
for (on, text) in [(*r128, "r128"), (*unorm, "unorm")] {
|
||||
if on {
|
||||
out.push(' ');
|
||||
out.push_str(text);
|
||||
}
|
||||
}
|
||||
flags(&mut out, cache, true);
|
||||
for (on, text) in [(*a16, "a16"), (*d16, "d16"), (*tfe, "tfe"), (*lwe, "lwe")] {
|
||||
if on {
|
||||
out.push(' ');
|
||||
out.push_str(text);
|
||||
}
|
||||
}
|
||||
}
|
||||
Fields::Flat {
|
||||
dst,
|
||||
addr,
|
||||
data,
|
||||
saddr,
|
||||
offset,
|
||||
lds,
|
||||
cache,
|
||||
} => {
|
||||
let addr = addr.map_or("off".into(), |a| a.to_string());
|
||||
out = join(
|
||||
dst.iter()
|
||||
.map(|o| o.to_string())
|
||||
.chain([addr])
|
||||
.chain(data.iter().chain(saddr).map(|o| o.to_string())),
|
||||
);
|
||||
if *offset != 0 {
|
||||
let _ = write!(out, " inst_offset:{offset}");
|
||||
}
|
||||
flags(&mut out, cache, false);
|
||||
if *lds {
|
||||
out.push_str(" lds");
|
||||
}
|
||||
}
|
||||
Fields::Exp {
|
||||
target,
|
||||
src,
|
||||
compr,
|
||||
done,
|
||||
vm,
|
||||
} => {
|
||||
let target = match *target {
|
||||
0..=7 => format!("mrt{target}"),
|
||||
8 => "mrtz".into(),
|
||||
9 => "null".into(),
|
||||
12..=15 => format!("pos{}", target - 12),
|
||||
20 => "prim".into(),
|
||||
32..=63 => format!("param{}", target - 32),
|
||||
_ => format!("<target {target}>"),
|
||||
};
|
||||
out = join(
|
||||
[target].into_iter().chain(
|
||||
src.iter()
|
||||
.map(|s| s.map_or("off".into(), |o| o.to_string())),
|
||||
),
|
||||
);
|
||||
for (on, text) in [(*done, " done"), (*compr, " compr"), (*vm, " vm")] {
|
||||
if on {
|
||||
out.push_str(text);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Cache flags; images write `dlc` first.
|
||||
fn flags(out: &mut String, cache: &Cache, dlc_first: bool) {
|
||||
let dlc = (cache.dlc, " dlc");
|
||||
let (first, last) = if dlc_first {
|
||||
(dlc, (false, ""))
|
||||
} else {
|
||||
((false, ""), dlc)
|
||||
};
|
||||
for (on, text) in [first, (cache.glc, " glc"), (cache.slc, " slc"), last] {
|
||||
if on {
|
||||
out.push_str(text);
|
||||
}
|
||||
}
|
||||
if out.starts_with(' ') {
|
||||
out.remove(0);
|
||||
}
|
||||
}
|
||||
|
||||
fn label(inst: &Instruction, imm: u16) -> String {
|
||||
let target = inst.offset as i64 + 4 * inst.words.len() as i64 + 4 * i64::from(imm as i16);
|
||||
format!("label_{target:04X}")
|
||||
}
|
||||
|
||||
fn hwreg(imm: u16) -> String {
|
||||
let (id, offset, size) = (imm & 0x3F, imm >> 6 & 0x1F, (imm >> 11 & 0x1F) + 1);
|
||||
let name = match id {
|
||||
1 => "HW_REG_MODE".into(),
|
||||
20 => "HW_REG_SHADER_FLAT_SCRATCH_LO".into(),
|
||||
21 => "HW_REG_SHADER_FLAT_SCRATCH_HI".into(),
|
||||
25 => "HW_REG_POPS_PACKER".into(),
|
||||
_ => id.to_string(),
|
||||
};
|
||||
if offset == 0 && size == 32 {
|
||||
format!("hwreg({name})")
|
||||
} else {
|
||||
format!("hwreg({name}, {offset}, {size})")
|
||||
}
|
||||
}
|
||||
|
||||
fn waitcnt(imm: u16) -> String {
|
||||
let vm = imm & 0xF | (imm >> 14) << 4;
|
||||
let exp = imm >> 4 & 7;
|
||||
let lgkm = imm >> 8 & 0x3F;
|
||||
let mut parts = Vec::new();
|
||||
if vm != 0x3F {
|
||||
parts.push(format!("vmcnt({vm})"));
|
||||
}
|
||||
if exp != 7 {
|
||||
parts.push(format!("expcnt({exp})"));
|
||||
}
|
||||
if lgkm != 0x3F {
|
||||
parts.push(format!("lgkmcnt({lgkm})"));
|
||||
}
|
||||
if matches!(parts.len(), 0 | 3) {
|
||||
return format!("0x{imm:04x}");
|
||||
}
|
||||
parts.join(" & ")
|
||||
}
|
||||
|
||||
fn sendmsg(imm: u16) -> String {
|
||||
let (msg, op, stream) = (imm & 0xF, imm >> 4 & 7, imm >> 8 & 3);
|
||||
let msg_name = match msg {
|
||||
2 => "MSG_GS".into(),
|
||||
3 => "MSG_GS_DONE".into(),
|
||||
7 => "MSG_ORDERED_PS_DONE".into(),
|
||||
9 => "MSG_GS_ALLOC_REQ".into(),
|
||||
_ => msg.to_string(),
|
||||
};
|
||||
let op_name = ["GS_OP_NOP", "GS_OP_CUT", "GS_OP_EMIT", "GS_OP_EMIT_CUT"]
|
||||
.get(usize::from(op))
|
||||
.map_or(op.to_string(), |s| s.to_string());
|
||||
if msg == 3 && op == 0 {
|
||||
format!("sendmsg({msg_name}, {op_name})")
|
||||
} else {
|
||||
format!("sendmsg({msg_name}, {op_name}, {stream})")
|
||||
}
|
||||
}
|
||||
|
||||
fn buffer_format(format: u8) -> String {
|
||||
const NAMES: [&str; 78] = [
|
||||
"INVALID",
|
||||
"8_UNORM",
|
||||
"8_SNORM",
|
||||
"8_USCALED",
|
||||
"8_SSCALED",
|
||||
"8_UINT",
|
||||
"8_SINT",
|
||||
"16_UNORM",
|
||||
"16_SNORM",
|
||||
"16_USCALED",
|
||||
"16_SSCALED",
|
||||
"16_UINT",
|
||||
"16_SINT",
|
||||
"16_FLOAT",
|
||||
"8_8_UNORM",
|
||||
"8_8_SNORM",
|
||||
"8_8_USCALED",
|
||||
"8_8_SSCALED",
|
||||
"8_8_UINT",
|
||||
"8_8_SINT",
|
||||
"32_UINT",
|
||||
"32_SINT",
|
||||
"32_FLOAT",
|
||||
"16_16_UNORM",
|
||||
"16_16_SNORM",
|
||||
"16_16_USCALED",
|
||||
"16_16_SSCALED",
|
||||
"16_16_UINT",
|
||||
"16_16_SINT",
|
||||
"16_16_FLOAT",
|
||||
"10_11_11_UNORM",
|
||||
"10_11_11_SNORM",
|
||||
"10_11_11_USCALED",
|
||||
"10_11_11_SSCALED",
|
||||
"10_11_11_UINT",
|
||||
"10_11_11_SINT",
|
||||
"10_11_11_FLOAT",
|
||||
"11_11_10_UNORM",
|
||||
"11_11_10_SNORM",
|
||||
"11_11_10_USCALED",
|
||||
"11_11_10_SSCALED",
|
||||
"11_11_10_UINT",
|
||||
"11_11_10_SINT",
|
||||
"11_11_10_FLOAT",
|
||||
"10_10_10_2_UNORM",
|
||||
"10_10_10_2_SNORM",
|
||||
"10_10_10_2_USCALED",
|
||||
"10_10_10_2_SSCALED",
|
||||
"10_10_10_2_UINT",
|
||||
"10_10_10_2_SINT",
|
||||
"2_10_10_10_UNORM",
|
||||
"2_10_10_10_SNORM",
|
||||
"2_10_10_10_USCALED",
|
||||
"2_10_10_10_SSCALED",
|
||||
"2_10_10_10_UINT",
|
||||
"2_10_10_10_SINT",
|
||||
"8_8_8_8_UNORM",
|
||||
"8_8_8_8_SNORM",
|
||||
"8_8_8_8_USCALED",
|
||||
"8_8_8_8_SSCALED",
|
||||
"8_8_8_8_UINT",
|
||||
"8_8_8_8_SINT",
|
||||
"32_32_UINT",
|
||||
"32_32_SINT",
|
||||
"32_32_FLOAT",
|
||||
"16_16_16_16_UNORM",
|
||||
"16_16_16_16_SNORM",
|
||||
"16_16_16_16_USCALED",
|
||||
"16_16_16_16_SSCALED",
|
||||
"16_16_16_16_UINT",
|
||||
"16_16_16_16_SINT",
|
||||
"16_16_16_16_FLOAT",
|
||||
"32_32_32_UINT",
|
||||
"32_32_32_SINT",
|
||||
"32_32_32_FLOAT",
|
||||
"32_32_32_32_UINT",
|
||||
"32_32_32_32_SINT",
|
||||
"32_32_32_32_FLOAT",
|
||||
];
|
||||
NAMES
|
||||
.get(usize::from(format))
|
||||
.map_or(format!("{format}"), |n| format!("BUF_FMT_{n}"))
|
||||
}
|
||||
|
||||
fn valu(name: &str, v: &Valu, encoding: Encoding) -> String {
|
||||
let bit = |mask: u8, i: usize| mask >> i & 1 != 0;
|
||||
let mix = name.starts_with("v_fma_mix");
|
||||
let src = |i: usize| {
|
||||
let o = v.src[i];
|
||||
let mut s = o.to_string();
|
||||
if let Some(sdwa) = v.sdwa
|
||||
&& bit(sdwa.sext, i)
|
||||
{
|
||||
s = format!("sext({s})");
|
||||
}
|
||||
if encoding == Encoding::Vop3p {
|
||||
if mix {
|
||||
if bit(v.opsel_hi, i) {
|
||||
s = format!("{}({s})", if bit(v.opsel, i) { "sel_hi" } else { "sel_lo" });
|
||||
}
|
||||
if bit(v.neg_hi, i) {
|
||||
s = format!("abs({s})");
|
||||
}
|
||||
if bit(v.neg, i) {
|
||||
s = format!("-{s}");
|
||||
}
|
||||
} else {
|
||||
if bit(v.neg, i) && bit(v.neg_hi, i) {
|
||||
s = format!("-{s}");
|
||||
}
|
||||
match (bit(v.opsel, i), bit(v.opsel_hi, i)) {
|
||||
(false, true) => {}
|
||||
(false, false) => s = format!("sel_lo({s})"),
|
||||
(true, true) => s = format!("sel_hi({s})"),
|
||||
(true, false) => s = format!("sel_hi_lo({s})"),
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if bit(v.abs, i) {
|
||||
s = format!("abs({s})");
|
||||
}
|
||||
if bit(v.neg, i) {
|
||||
s = format!("-{s}");
|
||||
}
|
||||
// v_permlane*: the opsel bits are fi and bound_ctrl.
|
||||
if bit(v.opsel, i) && !name.starts_with("v_permlane") {
|
||||
s = format!("sel_hi({s})");
|
||||
}
|
||||
}
|
||||
s
|
||||
};
|
||||
let mut ops: Vec<String> = v
|
||||
.dst
|
||||
.iter()
|
||||
.chain(&v.carry)
|
||||
.map(|o| o.to_string())
|
||||
.collect();
|
||||
let mut order: Vec<usize> = (0..v.src.len()).collect();
|
||||
if name.starts_with("v_interp_") && order.len() > 1 {
|
||||
// dst, i/j, attribute, then the p1 result for p2.
|
||||
order.swap(0, 1);
|
||||
}
|
||||
ops.extend(order.into_iter().map(src));
|
||||
let mut out = ops.join(", ");
|
||||
let mut suffix = |s: &str| {
|
||||
out.push(' ');
|
||||
out.push_str(s);
|
||||
};
|
||||
if let Some(Operand::Attr { high: true, .. }) = v.src.first() {
|
||||
suffix("high");
|
||||
}
|
||||
let omod = ["", "mul:2", "mul:4", "div:2"][usize::from(v.omod & 3)];
|
||||
if name.starts_with("v_permlane") {
|
||||
if v.opsel & 1 != 0 {
|
||||
suffix("fi:1");
|
||||
}
|
||||
if v.opsel & 2 != 0 {
|
||||
suffix("bound_ctrl:1");
|
||||
}
|
||||
}
|
||||
if let Some(sdwa) = v.sdwa {
|
||||
if v.clamp {
|
||||
suffix("clamp");
|
||||
}
|
||||
if !omod.is_empty() {
|
||||
suffix(omod);
|
||||
}
|
||||
let sel = [
|
||||
"BYTE_0", "BYTE_1", "BYTE_2", "BYTE_3", "WORD_0", "WORD_1", "DWORD", "?",
|
||||
];
|
||||
if sdwa.dst_sel != 6 {
|
||||
suffix(&format!("dst_sel:{}", sel[usize::from(sdwa.dst_sel & 7)]));
|
||||
}
|
||||
if sdwa.dst_unused != 0 {
|
||||
let unused = ["UNUSED_PAD", "UNUSED_SEXT", "UNUSED_PRESERVE", "?"];
|
||||
suffix(&format!(
|
||||
"dst_unused:{}",
|
||||
unused[usize::from(sdwa.dst_unused & 3)]
|
||||
));
|
||||
}
|
||||
for (i, s) in sdwa.src_sel.iter().enumerate() {
|
||||
if *s != 6 {
|
||||
suffix(&format!("src{i}_sel:{}", sel[usize::from(s & 7)]));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if !omod.is_empty() {
|
||||
suffix(omod);
|
||||
}
|
||||
if v.clamp {
|
||||
suffix("clamp");
|
||||
}
|
||||
}
|
||||
match v.dpp {
|
||||
Some(Dpp::Row {
|
||||
ctrl,
|
||||
row_mask,
|
||||
bank_mask,
|
||||
bound_ctrl,
|
||||
fi,
|
||||
}) => {
|
||||
suffix(&match ctrl {
|
||||
0x000..=0x0FF => format!(
|
||||
"quad_perm:[{},{},{},{}]",
|
||||
ctrl & 3,
|
||||
ctrl >> 2 & 3,
|
||||
ctrl >> 4 & 3,
|
||||
ctrl >> 6 & 3
|
||||
),
|
||||
0x101..=0x10F => format!("row_shl:{}", ctrl & 0xF),
|
||||
0x111..=0x11F => format!("row_shr:{}", ctrl & 0xF),
|
||||
0x121..=0x12F => format!("row_ror:{}", ctrl & 0xF),
|
||||
0x140 => "row_mirror".into(),
|
||||
0x141 => "row_half_mirror".into(),
|
||||
0x150..=0x15F => format!("row_share:{}", ctrl & 0xF),
|
||||
0x160..=0x16F => format!("row_xmask:{}", ctrl & 0xF),
|
||||
_ => format!("dpp_ctrl:0x{ctrl:x}"),
|
||||
});
|
||||
if row_mask != 0xF {
|
||||
suffix(&format!("row_mask:0x{row_mask:x}"));
|
||||
}
|
||||
if bank_mask != 0xF {
|
||||
suffix(&format!("bank_mask:0x{bank_mask:x}"));
|
||||
}
|
||||
if bound_ctrl {
|
||||
suffix("bound_ctrl:1");
|
||||
}
|
||||
if fi {
|
||||
suffix("fi:1");
|
||||
}
|
||||
}
|
||||
Some(Dpp::Lanes { sel, fi }) => {
|
||||
let lanes: Vec<String> = (0..8).map(|i| (sel >> (3 * i) & 7).to_string()).collect();
|
||||
suffix(&format!("dpp8:[{}]", lanes.join(",")));
|
||||
if fi {
|
||||
suffix("fi:1");
|
||||
}
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::gfx10::{Fields, Operand, decode};
|
||||
|
||||
/// Text of each instruction in `words` (a straight-line program).
|
||||
fn texts(words: &[u32], wave64: bool) -> Vec<String> {
|
||||
let mut code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
|
||||
code.extend(0xBF81_0000u32.to_le_bytes()); // s_endpgm
|
||||
let insts = decode(&code).unwrap();
|
||||
insts[..insts.len() - 1]
|
||||
.iter()
|
||||
.map(|i| i.text(wave64))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn one(words: &[u32], wave64: bool) -> String {
|
||||
let t = texts(words, wave64);
|
||||
assert_eq!(t.len(), 1, "{t:?}");
|
||||
t[0].clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar() {
|
||||
assert_eq!(
|
||||
texts(&[0xBF88_0001, 0xBF8C_0070, 0xBE80_03FF, 0x1234_5678], true),
|
||||
[
|
||||
"s_cbranch_execz label_0008",
|
||||
"s_waitcnt vmcnt(0) & lgkmcnt(0)",
|
||||
"s_mov_b32 s0, lit(0x12345678)",
|
||||
]
|
||||
);
|
||||
assert_eq!(one(&[0x8782_027E], true), "s_and_b64 s[2:3], exec, s[2:3]");
|
||||
assert_eq!(
|
||||
one(&[0xF408_0501, 0xFA00_0040], true),
|
||||
"s_load_dwordx4 s[20:23], s[2:3], 0x000040"
|
||||
);
|
||||
assert_eq!(
|
||||
one(&[0xF420_0144, 0x0400_0000], true),
|
||||
"s_buffer_load_dword s5, s[8:11], s2"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lane_masks_follow_the_wave_size() {
|
||||
let cmp = [0x7C08_06F0]; // v_cmp_gt_f32 with 0.5 and v3
|
||||
assert_eq!(one(&cmp, false), "v_cmp_gt_f32 vcc_lo, 0.5, v3");
|
||||
assert_eq!(one(&cmp, true), "v_cmp_gt_f32 vcc, 0.5, v3");
|
||||
let vop3 = [0xD401_0106, 0x0001_E501]; // v_cmp_lt_f32 to s6, |v1| < 1.0
|
||||
assert_eq!(one(&vop3, false), "v_cmp_lt_f32 s6, abs(v1), 1.0");
|
||||
assert_eq!(one(&vop3, true), "v_cmp_lt_f32 s[6:7], abs(v1), 1.0");
|
||||
assert_eq!(
|
||||
one(&[0x0202_0480], false),
|
||||
"v_cndmask_b32 v1, 0, v2, vcc_lo"
|
||||
);
|
||||
assert_eq!(
|
||||
one(&[0x5006_0801], true),
|
||||
"v_add_co_ci_u32 v3, vcc, s1, v4, vcc"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vector_modifiers() {
|
||||
assert_eq!(
|
||||
one(&[0x1004_0AFF, 0x3F00_0001], true),
|
||||
"v_mul_f32 v2, lit(0x3f000001), v5"
|
||||
);
|
||||
assert_eq!(
|
||||
one(&[0xD54B_8004, 0x2BC0_0501], true),
|
||||
"v_fma_f32 v4, -v1, s2, 0.5 mul:2 clamp"
|
||||
);
|
||||
assert_eq!(
|
||||
one(&[0x7E02_16F9, 0x0605_0602], true),
|
||||
"v_cvt_f32_f16 v1, v2 src0_sel:WORD_1"
|
||||
);
|
||||
assert_eq!(
|
||||
one(&[0x7E06_02E9, 0x0539_7701], true),
|
||||
"v_mov_b32 v3, v1 dpp8:[7,6,5,4,3,2,1,0]"
|
||||
);
|
||||
assert_eq!(
|
||||
one(&[0x7E0A_02FA, 0xFF08_B106], true),
|
||||
"v_mov_b32 v5, v6 quad_perm:[1,0,3,2] bound_ctrl:1"
|
||||
);
|
||||
assert_eq!(
|
||||
one(&[0xCC20_0C01, 0x2C10_0702], true),
|
||||
"v_fma_mix_f32 v1, -sel_hi(v2), s3, abs(v4)"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn memory_and_export() {
|
||||
assert_eq!(
|
||||
one(&[0xE034_7010, 0x0102_0402], true),
|
||||
"buffer_load_dwordx2 v[4:5], v[2:3], s[8:11], s1 idxen offen offset:16 glc"
|
||||
);
|
||||
assert_eq!(
|
||||
one(&[0xD8DC_0302, 0x0600_0001], true),
|
||||
"ds_read2_b32 v[6:7], v1 offset0:2 offset1:3"
|
||||
);
|
||||
assert_eq!(
|
||||
one(&[0xF800_1C0F, 0x0000_0302], true),
|
||||
"exp mrt0, v2, v2, v3, v3 done compr vm"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_d16_data_is_packed() {
|
||||
// Three f16 channels occupy two VGPRs; NSA lists the addresses.
|
||||
let words = [0xF09C_070A, 0x8024_0801, 0x0000_0005];
|
||||
assert_eq!(
|
||||
one(&words, true),
|
||||
"image_sample_lz v[8:9], [v1,v5], s[16:23], s[4:7] dmask:0x7 dim:SQ_RSRC_IMG_2D d16"
|
||||
);
|
||||
let code: Vec<u8> = words
|
||||
.iter()
|
||||
.chain(&[0xBF81_0000])
|
||||
.flat_map(|w| w.to_le_bytes())
|
||||
.collect();
|
||||
let Fields::Image { data, addr, .. } = decode(&code).unwrap()[0].fields(true) else {
|
||||
panic!("not an image instruction");
|
||||
};
|
||||
assert_eq!(data, Operand::Vector { reg: 8, dwords: 2 });
|
||||
assert_eq!(addr.len(), 2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,826 @@
|
||||
//! I/O raising (decision 0003): what a program's input registers, its
|
||||
//! interpolation and its exports mean.
|
||||
//!
|
||||
//! Pixel shaders get the VGPRs `SPI_PS_INPUT_ADDR` enables, in a fixed
|
||||
//! order (barycentrics, then position, front face...). `v_interp_p1` and
|
||||
//! `v_interp_p2` (and their f16 forms) evaluate an attribute from a pair of
|
||||
//! barycentrics; `v_interp_mov` reads one vertex's value. After the 32-bit
|
||||
//! export patch ([`NativeProgram::patched_code`]) exports carry plain
|
||||
//! 32-bit values: `mrt<n>` is render target n, `mrtz` depth, stencil and
|
||||
//! sample mask, `null` nothing. A lane whose EXEC bit is clear at the
|
||||
//! export that ends the program (`done`) is discarded: that export's guard
|
||||
//! after structurisation.
|
||||
//!
|
||||
//! Vertex shaders that run as the hardware VS get the vertex id in v0, the
|
||||
//! primitive id in v2 and the instance id in v3; the fetch shader loads
|
||||
//! channel k of each attribute into its VGPR + k. `exp pos0` is the
|
||||
//! position, `exp param<n>` the output with parameter n.
|
||||
//!
|
||||
//! Attributes and outputs are named by their row: a register of the
|
||||
//! container's signature part.
|
||||
//!
|
||||
//! Compute programs get the thread id in the group in v0-v2 and the group
|
||||
//! id in the SGPRs after the user data, as `COMPUTE_PGM_RSRC2` enables them.
|
||||
//!
|
||||
//! Mesh programs run as one NGG stage. The program computes its thread
|
||||
//! index from the wave index (s3 bits 24-27) and the lane (`v_mbcnt`), and
|
||||
//! its group id from v5 of the first lane (`v_readfirstlane`: the group
|
||||
//! times the group size). Lane n exports vertex n (`exp pos`, `exp param`)
|
||||
//! and primitive n (`exp prim`: 10-bit vertex indices at bits 0, 10, 20,
|
||||
//! bit 31 culls); `param` entries with bit 7 are per-primitive outputs. One
|
||||
//! lane sends the output counts (`s_sendmsg` GS_ALLOC_REQ, m0 = vertices |
|
||||
//! primitives << 12).
|
||||
|
||||
use crate::ShaderError;
|
||||
use crate::gfx10::{Fields, Operand};
|
||||
use crate::ir::{Exit, Inst, Program, Reg, Value, operand_reads};
|
||||
use crate::native::{HwStage, NativeProgram, PsInput, StageIo, Usage};
|
||||
use crate::resource::Site;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Input {
|
||||
VertexId,
|
||||
PrimitiveId,
|
||||
InstanceId,
|
||||
/// A vertex attribute the fetch shader loads.
|
||||
Attribute {
|
||||
row: u8,
|
||||
channel: u8,
|
||||
},
|
||||
/// `index` 0 is i, 1 is j (2 the pull model's w).
|
||||
Barycentric {
|
||||
kind: Barycentric,
|
||||
index: u8,
|
||||
},
|
||||
/// Pixel position channel (0-3: x, y, z, w).
|
||||
Position(u8),
|
||||
FrontFace,
|
||||
/// Sample id and other bits.
|
||||
Ancillary,
|
||||
SampleCoverage,
|
||||
FixedPosition,
|
||||
LineStipple,
|
||||
/// Compute: thread-group id component (an SGPR).
|
||||
GroupId(u8),
|
||||
/// Compute: thread id within the group, component (a VGPR).
|
||||
ThreadIdInGroup(u8),
|
||||
/// Compute: the thread-group info SGPR (wave index and count).
|
||||
GroupInfo,
|
||||
/// Mesh: v5, the group id times the group size (read as uniform).
|
||||
MeshGroup,
|
||||
/// Mesh: s3, the wave's index in the group in bits 24-27.
|
||||
MergedWaveInfo,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Barycentric {
|
||||
PerspectiveSample,
|
||||
PerspectiveCenter,
|
||||
PerspectiveCentroid,
|
||||
PerspectivePullModel,
|
||||
LinearSample,
|
||||
LinearCenter,
|
||||
LinearCentroid,
|
||||
}
|
||||
|
||||
/// The pixel input VGPRs in hardware order: one entry per
|
||||
/// `SPI_PS_INPUT_ADDR` bit.
|
||||
const PS_VGPRS: [(u8, Option<Barycentric>); 16] = [
|
||||
(2, Some(Barycentric::PerspectiveSample)),
|
||||
(2, Some(Barycentric::PerspectiveCenter)),
|
||||
(2, Some(Barycentric::PerspectiveCentroid)),
|
||||
(3, Some(Barycentric::PerspectivePullModel)),
|
||||
(2, Some(Barycentric::LinearSample)),
|
||||
(2, Some(Barycentric::LinearCenter)),
|
||||
(2, Some(Barycentric::LinearCentroid)),
|
||||
(1, None), // line stipple
|
||||
(1, None), // position x
|
||||
(1, None), // y
|
||||
(1, None), // z
|
||||
(1, None), // w
|
||||
(1, None), // front face
|
||||
(1, None), // ancillary
|
||||
(1, None), // sample coverage
|
||||
(1, None), // fixed-point position
|
||||
];
|
||||
|
||||
fn ps_system(bit: usize) -> Input {
|
||||
match bit {
|
||||
7 => Input::LineStipple,
|
||||
8..=11 => Input::Position(bit as u8 - 8),
|
||||
12 => Input::FrontFace,
|
||||
13 => Input::Ancillary,
|
||||
14 => Input::SampleCoverage,
|
||||
_ => Input::FixedPosition,
|
||||
}
|
||||
}
|
||||
|
||||
/// An attribute channel of the input signature.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Attribute {
|
||||
pub usage: Usage,
|
||||
pub row: u8,
|
||||
pub channel: u8,
|
||||
/// The upper f16 half of the channel (packed fp16 inputs).
|
||||
pub high: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Interp {
|
||||
/// This site's result (`v_interp_p2*`) is the attribute interpolated
|
||||
/// with `barycentric`; `first` are the `v_interp_p1*` halves it
|
||||
/// completes (one per path where the compiler shares a first half).
|
||||
Interpolated {
|
||||
attribute: Attribute,
|
||||
barycentric: Barycentric,
|
||||
first: Vec<Site>,
|
||||
},
|
||||
/// One vertex's value (`v_interp_mov_f32`), as encoded: 0 for P10,
|
||||
/// 1 for P20, 2 for P0 (the provoking vertex).
|
||||
Vertex { attribute: Attribute, vertex: u8 },
|
||||
/// A half of an interpolation whose i or j is computed rather than
|
||||
/// loaded: each half evaluates as the hardware does, from the
|
||||
/// attribute's vertex values (`v_interp_p1*`: P0 + i P10, with P10 =
|
||||
/// P1 - P0; `v_interp_p2*`: its old dst + j P20, with P20 = P2 - P0).
|
||||
Weighted { attribute: Attribute },
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Target {
|
||||
Color(u8),
|
||||
/// Depth, stencil, sample mask (channels as `DB_SHADER_CONTROL` enables).
|
||||
Depth,
|
||||
Null,
|
||||
Position(u8),
|
||||
Param {
|
||||
usage: Usage,
|
||||
row: u8,
|
||||
},
|
||||
/// `param0` of a vertex shader without outputs: the hardware wants one
|
||||
/// parameter export regardless.
|
||||
Unread,
|
||||
/// The primitive export of a merged or mesh stage.
|
||||
Primitive,
|
||||
/// A mesh program's per-primitive output (a row of `PSG1`).
|
||||
PrimitiveParam {
|
||||
usage: Usage,
|
||||
row: u8,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Export {
|
||||
pub site: Site,
|
||||
pub target: Target,
|
||||
/// Per channel, as the instruction enables them.
|
||||
pub values: [Option<Value>; 4],
|
||||
/// Two f16 values per dword.
|
||||
pub compressed: bool,
|
||||
/// The program's last export (for pixels: kills the lanes not in EXEC).
|
||||
pub done: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct Io {
|
||||
/// Input values the hardware loads, with their meaning; other VGPRs
|
||||
/// read before written hold undefined values.
|
||||
pub inputs: Vec<(Value, Input)>,
|
||||
pub interps: Vec<(Site, Interp)>,
|
||||
pub exports: Vec<Export>,
|
||||
/// Compute: how many SGPRs the hardware initializes
|
||||
/// ([`ComputeIo::initialized_sgprs`](crate::native::ComputeIo::initialized_sgprs)).
|
||||
pub initialized_sgprs: Option<u8>,
|
||||
}
|
||||
|
||||
/// Raises the I/O of `p`, built from `native`'s patched code. Fails for
|
||||
/// stages whose stage data is not read and on constructs not covered yet.
|
||||
pub fn raise(p: &Program, native: &NativeProgram) -> Result<Io, ShaderError> {
|
||||
let unsupported = |offset, what| ShaderError::Unsupported { offset, what };
|
||||
let (loaded, ps_inputs, params) = match (&native.io, native.stage) {
|
||||
(
|
||||
StageIo::Ps {
|
||||
inputs, input_addr, ..
|
||||
},
|
||||
HwStage::Ps,
|
||||
) => {
|
||||
// A pixel shader exports no parameters; `[]` never reaches `Unread`.
|
||||
let loaded = ps_vgprs(*input_addr)
|
||||
.into_iter()
|
||||
.map(|(r, i)| (Reg::V(r), i))
|
||||
.collect();
|
||||
(loaded, &inputs[..], &[][..])
|
||||
}
|
||||
(StageIo::Vs { inputs, outputs }, HwStage::Vs) => {
|
||||
let mut loaded = vec![
|
||||
(Reg::V(0), Input::VertexId),
|
||||
(Reg::V(2), Input::PrimitiveId),
|
||||
(Reg::V(3), Input::InstanceId),
|
||||
];
|
||||
for i in inputs {
|
||||
for channel in (0..4).filter(|c| i.mask >> c & 1 != 0) {
|
||||
let input = Input::Attribute {
|
||||
row: i.row,
|
||||
channel,
|
||||
};
|
||||
loaded.push((Reg::V(i.vgpr + channel), input));
|
||||
}
|
||||
}
|
||||
(loaded, &[][..], &outputs[..])
|
||||
}
|
||||
// Compute: thread ids in v0-v2, group ids and the group info in the
|
||||
// SGPRs after the user data.
|
||||
(StageIo::Cs(cs), HwStage::Cs) => {
|
||||
let (ids, info) = cs.system_sgprs();
|
||||
let mut loaded: Vec<(Reg, Input)> = (0..cs.thread_id_vgprs())
|
||||
.map(|c| (Reg::V(c), Input::ThreadIdInGroup(c)))
|
||||
.collect();
|
||||
for (c, s) in ids.into_iter().enumerate() {
|
||||
if let Some(s) = s {
|
||||
loaded.push((Reg::S(s), Input::GroupId(c as u8)));
|
||||
}
|
||||
}
|
||||
loaded.extend(info.map(|s| (Reg::S(s), Input::GroupInfo)));
|
||||
(loaded, &[][..], &[][..])
|
||||
}
|
||||
(StageIo::Ms(ms), HwStage::Ms) => {
|
||||
// The group input, and the phis that may carry it past a join.
|
||||
let mut group: Vec<Value> = p
|
||||
.inputs
|
||||
.iter()
|
||||
.filter(|i| i.0 == Reg::V(5))
|
||||
.map(|i| i.1)
|
||||
.collect();
|
||||
// No lane is active over the EXEC-zero edge of s_cbranch_execz or
|
||||
// _execnz, the same case as a partial-EXEC write below.
|
||||
let no_lanes = |q: usize, b: usize| match (
|
||||
p.blocks[q].insts.last().map(Inst::name),
|
||||
p.blocks[q].exit,
|
||||
) {
|
||||
(Some("s_cbranch_execz"), Exit::Branch { taken, not_taken }) => {
|
||||
taken == b && not_taken != b
|
||||
}
|
||||
(Some("s_cbranch_execnz"), Exit::Branch { taken, not_taken }) => {
|
||||
not_taken == b && taken != b
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
while let Some(v) = p
|
||||
.blocks
|
||||
.iter()
|
||||
.enumerate()
|
||||
.flat_map(|(b, k)| k.phis.iter().map(move |f| (b, f)))
|
||||
.find_map(|(b, f)| {
|
||||
let mut args = f.args.iter().zip(&p.blocks[b].preds);
|
||||
let carried = args.any(|(a, &q)| group.contains(a) && !no_lanes(q, b));
|
||||
(carried && !group.contains(&f.value)).then_some(f.value)
|
||||
})
|
||||
{
|
||||
group.push(v);
|
||||
}
|
||||
// The group input holds the same value in every lane only as the
|
||||
// first lane reads it. A write to v5 reads its old value too, which
|
||||
// only lanes outside EXEC keep.
|
||||
// shortcut: writes that may keep the old v5 in active lanes
|
||||
// (v_fmac_f32's accumulator, a 16-bit half or d16 load,
|
||||
// v_writelane_b32, v_movreld_b32, DPP that skips lanes) and
|
||||
// partial-EXEC writes pass; check those too if a mesh program
|
||||
// writes v5 that way.
|
||||
let per_lane = p.blocks.iter().flat_map(|b| &b.insts).find(|i| {
|
||||
i.read(Reg::V(5)).is_some_and(|v| group.contains(&v))
|
||||
&& i.name() != "v_readfirstlane_b32"
|
||||
&& (i.write(Reg::V(5)).is_none() || operand_reads(p, i).contains(&Reg::V(5)))
|
||||
});
|
||||
if let Some(i) = per_lane {
|
||||
return Err(unsupported(
|
||||
i.machine.offset,
|
||||
"the mesh group input read per lane",
|
||||
));
|
||||
}
|
||||
let loaded = vec![
|
||||
(Reg::V(5), Input::MeshGroup),
|
||||
(Reg::S(3), Input::MergedWaveInfo),
|
||||
];
|
||||
(loaded, &[][..], &ms.outputs[..])
|
||||
}
|
||||
_ => return Err(unsupported(0, "I/O of this stage")),
|
||||
};
|
||||
let inputs: Vec<(Value, Input)> = p
|
||||
.inputs
|
||||
.iter()
|
||||
.filter_map(|&(reg, v)| loaded.iter().find(|l| l.0 == reg).map(|l| (v, l.1)))
|
||||
.collect();
|
||||
let input_of = |v: Value| inputs.iter().find(|i| i.0 == v).map(|i| i.1);
|
||||
let attribute = |inst: &Inst, attr: &Operand| match *attr {
|
||||
Operand::Attr { index, chan, high } => ps_inputs
|
||||
.iter()
|
||||
.find(|i: &&PsInput| i.attr == index)
|
||||
.map(|i| Attribute {
|
||||
usage: i.usage,
|
||||
row: i.row,
|
||||
channel: chan,
|
||||
high,
|
||||
})
|
||||
.ok_or(unsupported(
|
||||
inst.machine.offset,
|
||||
"an interpolated attribute the stage data does not list",
|
||||
)),
|
||||
_ => Err(unsupported(inst.machine.offset, "an interpolation operand")),
|
||||
};
|
||||
// A VGPR value's barycentric kind and index, if it is one as loaded.
|
||||
let barycentric = |v: Option<Value>| match v.and_then(input_of) {
|
||||
Some(Input::Barycentric { kind, index }) => Some((kind, index)),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
let mut io = Io {
|
||||
inputs: inputs.clone(),
|
||||
initialized_sgprs: match &native.io {
|
||||
StageIo::Cs(cs) => Some(cs.initialized_sgprs()),
|
||||
_ => None,
|
||||
},
|
||||
..Io::default()
|
||||
};
|
||||
let defs: std::collections::HashMap<Value, Site> = p
|
||||
.blocks
|
||||
.iter()
|
||||
.enumerate()
|
||||
.flat_map(|(b, block)| {
|
||||
block
|
||||
.insts
|
||||
.iter()
|
||||
.enumerate()
|
||||
.flat_map(move |(i, inst)| inst.writes.iter().map(move |w| (w.1, (b, i))))
|
||||
})
|
||||
.collect();
|
||||
let phis: std::collections::HashMap<Value, (usize, usize)> = p
|
||||
.blocks
|
||||
.iter()
|
||||
.enumerate()
|
||||
.flat_map(|(b, block)| {
|
||||
block
|
||||
.phis
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(move |(i, phi)| (phi.value, (b, i)))
|
||||
})
|
||||
.collect();
|
||||
let halves = Halves {
|
||||
p,
|
||||
defs: &defs,
|
||||
phis: &phis,
|
||||
};
|
||||
for (b, block) in p.blocks.iter().enumerate() {
|
||||
for (i, inst) in block.insts.iter().enumerate() {
|
||||
let site = (b, i);
|
||||
let at = inst.machine.offset;
|
||||
let name = inst.name();
|
||||
match &inst.fields {
|
||||
Fields::Vintrp { dst, src, attr } => {
|
||||
let attribute = attribute(inst, attr)?;
|
||||
match (name, *src) {
|
||||
("v_interp_mov_f32", Operand::Const(vertex)) => {
|
||||
io.interps
|
||||
.push((site, Interp::Vertex { attribute, vertex }));
|
||||
}
|
||||
("v_interp_p1_f32", _) => {}
|
||||
("v_interp_p2_f32", Operand::Vector { reg, .. }) => {
|
||||
let Operand::Vector { reg: d, .. } = *dst else {
|
||||
return Err(unsupported(at, "an interpolation operand"));
|
||||
};
|
||||
// The first half's result is this one's old dst.
|
||||
let interp = halves
|
||||
.pair(
|
||||
attr,
|
||||
inst.read(Reg::V(d)),
|
||||
inst.read(Reg::V(reg)),
|
||||
&barycentric,
|
||||
)
|
||||
.map_err(|what| unsupported(at, what))?;
|
||||
push_pair(&mut io, site, interp, attribute);
|
||||
}
|
||||
_ => return Err(unsupported(at, "an interpolation form")),
|
||||
}
|
||||
}
|
||||
Fields::Valu(v) if name.starts_with("v_interp_") => match name {
|
||||
"v_interp_p1ll_f16" => {}
|
||||
"v_interp_p2_f16" => {
|
||||
let attribute = attribute(inst, &v.src[0])?;
|
||||
let read = |k: usize| match v.src.get(k) {
|
||||
Some(&Operand::Vector { reg, .. }) => inst.read(Reg::V(reg)),
|
||||
_ => None,
|
||||
};
|
||||
let interp = halves
|
||||
.pair(&v.src[0], read(2), read(1), &barycentric)
|
||||
.map_err(|what| unsupported(at, what))?;
|
||||
push_pair(&mut io, site, interp, attribute);
|
||||
}
|
||||
_ => return Err(unsupported(at, "an interpolation form")),
|
||||
},
|
||||
Fields::Exp {
|
||||
target,
|
||||
src,
|
||||
compr,
|
||||
done,
|
||||
..
|
||||
} => {
|
||||
let target = match *target {
|
||||
t @ 0..=7 => Target::Color(t),
|
||||
8 => Target::Depth,
|
||||
9 => Target::Null,
|
||||
t @ 12..=16 => Target::Position(t - 12),
|
||||
20 => Target::Primitive,
|
||||
32 if params.is_empty() => Target::Unread,
|
||||
t @ 32..=63 => {
|
||||
// Bit 7: a mesh program's per-primitive output.
|
||||
let o = params.iter().find(|o| o.param & 0x7F == t - 32).ok_or(
|
||||
unsupported(at, "a parameter export the stage data does not list"),
|
||||
)?;
|
||||
let (usage, row) = (o.usage, o.row);
|
||||
if o.param & 0x80 != 0 {
|
||||
Target::PrimitiveParam { usage, row }
|
||||
} else {
|
||||
Target::Param { usage, row }
|
||||
}
|
||||
}
|
||||
_ => return Err(unsupported(at, "an export target")),
|
||||
};
|
||||
let values = src.map(|s| match s {
|
||||
Some(Operand::Vector { reg, .. }) => inst.read(Reg::V(reg)),
|
||||
_ => None,
|
||||
});
|
||||
io.exports.push(Export {
|
||||
site,
|
||||
target,
|
||||
values,
|
||||
compressed: *compr,
|
||||
done: *done,
|
||||
});
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(io)
|
||||
}
|
||||
|
||||
/// The pixel input VGPRs that `addr` enables, with their meaning.
|
||||
fn ps_vgprs(addr: u32) -> Vec<(u8, Input)> {
|
||||
let mut out = Vec::new();
|
||||
let mut next = 0u8;
|
||||
for (bit, &(count, kind)) in PS_VGPRS.iter().enumerate() {
|
||||
if addr >> bit & 1 == 0 {
|
||||
continue;
|
||||
}
|
||||
for index in 0..count {
|
||||
let input = match kind {
|
||||
Some(kind) => Input::Barycentric { kind, index },
|
||||
None => ps_system(bit),
|
||||
};
|
||||
out.push((next + index, input));
|
||||
}
|
||||
next += count;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// An interpolation before its attribute is known: `barycentric` none
|
||||
/// when i or j is computed.
|
||||
struct Pair {
|
||||
barycentric: Option<Barycentric>,
|
||||
first: Vec<Site>,
|
||||
}
|
||||
|
||||
impl Pair {
|
||||
fn with(self, attribute: Attribute) -> Interp {
|
||||
match self.barycentric {
|
||||
Some(barycentric) => Interp::Interpolated {
|
||||
attribute,
|
||||
barycentric,
|
||||
first: self.first,
|
||||
},
|
||||
None => Interp::Weighted { attribute },
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Records interpolation `pair` at `site`, and its first halves too when
|
||||
/// they evaluate on their own (computed barycentrics).
|
||||
fn push_pair(io: &mut Io, site: Site, pair: Pair, attribute: Attribute) {
|
||||
if pair.barycentric.is_none() {
|
||||
for &f in &pair.first {
|
||||
if !io.interps.iter().any(|(s, _)| *s == f) {
|
||||
io.interps.push((f, Interp::Weighted { attribute }));
|
||||
}
|
||||
}
|
||||
}
|
||||
io.interps.push((site, pair.with(attribute)));
|
||||
}
|
||||
|
||||
/// Finds the first halves of interpolations.
|
||||
struct Halves<'a> {
|
||||
p: &'a Program,
|
||||
defs: &'a std::collections::HashMap<Value, Site>,
|
||||
phis: &'a std::collections::HashMap<Value, (usize, usize)>,
|
||||
}
|
||||
|
||||
impl Halves<'_> {
|
||||
/// The interpolation whose second half reads the first half's result
|
||||
/// `acc`, the barycentric `j`, and attribute `attr`: every first half
|
||||
/// must read the same attribute channel. With j and every first half's
|
||||
/// i loaded as one kind's, the pair interpolates with that kind;
|
||||
/// otherwise each half evaluates on its own (`Interp::Weighted`).
|
||||
fn pair(
|
||||
&self,
|
||||
attr: &Operand,
|
||||
acc: Option<Value>,
|
||||
j: Option<Value>,
|
||||
barycentric: &impl Fn(Option<Value>) -> Option<(Barycentric, u8)>,
|
||||
) -> Result<Pair, &'static str> {
|
||||
let mut first = Vec::new();
|
||||
self.sites(
|
||||
acc.ok_or("an interpolation without its first half")?,
|
||||
&mut Vec::new(),
|
||||
&mut first,
|
||||
)?;
|
||||
let mut kind = match barycentric(j) {
|
||||
Some((kind, 1)) => Some(kind),
|
||||
_ => None,
|
||||
};
|
||||
for &(b, i) in &first {
|
||||
let inst = &self.p.blocks[b].insts[i];
|
||||
let (a, i) = match &inst.fields {
|
||||
Fields::Vintrp {
|
||||
src: Operand::Vector { reg, .. },
|
||||
attr,
|
||||
..
|
||||
} if inst.name() == "v_interp_p1_f32" => (*attr, inst.read(Reg::V(*reg))),
|
||||
Fields::Valu(v) if inst.name() == "v_interp_p1ll_f16" => match v.src.get(1) {
|
||||
Some(&Operand::Vector { reg, .. }) => (v.src[0], inst.read(Reg::V(reg))),
|
||||
_ => return Err("an interpolation without its first half"),
|
||||
},
|
||||
_ => return Err("an interpolation without its first half"),
|
||||
};
|
||||
if a != *attr {
|
||||
return Err("interpolation halves of different attributes");
|
||||
}
|
||||
if kind.is_some_and(|k| barycentric(i) != Some((k, 0))) {
|
||||
kind = None;
|
||||
}
|
||||
}
|
||||
Ok(Pair {
|
||||
barycentric: kind,
|
||||
first,
|
||||
})
|
||||
}
|
||||
|
||||
/// The instructions `v` comes from, through phis (`seen`: phis on the
|
||||
/// way; a loop back to one adds nothing).
|
||||
fn sites(
|
||||
&self,
|
||||
v: Value,
|
||||
seen: &mut Vec<Value>,
|
||||
out: &mut Vec<Site>,
|
||||
) -> Result<(), &'static str> {
|
||||
if let Some(&site) = self.defs.get(&v) {
|
||||
if !out.contains(&site) {
|
||||
out.push(site);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let &(b, i) = self
|
||||
.phis
|
||||
.get(&v)
|
||||
.ok_or("an interpolation without its first half")?;
|
||||
if !seen.contains(&v) {
|
||||
seen.push(v);
|
||||
for &a in &self.p.blocks[b].phis[i].args {
|
||||
self.sites(a, seen, out)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::native::ExportPatch;
|
||||
|
||||
const S_ENDPGM: u32 = 0xBF81_0000;
|
||||
|
||||
fn program(words: &[u32]) -> Program {
|
||||
let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
|
||||
crate::ir::build(&code, false, 256).unwrap()
|
||||
}
|
||||
|
||||
fn pixel(inputs: Vec<PsInput>, input_addr: u32) -> NativeProgram {
|
||||
NativeProgram {
|
||||
stage: HwStage::Ps,
|
||||
wave64: false,
|
||||
vgprs: 256,
|
||||
layout: vec![],
|
||||
used: vec![],
|
||||
io: StageIo::Ps {
|
||||
inputs,
|
||||
input_addr,
|
||||
db_shader_control: 0,
|
||||
patches: Vec::<ExportPatch>::new(),
|
||||
},
|
||||
code: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
const TEXCOORD: PsInput = PsInput {
|
||||
usage: Usage::Generic,
|
||||
row: 1,
|
||||
mask: 3,
|
||||
attr: 0,
|
||||
flat: false,
|
||||
fp16: false,
|
||||
pack2: false,
|
||||
row2: 1,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn interpolation_pairs_and_color_exports() {
|
||||
// Blit's pixel shader: TEXCOORD.xy from the perspective-center i/j
|
||||
// in v0/v1, then exported unconverted to MRT0.
|
||||
let p = program(&[
|
||||
0xC808_0000, // v_interp_p1_f32 v2, v0, attr0.x
|
||||
0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x
|
||||
0xF800_180F,
|
||||
0x0302_0102, // exp mrt0, v2, v1, v2, v3 done vm
|
||||
S_ENDPGM,
|
||||
]);
|
||||
let io = raise(&p, &pixel(vec![TEXCOORD], 2)).unwrap();
|
||||
let input = |reg| p.inputs.iter().find(|i| i.0 == Reg::V(reg)).unwrap().1;
|
||||
let center = |index| Input::Barycentric {
|
||||
kind: Barycentric::PerspectiveCenter,
|
||||
index,
|
||||
};
|
||||
assert!(io.inputs.contains(&(input(0), center(0))));
|
||||
assert!(io.inputs.contains(&(input(1), center(1))));
|
||||
// v2 and v3 are read before written but hold nothing.
|
||||
assert!(!io.inputs.iter().any(|i| i.0 == input(3)));
|
||||
assert_eq!(
|
||||
io.interps,
|
||||
[(
|
||||
(0, 1),
|
||||
Interp::Interpolated {
|
||||
attribute: Attribute {
|
||||
usage: Usage::Generic,
|
||||
row: 1,
|
||||
channel: 0,
|
||||
high: false
|
||||
},
|
||||
barycentric: Barycentric::PerspectiveCenter,
|
||||
first: vec![(0, 0)],
|
||||
}
|
||||
)]
|
||||
);
|
||||
let [e] = &io.exports[..] else {
|
||||
panic!("{:?}", io.exports)
|
||||
};
|
||||
assert_eq!(
|
||||
(e.target, e.done, e.compressed),
|
||||
(Target::Color(0), true, false)
|
||||
);
|
||||
assert_eq!(e.values[0], p.blocks[0].insts[1].write(Reg::V(2)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unpaired_or_unknown_interpolation_fails() {
|
||||
// p2 alone: its old dst is no p1's result.
|
||||
let lone = program(&[0xC809_0001, S_ENDPGM]); // v_interp_p2_f32 v2, v1, attr0.x
|
||||
assert!(raise(&lone, &pixel(vec![TEXCOORD], 2)).is_err());
|
||||
// attr1 is not in the stage data.
|
||||
let other = program(&[0xC808_0400, S_ENDPGM]); // v_interp_p1_f32 v2, v0, attr1.x
|
||||
assert!(raise(&other, &pixel(vec![TEXCOORD], 2)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn computed_barycentrics_evaluate_each_half() {
|
||||
// i scaled before the first half: both halves stand on their own.
|
||||
let p = program(&[
|
||||
0x1006_00F0, // v_mul_f32 v3, 0.5, v0
|
||||
0xC808_0003, // v_interp_p1_f32 v2, v3, attr0.x
|
||||
0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x
|
||||
S_ENDPGM,
|
||||
]);
|
||||
let io = raise(&p, &pixel(vec![TEXCOORD], 2)).unwrap();
|
||||
let attribute = Attribute {
|
||||
usage: Usage::Generic,
|
||||
row: 1,
|
||||
channel: 0,
|
||||
high: false,
|
||||
};
|
||||
let mut interps = io.interps.clone();
|
||||
interps.sort_by_key(|i| i.0);
|
||||
assert_eq!(
|
||||
interps,
|
||||
[
|
||||
((0, 1), Interp::Weighted { attribute }),
|
||||
((0, 2), Interp::Weighted { attribute }),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mesh_inputs_and_primitive_export() {
|
||||
let mesh = |words: &[u32]| {
|
||||
let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
|
||||
let p = crate::ir::build(&code, true, 256).unwrap();
|
||||
let native = NativeProgram {
|
||||
stage: HwStage::Ms,
|
||||
wave64: true,
|
||||
vgprs: 256,
|
||||
layout: vec![],
|
||||
used: vec![],
|
||||
io: StageIo::Ms(crate::native::MeshIo {
|
||||
outputs: vec![],
|
||||
clip_cntl: 0,
|
||||
threads: 128,
|
||||
max_vertices: 128,
|
||||
max_primitives: 128,
|
||||
topology: 2,
|
||||
lds_bytes: 0,
|
||||
}),
|
||||
code,
|
||||
};
|
||||
raise(&p, &native)
|
||||
};
|
||||
let io = mesh(&[
|
||||
0x7E04_0505, // v_readfirstlane_b32 s2, v5
|
||||
0xF800_0941,
|
||||
0x0000_0009, // exp prim, v9, off, off, off done
|
||||
S_ENDPGM,
|
||||
])
|
||||
.unwrap();
|
||||
assert!(io.inputs.iter().any(|i| i.1 == Input::MeshGroup));
|
||||
assert_eq!(io.exports[0].target, Target::Primitive);
|
||||
// The group input is uniform only as the first lane reads it.
|
||||
assert!(mesh(&[0x7E02_0305, S_ENDPGM]).is_err()); // v_mov_b32 v1, v5
|
||||
// Also as an operand of a write to v5, or after a join.
|
||||
let per_lane: [&[u32]; 5] = [
|
||||
&[0x4A0A_0305, S_ENDPGM], // v_add_nc_u32 v5, v5, v1
|
||||
&[0x7E0A_0D05, S_ENDPGM], // v_cvt_f32_u32 v5, v5
|
||||
&[0xDC30_8000, 0x0500_0005, S_ENDPGM], // global_load_dword v5, v5, s[0:1]
|
||||
&[0x7E0A_CB01, S_ENDPGM], // v_swap_b32 v5, v1
|
||||
&[
|
||||
0xBF06_8001, // s_cmp_eq_u32 s1, 0
|
||||
0xBF85_0001, // s_cbranch_scc1 -> 0xc
|
||||
0x7E0A_0280, // v_mov_b32 v5, 0
|
||||
0x7E02_0305, // 0xc: v_mov_b32 v1, v5
|
||||
S_ENDPGM,
|
||||
],
|
||||
];
|
||||
let accepted: Vec<_> = per_lane.iter().filter(|w| mesh(w).is_ok()).collect();
|
||||
assert!(accepted.is_empty(), "accepted: {accepted:08X?}");
|
||||
// Overwriting v5 reads the group input only for lanes outside EXEC:
|
||||
// v_mov_b32 v5, 0; v_mov_b32 v1, v5.
|
||||
assert!(mesh(&[0x7E0A_0280, 0x7E02_0305, S_ENDPGM]).is_ok());
|
||||
// Skipping that write with s_cbranch_execz is the same case: under the
|
||||
// same mask, the read sees only the 0.
|
||||
let reuse = [
|
||||
0x7E04_0505, // v_readfirstlane_b32 s2, v5
|
||||
0x7D88_0084, // v_cmp_gt_u32 vcc, 4, v0
|
||||
0xBE86_246A, // s_and_saveexec_b64 s[6:7], vcc
|
||||
0xBF88_0001, // s_cbranch_execz -> 0x14
|
||||
0x7E0A_0280, // v_mov_b32 v5, 0
|
||||
0x88FE_067E, // 0x14: s_or_b64 exec, exec, s[6:7]
|
||||
0xBE86_246A, // s_and_saveexec_b64 s[6:7], vcc
|
||||
0xBF88_0001, // s_cbranch_execz -> 0x24
|
||||
0x7E02_0305, // v_mov_b32 v1, v5
|
||||
0x88FE_067E, // 0x24: s_or_b64 exec, exec, s[6:7]
|
||||
S_ENDPGM,
|
||||
];
|
||||
assert_eq!(mesh(&reuse).map(|_| ()), Ok(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pixel_vgprs_follow_the_input_address() {
|
||||
// Linear center (bit 5), then position x and y (bits 8, 9).
|
||||
let v = ps_vgprs(1 << 5 | 1 << 8 | 1 << 9);
|
||||
assert_eq!(
|
||||
v,
|
||||
[
|
||||
(
|
||||
0,
|
||||
Input::Barycentric {
|
||||
kind: Barycentric::LinearCenter,
|
||||
index: 0
|
||||
}
|
||||
),
|
||||
(
|
||||
1,
|
||||
Input::Barycentric {
|
||||
kind: Barycentric::LinearCenter,
|
||||
index: 1
|
||||
}
|
||||
),
|
||||
(2, Input::Position(0)),
|
||||
(3, Input::Position(1)),
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,49 @@
|
||||
//! Xbox Series shaders to host shaders.
|
||||
//!
|
||||
//! An Xbox Series shader is a standard DXBC container ([`dxbc`]). Its `DXIL`
|
||||
//! part ([`dxil`]) may carry Xbox additions around the LLVM bitcode: an
|
||||
//! `XDAT` table before it indexing blobs after it, among them `xbop`
|
||||
//! (compiler options) and the zlib-compressed GFX10 code. The bitcode may use
|
||||
//! console-only intrinsics, so the GFX10 code is translated in general.
|
||||
|
||||
#[rustfmt::skip] // BetterXen: vendored from upstream, kept diffable (see ../UPSTREAM.md)
|
||||
pub mod bvh;
|
||||
#[rustfmt::skip] // BetterXen: vendored from upstream, kept diffable (see ../UPSTREAM.md)
|
||||
pub mod dxbc;
|
||||
#[rustfmt::skip] // BetterXen: vendored from upstream, kept diffable (see ../UPSTREAM.md)
|
||||
pub mod dxil;
|
||||
#[rustfmt::skip] // BetterXen: vendored from upstream, kept diffable (see ../UPSTREAM.md)
|
||||
pub mod emit;
|
||||
#[rustfmt::skip] // BetterXen: vendored from upstream, kept diffable (see ../UPSTREAM.md)
|
||||
pub mod gfx10;
|
||||
#[rustfmt::skip] // BetterXen: vendored from upstream, kept diffable (see ../UPSTREAM.md)
|
||||
pub mod io;
|
||||
#[rustfmt::skip] // BetterXen: vendored from upstream, kept diffable (see ../UPSTREAM.md)
|
||||
pub mod ir;
|
||||
#[rustfmt::skip] // BetterXen: vendored from upstream, kept diffable (see ../UPSTREAM.md)
|
||||
pub mod native;
|
||||
#[rustfmt::skip] // BetterXen: vendored from upstream, kept diffable (see ../UPSTREAM.md)
|
||||
pub mod resource;
|
||||
#[rustfmt::skip] // BetterXen: vendored from upstream, kept diffable (see ../UPSTREAM.md)
|
||||
pub mod spill;
|
||||
#[rustfmt::skip] // BetterXen: vendored from upstream, kept diffable (see ../UPSTREAM.md)
|
||||
pub mod structure;
|
||||
|
||||
pub use dxbc::{Container, FourCC, Part};
|
||||
pub use dxil::{DxilProgram, ShaderKind, XboxExtras};
|
||||
pub use native::{
|
||||
HwStage, NativeProgram, ResourceType, RootParam, RootType, UsedResource, native_programs,
|
||||
};
|
||||
|
||||
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
|
||||
pub enum ShaderError {
|
||||
#[error("not a DXBC container")]
|
||||
NotDxbc,
|
||||
#[error("malformed shader: {0}")]
|
||||
Malformed(&'static str),
|
||||
#[error("GFX10 code at {offset:#x}: {reason}")]
|
||||
Isa { offset: usize, reason: &'static str },
|
||||
/// Valid code the translator cannot handle yet: an opcode name or a construct.
|
||||
#[error("GFX10 code at {offset:#x}: {what} is not supported")]
|
||||
Unsupported { offset: usize, what: &'static str },
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,380 @@
|
||||
//! The spilled user-data table of a compute program.
|
||||
//!
|
||||
//! A compute program has as many user SGPRs as `COMPUTE_PGM_RSRC2` says. A
|
||||
//! root signature that needs more dwords than that keeps none of its
|
||||
//! parameters in registers: user-data dwords 0 and 1 then hold the 40-bit
|
||||
//! address of a table in memory (`s0`, and `s1 & 0xff` as bits 32-39), and
|
||||
//! the parameter the layout declares at user-data index N (16 or above) is
|
||||
//! at byte `4 * (N - 16)` of that table. The code reads it with
|
||||
//! `s_load_dword*` through that pointer. (Every compute program of the
|
||||
//! console's ray-tracing structure builder, `XboxBvhBuilder.dll`, is of this
|
||||
//! kind; measured there: 118 of 118 such loads land on a declared parameter.)
|
||||
//!
|
||||
//! [`user_data`] rewrites those loads away: each dword they read becomes the
|
||||
//! entry value of the SGPR its user-data index names, as if the parameter
|
||||
//! had arrived in a register. Resource tracking and lowering then treat a
|
||||
//! spilled parameter like any other (the host binds user data by root slot
|
||||
//! and dword, not by register).
|
||||
|
||||
use crate::ShaderError;
|
||||
use crate::gfx10::{Fields, NULL, Operand};
|
||||
use crate::ir::{self, Program, Reg, Value};
|
||||
use crate::native::{HwStage, NativeProgram, StageIo};
|
||||
|
||||
/// The user-data index of the table's first dword.
|
||||
const FIRST: u32 = 16;
|
||||
|
||||
/// [`ir::build`] of `native`'s code as the hardware runs it, with the loads
|
||||
/// of a spilled user-data table rewritten ([`user_data`]).
|
||||
pub fn build(native: &NativeProgram) -> Result<Program, ShaderError> {
|
||||
let mut p = ir::build(&native.patched_code(), native.wave64, native.vgprs)?;
|
||||
user_data(&mut p, native);
|
||||
Ok(p)
|
||||
}
|
||||
|
||||
/// Whether `native` is a compute program that keeps its root parameters in
|
||||
/// a spilled user-data table (see the module): the entries no register
|
||||
/// holds, as (first user-data index, dwords), if the table starts at index
|
||||
/// 16 and the program has the two registers of its address.
|
||||
fn spilled(native: &NativeProgram) -> Option<Vec<(u32, u32)>> {
|
||||
let StageIo::Cs(cs) = &native.io else {
|
||||
return None;
|
||||
};
|
||||
if native.stage != HwStage::Cs {
|
||||
return None;
|
||||
}
|
||||
let registers = u32::from(cs.user_sgprs());
|
||||
let spilled: Vec<(u32, u32)> = native
|
||||
.layout
|
||||
.iter()
|
||||
.filter(|e| e.sgprs > 0 && u32::from(e.user_data) >= registers)
|
||||
.map(|e| (u32::from(e.user_data), e.sgprs))
|
||||
.collect();
|
||||
// Only the one arrangement seen: the table starts at index 16.
|
||||
(spilled.iter().map(|e| e.0).min() == Some(FIRST) && registers >= 2).then_some(spilled)
|
||||
}
|
||||
|
||||
/// Whether `native` reads its root parameters from a spilled user-data
|
||||
/// table. (In the title exactly the compute programs of the
|
||||
/// console's ray-tracing structure builder do.)
|
||||
pub fn is_spilled(native: &NativeProgram) -> bool {
|
||||
spilled(native).is_some()
|
||||
}
|
||||
|
||||
/// Rewrites the loads of `native`'s spilled user-data table in `p`; returns
|
||||
/// how many loads it replaced. Nothing changes unless the program is a
|
||||
/// compute program whose layout has entries past its user SGPRs, the first
|
||||
/// at index 16. A load is left alone (and resource tracking then refuses it
|
||||
/// as before) when its offset is not a constant on a dword, or when a dword
|
||||
/// it reads and the program uses is in no layout entry.
|
||||
pub fn user_data(p: &mut Program, native: &NativeProgram) -> usize {
|
||||
let Some(spilled) = spilled(native) else {
|
||||
return 0;
|
||||
};
|
||||
let entry = |reg: Reg, p: &Program| p.inputs.iter().find(|i| i.0 == reg).map(|i| i.1);
|
||||
let (Some(low), Some(high)) = (entry(Reg::S(0), p), entry(Reg::S(1), p)) else {
|
||||
return 0;
|
||||
};
|
||||
|
||||
// The pointer's halves: `s0` and its copies, `s1 & 0xff` and its copies.
|
||||
let mut lows = vec![low];
|
||||
let mut highs: Vec<Value> = Vec::new();
|
||||
let mut raw_highs = vec![high];
|
||||
// Instructions that only form the pointer: dropped when nothing reads
|
||||
// them any more.
|
||||
let mut forming: Vec<(usize, usize)> = Vec::new();
|
||||
loop {
|
||||
let mut changed = false;
|
||||
for (b, block) in p.blocks.iter().enumerate() {
|
||||
for (i, inst) in block.insts.iter().enumerate() {
|
||||
let Fields::Sop { dst, src, .. } = &inst.fields else {
|
||||
continue;
|
||||
};
|
||||
let Some(Operand::Scalar { code: d, .. }) = *dst else {
|
||||
continue;
|
||||
};
|
||||
let Some(out) = inst.write(Reg::S(d)) else {
|
||||
continue;
|
||||
};
|
||||
let read = |op: &Operand| match *op {
|
||||
Operand::Scalar { code, .. } if code != NULL => inst.read(Reg::S(code)),
|
||||
_ => None,
|
||||
};
|
||||
let found = match (inst.name(), &src[..]) {
|
||||
("s_mov_b32", [s]) => match read(s) {
|
||||
Some(v) if lows.contains(&v) => Some(&mut lows),
|
||||
Some(v) if highs.contains(&v) => Some(&mut highs),
|
||||
Some(v) if raw_highs.contains(&v) => Some(&mut raw_highs),
|
||||
_ => None,
|
||||
},
|
||||
("s_and_b32", [x, y]) => {
|
||||
let masked = |a: &Operand, m: &Operand| {
|
||||
matches!(*m, Operand::Literal(0xff))
|
||||
&& read(a).is_some_and(|v| raw_highs.contains(&v))
|
||||
};
|
||||
(masked(x, y) || masked(y, x)).then_some(&mut highs)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
if let Some(set) = found
|
||||
&& !set.contains(&out)
|
||||
{
|
||||
set.push(out);
|
||||
forming.push((b, i));
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if !changed {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if highs.is_empty() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Values some instruction or phi reads.
|
||||
let mut read_somewhere = std::collections::HashSet::new();
|
||||
for block in &p.blocks {
|
||||
read_somewhere.extend(block.phis.iter().flat_map(|phi| phi.args.iter().copied()));
|
||||
read_somewhere.extend(block.insts.iter().flat_map(|i| i.reads.iter().map(|r| r.1)));
|
||||
}
|
||||
let mut next = p
|
||||
.inputs
|
||||
.iter()
|
||||
.map(|i| i.1)
|
||||
.chain(p.blocks.iter().flat_map(|b| {
|
||||
b.phis
|
||||
.iter()
|
||||
.map(|phi| phi.value)
|
||||
.chain(b.insts.iter().flat_map(|i| i.writes.iter().map(|w| w.1)))
|
||||
}))
|
||||
.map(|v| v.0 + 1)
|
||||
.max()
|
||||
.unwrap_or(0);
|
||||
|
||||
// Each load through the pointer: its dwords become entry values.
|
||||
let mut replaced: std::collections::HashMap<Value, Value> = Default::default();
|
||||
let mut gone: Vec<(usize, usize)> = Vec::new();
|
||||
let mut inputs = p.inputs.clone();
|
||||
for (b, block) in p.blocks.iter().enumerate() {
|
||||
'insts: for (i, inst) in block.insts.iter().enumerate() {
|
||||
let Fields::Smem {
|
||||
data: Some(Operand::Scalar { code: first, .. }),
|
||||
base: Operand::Scalar { code: base, .. },
|
||||
offset,
|
||||
soffset,
|
||||
..
|
||||
} = inst.fields
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if !inst.name().starts_with("s_load_dword")
|
||||
|| !matches!(soffset, Operand::Scalar { code: NULL, .. } | Operand::Const(128))
|
||||
|| offset < 0
|
||||
|| offset % 4 != 0
|
||||
|| !inst.read(Reg::S(base)).is_some_and(|v| lows.contains(&v))
|
||||
|| !inst.read(Reg::S(base + 1)).is_some_and(|v| highs.contains(&v))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let mut dwords = Vec::new();
|
||||
for &(reg, v) in &inst.writes {
|
||||
let Reg::S(code) = reg else {
|
||||
continue 'insts;
|
||||
};
|
||||
let Some(k) = code.checked_sub(first) else {
|
||||
continue 'insts;
|
||||
};
|
||||
let index = FIRST + offset as u32 / 4 + u32::from(k);
|
||||
let declared = spilled.iter().any(|&(at, n)| index >= at && index < at + n);
|
||||
if !declared {
|
||||
if read_somewhere.contains(&v) {
|
||||
continue 'insts;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// SGPR codes end at 105; no root signature reaches there.
|
||||
let Ok(code) = u8::try_from(index) else {
|
||||
continue 'insts;
|
||||
};
|
||||
if code > 105 {
|
||||
continue 'insts;
|
||||
}
|
||||
dwords.push((Reg::S(code), v));
|
||||
}
|
||||
for (reg, v) in dwords {
|
||||
let value = match inputs.iter().find(|e| e.0 == reg) {
|
||||
Some(e) => e.1,
|
||||
None => {
|
||||
let value = Value(next);
|
||||
next += 1;
|
||||
inputs.push((reg, value));
|
||||
value
|
||||
}
|
||||
};
|
||||
replaced.insert(v, value);
|
||||
}
|
||||
gone.push((b, i));
|
||||
}
|
||||
}
|
||||
if gone.is_empty() {
|
||||
return 0;
|
||||
}
|
||||
p.inputs = inputs;
|
||||
let renamed = |v: &mut Value| {
|
||||
if let Some(&to) = replaced.get(v) {
|
||||
*v = to;
|
||||
}
|
||||
};
|
||||
for block in &mut p.blocks {
|
||||
for phi in &mut block.phis {
|
||||
phi.args.iter_mut().for_each(renamed);
|
||||
}
|
||||
for inst in &mut block.insts {
|
||||
inst.reads.iter_mut().for_each(|r| renamed(&mut r.1));
|
||||
}
|
||||
}
|
||||
// The loads go, then what only formed the pointer (last first, so a
|
||||
// copy goes before what it copied).
|
||||
let mut drop = gone.clone();
|
||||
loop {
|
||||
let read_somewhere = {
|
||||
let mut used = std::collections::HashSet::new();
|
||||
for (b, block) in p.blocks.iter().enumerate() {
|
||||
used.extend(block.phis.iter().flat_map(|phi| phi.args.iter().copied()));
|
||||
for (i, inst) in block.insts.iter().enumerate() {
|
||||
if !drop.contains(&(b, i)) {
|
||||
used.extend(inst.reads.iter().map(|r| r.1));
|
||||
}
|
||||
}
|
||||
}
|
||||
used
|
||||
};
|
||||
let before = drop.len();
|
||||
for &site in &forming {
|
||||
let inst = &p.blocks[site.0].insts[site.1];
|
||||
if !drop.contains(&site) && inst.writes.iter().all(|w| !read_somewhere.contains(&w.1)) {
|
||||
drop.push(site);
|
||||
}
|
||||
}
|
||||
if drop.len() == before {
|
||||
break;
|
||||
}
|
||||
}
|
||||
for (b, block) in p.blocks.iter_mut().enumerate() {
|
||||
let mut i = 0;
|
||||
block.insts.retain(|_| {
|
||||
i += 1;
|
||||
!drop.contains(&(b, i - 1))
|
||||
});
|
||||
}
|
||||
// The pointer's registers are no inputs once nothing reads them.
|
||||
let mut read = std::collections::HashSet::new();
|
||||
for block in &p.blocks {
|
||||
read.extend(block.phis.iter().flat_map(|phi| phi.args.iter().copied()));
|
||||
read.extend(block.insts.iter().flat_map(|i| i.reads.iter().map(|r| r.1)));
|
||||
}
|
||||
p.inputs
|
||||
.retain(|&(reg, v)| !matches!(reg, Reg::S(0 | 1)) || read.contains(&v));
|
||||
gone.len()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::native::{ComputeIo, RootParam, RootType};
|
||||
|
||||
fn param(root: RootType, user_data: u8, sgprs: u32, slot: u8) -> RootParam {
|
||||
RootParam {
|
||||
root,
|
||||
table_offset_dwords: 0,
|
||||
sgprs,
|
||||
base_register: 0,
|
||||
user_data,
|
||||
slot,
|
||||
}
|
||||
}
|
||||
|
||||
/// A compute program with `registers` user SGPRs and the group id after
|
||||
/// them.
|
||||
fn native(words: &[u32], registers: u32, layout: Vec<RootParam>) -> NativeProgram {
|
||||
NativeProgram {
|
||||
stage: HwStage::Cs,
|
||||
wave64: false,
|
||||
vgprs: 256,
|
||||
layout,
|
||||
used: vec![],
|
||||
io: StageIo::Cs(ComputeIo {
|
||||
rsrc2: registers << 1 | 1 << 7,
|
||||
threads: [1, 1, 1],
|
||||
}),
|
||||
code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
// s_and_b32 s3, s1, 0xff; s_mov_b32 s2, s0; s_load_dword s5, s[2:3],
|
||||
// 0x10; s_load_dwordx2 s[0:1], s[2:3], 0; s_endpgm.
|
||||
const TABLE: [u32; 8] = [
|
||||
0x8703_FF01,
|
||||
0x0000_00FF,
|
||||
0xBE82_0300,
|
||||
0xF400_0141,
|
||||
0xFA00_0010,
|
||||
0xF404_0001,
|
||||
0xFA00_0000,
|
||||
0xBF81_0000,
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn loads_of_the_spilled_table_become_entry_registers() {
|
||||
let n = native(
|
||||
&TABLE,
|
||||
4,
|
||||
vec![
|
||||
param(RootType::Descriptor, 16, 2, 0),
|
||||
param(RootType::Descriptor, 18, 2, 1),
|
||||
param(RootType::Constants, 20, 16, 2),
|
||||
],
|
||||
);
|
||||
let mut p = ir::build(&n.code, false, 256).unwrap();
|
||||
assert_eq!(user_data(&mut p, &n), 2);
|
||||
let names: Vec<&str> = p.blocks.iter().flat_map(|b| &b.insts).map(|i| i.name()).collect();
|
||||
assert!(!names.iter().any(|n| n.starts_with("s_load_")), "{names:?}");
|
||||
// The pointer is gone with the loads; byte 0x10 is index 20, the
|
||||
// first root constant, and bytes 0-7 are the first root view.
|
||||
let mut regs: Vec<Reg> = p.inputs.iter().map(|i| i.0).collect();
|
||||
regs.sort();
|
||||
assert_eq!(regs, [Reg::S(16), Reg::S(17), Reg::S(20)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parameters_in_registers_are_left_alone() {
|
||||
// The same code where s0 and s1 are a root view the layout declares.
|
||||
let n = native(&TABLE, 6, vec![param(RootType::Descriptor, 0, 2, 0)]);
|
||||
let mut p = ir::build(&n.code, false, 256).unwrap();
|
||||
let before = p.clone();
|
||||
assert_eq!(user_data(&mut p, &n), 0);
|
||||
assert_eq!(p, before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_used_dword_no_parameter_declares_keeps_its_load() {
|
||||
// As above with `s_mov_b32 s6, s5` before the end: the dword at
|
||||
// byte 0x10 (index 20) is read, and here nothing declares it.
|
||||
let mut words = TABLE.to_vec();
|
||||
words.insert(7, 0xBE86_0305);
|
||||
let n = native(&words, 4, vec![param(RootType::Descriptor, 16, 2, 0)]);
|
||||
let mut p = ir::build(&n.code, false, 256).unwrap();
|
||||
assert_eq!(user_data(&mut p, &n), 1);
|
||||
let loads = p
|
||||
.blocks
|
||||
.iter()
|
||||
.flat_map(|b| &b.insts)
|
||||
.filter(|i| i.name().starts_with("s_load_"))
|
||||
.count();
|
||||
assert_eq!(loads, 1);
|
||||
// The pointer is still read, by the load that stays.
|
||||
assert!(p.inputs.iter().any(|i| i.0 == Reg::S(0)));
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
+19
-4
@@ -8,9 +8,16 @@ then read the [interface contracts](interfaces.md). Reproduce an
|
||||
[independent validation suite](../tests/validation/README.md) before changing
|
||||
either path. The [changelog](../CHANGELOG.md) records notable changes.
|
||||
|
||||
Use the [BetterXen development phases](development-phases.md) for current work
|
||||
order, existing issue/PR dependencies and measurable completion criteria.
|
||||
Historical phase checkpoints retain their original evidence scope.
|
||||
Use the [roadmap](roadmap.md) for the active CrossOver-based hybrid plan, phases,
|
||||
critical path and completion criteria; see [ADR 0005](adr/0005-crossover-hybrid-direction.md)
|
||||
for the decision and [project board setup](planning/project-board.md). Native work is
|
||||
paused: [deferred native roadmap](research/native-roadmap.md) and the archived
|
||||
[native-first plan](archive/development-phases-native-first.md) with
|
||||
[retired milestones](archive/native-first-milestones.json), the
|
||||
[native issue archive](research/native-issue-archive.md) and the retired
|
||||
[H0 to H7 breakdown](archive/hybrid-phases-h0-h7.md). Research inputs: the [upstream research registry](research/upstream-registry.md) and
|
||||
[component reuse matrix](research/component-reuse-matrix.md). Historical phase
|
||||
checkpoints retain their original evidence scope.
|
||||
|
||||
## Architecture and technical design
|
||||
|
||||
@@ -38,6 +45,7 @@ Historical phase checkpoints retain their original evidence scope.
|
||||
|
||||
- [Guest experiment guide](../experiments/x1/README.md) — Bounded x86-64 execution, executable loading, experimental services, native compute, and offscreen rendering.
|
||||
- [x86-64 instruction registry](cpu/instruction-registry.md) — Shared decoder, generated tables, semantics, native lowering and how to add a verified instruction form.
|
||||
- [Proposed AVX and AVX2 guest contract](cpu/avx-contract.md) — VEX decoding, vector state, fault behavior and an original integer fixture specification.
|
||||
- [Runtime service registry](runtime/registry.md) and [generated coverage](runtime/services.md) — Import resolution, typed Win64 adapters and how to add a tested service.
|
||||
- [Guest threads](runtime/threads.md) — Deterministic scheduler, thread services, limits and tests.
|
||||
- [Guest CPU research](research/cpu-boundary.md) — Public specifications and unresolved console requirements.
|
||||
@@ -49,7 +57,7 @@ Historical phase checkpoints retain their original evidence scope.
|
||||
- [Testing and acceptance index](testing/README.md) — Entry point for test procedures, evidence and review records.
|
||||
- [AMD RDNA2 desktop GPU (gfx1030) form acceptance](testing/shader-form-acceptance.md) — Independence, command, log and promotion rules for fixture-verified instruction forms.
|
||||
- [Engineering progress](progress.md) — Verification commands, metric definitions, and open release gates.
|
||||
- [CPU test runtime and shard selection](testing/cpu-coverage.md) — Measured CPU gate cost and deterministic test-target shards.
|
||||
- [CPU test runtime, shards and coverage map](testing/cpu-coverage.md) — Measured CPU gate cost, deterministic test-target shards, and a verified per-operation CPU/loader coverage map with exact test evidence.
|
||||
- [Test inventory comparison](testing/test-inventory.md) — Detect missing or newly ignored Cargo tests across commits.
|
||||
- [Persistent resource and translated rendering acceptance](testing/x9-acceptance.md) — Pinned upstream tests, native ARM64 results and unsupported cases.
|
||||
- [Baseline acceptance](testing/phase-02-baseline.md), [Phase 01 assurance](testing/phase01-assurance.md), and [independent reviews](testing/review-log.md) — Candidate-specific results and release findings.
|
||||
@@ -60,7 +68,14 @@ Historical phase checkpoints retain their original evidence scope.
|
||||
|
||||
- [Public sources](research/sources.md), [RDNA 2 notes](research/rdna2.md), and [Xbox GPU evidence](research/xbox-gpu.md) — Specifications, evidence scope, and unknown console behavior.
|
||||
- [Shader inputs](research/shader-containers.md) and [risk register](risk-register.md) — Input provenance and unresolved engineering risks.
|
||||
- [victory-shader provenance review](research/victory-shader-provenance.md) — Per-file licence and origin record for the proposed import; not approved, maintainer decision pending.
|
||||
- [victory-shader integration](research/victory-shader-integration.md) — The vendored GFX10-to-DXIL recompiler, how BetterXen's fixtures run through it on the GPU under CrossOver, and what is not verified.
|
||||
- [Shader wave-semantics investigation](research/shader-wave-semantics.md) — Why two upstream wave tests failed under D3DMetal: device capabilities, independent probes, the fix and its limits.
|
||||
- [Texture format inventory](research/texture-formats.md) — Formats and layouts by stage (decode, layout, native upload, sampling, guest), their public specifications, unknowns and ranked follow-ups.
|
||||
- [PortWatch native macOS research](research/portwatch-native-macos.md) — Screening of public Xbox-on-Windows port projects for native macOS planning; discovery only.
|
||||
- [Synthetic integration and upstream evidence](research/synthetic-integration.md) — Audited source snapshots and remaining commercial startup prerequisites.
|
||||
- [Hybrid backlog research record](research/hybrid-backlog-research-2026-11-25.md) — Findings, registry candidates and the issues they produced (2026-11-25); not verified on hardware.
|
||||
- [Primary-source verification](research/primary-source-verification-2026-11-25.md) — Which hybrid-research claims were confirmed, contradicted or left unverified against vendor documentation.
|
||||
|
||||
## Security, licensing, and contributions
|
||||
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
# ADR 0005: CrossOver-based hybrid direction
|
||||
|
||||
Status: **Accepted (strategic direction).** Accepted by the maintainers' planning directive of 2026-11-25. The proposed technical architecture below is **not** accepted or verified; each integration still needs validation.
|
||||
|
||||
## Context
|
||||
|
||||
BetterXen was developed native-first: an independent x86-64 decoder, interpreter, ARM64 translator, runtime, shader compiler and Metal backend, verified only on synthetic programs and shaders. No Xbox title runs on it. The maintainers decided to focus all active engineering on a hybrid architecture and to pause native work.
|
||||
|
||||
## Accepted strategic direction
|
||||
|
||||
- CrossOver is the primary compatibility foundation, installed externally.
|
||||
- Hybrid is the only active development direction. Native research is preserved (tag `native-first-final` marks the last `main` commit before this change; the code stays in the workspace) and paused; resuming needs an explicit maintainer decision.
|
||||
- Reuse established infrastructure; build independent replacements only for demonstrated limitations.
|
||||
- The engineering rules in `AGENTS.md` (and `CLAUDE.md`, a symlink) were rewritten accordingly, replacing the former prohibition on Wine, CrossOver, Rosetta and MoltenVK.
|
||||
|
||||
## Proposed technical architecture (not accepted)
|
||||
|
||||
BetterXen provides integration, configuration, environment management, diagnostics, reproducible testing, benchmarking and measured optimization around CrossOver. Within CrossOver, the intended layers are Wine-based runtime APIs, Rosetta 2 for x86-64 translation and D3DMetal or DXMT for graphics, on Apple Silicon (ARM64, Metal, unified memory). The exact responsibility boundary is decided in #351, at the end of Phase 1.
|
||||
|
||||
## Unverified integration assumptions
|
||||
|
||||
- That CrossOver, Rosetta 2, D3DMetal or DXMT run any authorized workload BetterXen needs. Assumed not until measured (#355).
|
||||
- That CrossOver offers supported interfaces for bottle management, configuration, launching and diagnostics (#350).
|
||||
- Rosetta 2's support lifetime and D3DMetal's license terms (#349, #354).
|
||||
- That any of this provides Xbox runtime compatibility. It is assumed not to.
|
||||
|
||||
## Verified implementation capabilities
|
||||
|
||||
None for the hybrid architecture. Verified native-research capabilities (synthetic evidence only) are unchanged and listed in `docs/progress.md`.
|
||||
|
||||
## Planning consequence
|
||||
|
||||
Planning is progressive: Phase 1 (research, feasibility and baseline) is the only active phase; later phases are provisional and defined from its findings. Native work is paused indefinitely.
|
||||
|
||||
## Consequences
|
||||
|
||||
Positive: reuse of mature infrastructure. Negative: dependence on a proprietary vendor and on Rosetta 2 availability; limited ability to modify closed components; the former "No Wine, No CrossOver, No Rosetta" project identity is retired for active work. Anything derived from leaked or unauthorized material stays excluded, including projects built for such inputs (see the upstream registry).
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
Continue native-first; maintain both tracks at 75/25; a generic Wine-based stack without CrossOver.
|
||||
@@ -1,3 +1,5 @@
|
||||
> **Archived 2026-11-25 (superseded). Not the active plan.** Native-first plan retained for history; the active roadmap is [../roadmap.md](../roadmap.md). Relative links below were written for `docs/` and may need `../`.
|
||||
|
||||
# BetterXen development phases
|
||||
|
||||
This is BetterXen's working development plan. Each phase ends with a reproducible
|
||||
@@ -26,10 +28,10 @@ Historical results below remain evidence for their recorded candidates only.
|
||||
| Native app | Swift app, Rust C interface, controller input and audio/virtual-filesystem fixtures | Existing fixtures do not establish one integrated threaded C++ 3D application. |
|
||||
| Quality tools | CPU/runtime inventories, shader coverage reconciliation, task queue, PR checks and acceptance records | Some inventories and ledgers contain stale limitation text. A successful tool invocation does not prove every catalog entry is current. |
|
||||
|
||||
Sources: [CPU registry](cpu/instruction-registry.md),
|
||||
[runtime registry](runtime/registry.md), [guest threads](runtime/threads.md),
|
||||
[interfaces](interfaces.md), [shader coverage](shaders/semantic-coverage.md),
|
||||
[Gate A](testing/gate-a.md), and [QA tooling](testing/infrastructure/README.md).
|
||||
Sources: [CPU registry](../cpu/instruction-registry.md),
|
||||
[runtime registry](../runtime/registry.md), [guest threads](../runtime/threads.md),
|
||||
[interfaces](../interfaces.md), [shader coverage](../shaders/semantic-coverage.md),
|
||||
[Gate A](../testing/gate-a.md), and [QA tooling](../testing/infrastructure/README.md).
|
||||
The read-only shader reconciliation reported zero mismatches during this task;
|
||||
that result is inventory consistency, not new GPU verification.
|
||||
|
||||
@@ -40,18 +42,18 @@ but their phase numbers are not the sequence for new BetterXen work.
|
||||
|
||||
| Existing record or name | Meaning | How to use it now |
|
||||
| --- | --- | --- |
|
||||
| [Phase 01 checkpoints and assurance](testing/phase01-assurance.md), [risk register](risk-register.md), [review log](testing/review-log.md) and [mutation record](testing/mutation.md) | Earlier bounded shader research and candidate-specific gates | Consult the original gate definitions and unresolved findings; do not relabel them as current acceptance. |
|
||||
| [Phase 02 GPU/guest baseline](testing/phase-02-baseline.md) and [CPU feasibility](research/phase02-cpu-feasibility.md), [ecosystem](research/phase02-ecosystem.md), [collaboration](research/phase02-collaboration.md) research | Early graphics expansion and CPU feasibility work | Reuse documented public sources and evidence limits, checking them against current source. |
|
||||
| [CPU/runtime campaign ledger](coordination/cpu-campaign-ledger.md) | Implementation batches and local evidence | Its older limitations are not a current feature inventory: scheduler, atomic and string work has since landed. |
|
||||
| [Infrastructure Phase II/III tooling](testing/infrastructure/README.md) and [compatibility ledger](testing/infrastructure/phase3-compat-ledger.md) | A separate QA campaign | Tool code now includes compatibility-gap analysis and verification profiles beyond the ledger's early checkpoint. Coordinate with existing issue #219 rather than starting another QA framework. |
|
||||
| [Gate A](testing/gate-a.md) | Compiled C execution, split into A1 and hosted-C A2 | A1 has a main-branch test. A2 is under review in PR #283; the document's “not started” description predates that PR. Neither is independently accepted by this plan. |
|
||||
| [Phase 01 checkpoints and assurance](../testing/phase01-assurance.md), [risk register](../risk-register.md), [review log](../testing/review-log.md) and [mutation record](../testing/mutation.md) | Earlier bounded shader research and candidate-specific gates | Consult the original gate definitions and unresolved findings; do not relabel them as current acceptance. |
|
||||
| [Phase 02 GPU/guest baseline](../testing/phase-02-baseline.md) and [CPU feasibility](../research/phase02-cpu-feasibility.md), [ecosystem](../research/phase02-ecosystem.md), [collaboration](../research/phase02-collaboration.md) research | Early graphics expansion and CPU feasibility work | Reuse documented public sources and evidence limits, checking them against current source. |
|
||||
| [CPU/runtime campaign ledger](../coordination/cpu-campaign-ledger.md) | Implementation batches and local evidence | Its older limitations are not a current feature inventory: scheduler, atomic and string work has since landed. |
|
||||
| [Infrastructure Phase II/III tooling](../testing/infrastructure/README.md) and [compatibility ledger](../testing/infrastructure/phase3-compat-ledger.md) | A separate QA campaign | Tool code now includes compatibility-gap analysis and verification profiles beyond the ledger's early checkpoint. Coordinate with existing issue #219 rather than starting another QA framework. |
|
||||
| [Gate A](../testing/gate-a.md) | Compiled C execution, split into A1 and hosted-C A2 | A1 has a main-branch test. A2 is under review in PR #283; the document's “not started” description predates that PR. Neither is independently accepted by this plan. |
|
||||
| Native app numbered gates in `crates/ffi` and `app` | Bounded session, graphics, audio and filesystem fixtures | Inspect their tests before proposing integration. Gate numbers are separate from shader acceptance gates. |
|
||||
| README X1–X25 milestones | Broad capability map | Retain as a capability reference; use the phases below for the next work order. |
|
||||
| Supplied Discord III, III-B, IV, V and VI excerpts | Broad runtime, graphics, application and performance objectives | Only excerpts were supplied. Their omitted requirements and completion status are unknown; they are not execution instructions. |
|
||||
|
||||
Bare issue numbers in historical documents may refer to the source repository.
|
||||
All issue and PR links in the work sections below refer to **MacosPorters/betterxen**.
|
||||
Use [migration records](migration.md) to resolve historical references.
|
||||
Use [migration records](../migration.md) to resolve historical references.
|
||||
|
||||
## Phase 1 — Establish a trustworthy working baseline
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
# Detailed hybrid phases H0 to H7 (retired planning)
|
||||
|
||||
**Archived 2026-11-25; not the active plan.** These eight phases were defined before any research had been done. The active roadmap is [../roadmap.md](../roadmap.md): five provisional phases, with only Phase 1 active. The text below preserves the objectives, scope and exit conditions of the retired H2 to H7 milestones (and H0/H1) for reference when later phases are defined. Issue numbers in it are historical.
|
||||
|
||||
## Phases as originally written
|
||||
|
||||
### H0 — CrossOver Architecture Transition
|
||||
|
||||
**Status:** In development
|
||||
|
||||
**Objective:** Make CrossOver the single authoritative active compatibility foundation across the repository and GitHub planning surfaces.
|
||||
|
||||
**Scope:** README, architecture docs, ADR 0005, rewritten engineering rules, roadmap, upstream research registry, technical plans, labels, milestones, issue and PR templates, issue triage, project board, preservation of the native implementation.
|
||||
|
||||
**Dependencies:** None.
|
||||
|
||||
**Deliverables:** Updated README and docs; ADR 0005; docs/roadmap.md; deferred docs/research/native-roadmap.md; rebuilt issues and milestones; project board; preserved native code.
|
||||
|
||||
**Validation:** Repository link/terminology check; GitHub consistency check.
|
||||
|
||||
**Exit conditions:** Repository, documentation, issues, milestones and board consistently state the CrossOver-based direction. The project board requires a token with the project scope and is not yet configured.
|
||||
|
||||
**Known risks:** Project board cannot be configured without the GitHub project token scope (#346). The engineering rules conflict was resolved by rewriting AGENTS.md (#345).
|
||||
|
||||
### H1 — CrossOver Research and Baseline
|
||||
|
||||
**Status:** Not started
|
||||
|
||||
**Objective:** Establish what the installed CrossOver version actually provides and a reproducible baseline, without assuming it provides Xbox runtime compatibility.
|
||||
|
||||
**Scope:** CrossOver architecture, supported macOS versions, Apple Silicon support, relationship to upstream Wine, CPU translation mechanism, graphics backends (D3DMetal, DXMT and others), supported Direct3D versions, configuration interfaces, documented command-line interfaces, bottle management, diagnostics and profiling options, licensing and redistribution, supported integration mechanisms, long-term maintenance. Open-source and proprietary components distinguished.
|
||||
|
||||
**Dependencies:** Engineering rules rewritten (#345, done). CrossOver is an externally installed dependency until its license says otherwise; nothing is bundled.
|
||||
|
||||
**Deliverables:** CrossOver capability and integration-boundary report; licensing and dependency assessment; reproducible environment; baselines of CPU, GPU, memory and stability on authorized workloads.
|
||||
|
||||
**Validation:** Every claim cites vendor or upstream documentation, or a recorded observation on the installed version. Unknown stays unknown. Equivalent workloads, settings, hardware and software versions.
|
||||
|
||||
**Exit conditions:** Capabilities and integration boundaries are documented for the installed version; environment is reproducible by another contributor; baselines recorded; BetterXen vs CrossOver responsibilities proposed.
|
||||
|
||||
**Known risks:** CrossOver is proprietary: bundling, modifying or redistributing may be prohibited; integration interfaces may be undocumented; Xbox titles may not run at all.
|
||||
|
||||
### H2 — BetterXen Integration Foundation
|
||||
|
||||
**Status:** Not started
|
||||
|
||||
**Objective:** Build the BetterXen layer around CrossOver: integration boundaries, configuration, diagnostics, reproducible test workflows and host integration.
|
||||
|
||||
**Scope:** Environment and configuration management, diagnostics, test workflows, verified host integration, regression testing. Only what CrossOver does not already provide adequately.
|
||||
|
||||
**Dependencies:** H1.
|
||||
|
||||
**Deliverables:** Boundary document; configuration and environment management where justified; diagnostic infrastructure; reproducible test workflows; verified host integration; regression tests.
|
||||
|
||||
**Validation:** Independent contributor reproduces the workflows; no placeholder components.
|
||||
|
||||
**Exit conditions:** Integration foundation builds, tests and reproduces on a second setup.
|
||||
|
||||
**Known risks:** Reliance on undocumented or changing CrossOver behavior.
|
||||
|
||||
### H3 — Compatibility Validation
|
||||
|
||||
**Status:** Not started
|
||||
|
||||
**Objective:** Evaluate authorized workloads and document verified behavior and limitations.
|
||||
|
||||
**Scope:** Authorized workloads, documented limitations, runtime behavior, graphics correctness, input and interaction, reproducible failures, integrated validation criteria.
|
||||
|
||||
**Dependencies:** H2.
|
||||
|
||||
**Deliverables:** Validation criteria; per-workload results; reproducible failure reports; verified runtime, graphics and input results.
|
||||
|
||||
**Validation:** Independent verification of rendering and behavior. Startup or a screenshot alone is not proof.
|
||||
|
||||
**Exit conditions:** Selected workloads show verified integrated behavior under documented criteria; failures reproducible.
|
||||
|
||||
**Known risks:** Failures may originate in CrossOver or its components outside project control.
|
||||
|
||||
### H4 — Graphics and Performance Engineering
|
||||
|
||||
**Status:** Not started
|
||||
|
||||
**Objective:** Evaluate graphics backends and optimize only demonstrated bottlenecks.
|
||||
|
||||
**Scope:** Supported backends, CPU/GPU utilization, unified memory, frame-time consistency, synchronization, shader compilation and caching. Metrics: average FPS, 1% low, frame-time percentiles, CPU and GPU utilization, unified memory, memory pressure, translation overhead where measurable, shader compile latency, startup, thermals, long-duration stability. Reference machine: M4 Mac, 24 GB.
|
||||
|
||||
**Dependencies:** H3; measurement protocol.
|
||||
|
||||
**Deliverables:** Backend comparison; profiling reports; bottleneck list; before/after results; regression tests.
|
||||
|
||||
**Validation:** Equivalent workloads, rendering settings, hardware and versions; correctness and rendering equivalence verified.
|
||||
|
||||
**Exit conditions:** Improvements measurable, reproducible and without loss of correctness or stability. No improvement is promised before measurement.
|
||||
|
||||
**Known risks:** Many components are closed and not modifiable; single reference machine.
|
||||
|
||||
### H5 — Stability and Hardware Scaling
|
||||
|
||||
**Status:** Not started
|
||||
|
||||
**Objective:** Evaluate Apple Silicon configurations, memory pressure, thermals and long-duration stability.
|
||||
|
||||
**Scope:** Available Apple Silicon configurations, memory pressure, thermal behavior, long-duration tests, hardware documentation, regression coverage.
|
||||
|
||||
**Dependencies:** H3; hardware access.
|
||||
|
||||
**Deliverables:** Hardware compatibility documentation; memory-pressure and thermal reports; long-duration results; expanded regression coverage.
|
||||
|
||||
**Validation:** Each documented configuration backed by a test run on it.
|
||||
|
||||
**Exit conditions:** Tested configurations documented; untested hardware never claimed.
|
||||
|
||||
**Known risks:** Only one reference machine currently available.
|
||||
|
||||
### H6 — Hybrid Architecture Maturity
|
||||
|
||||
**Status:** Not started
|
||||
|
||||
**Objective:** Maintainable integration infrastructure and contributor workflows.
|
||||
|
||||
**Scope:** Contributor workflows, verified-capability documentation, reproducible performance results, complexity reduction, long-term dependency risk (CrossOver, Rosetta 2, D3DMetal).
|
||||
|
||||
**Dependencies:** H3 to H5 evidence.
|
||||
|
||||
**Deliverables:** Maintainable infrastructure; contributor documentation; verified capability list; reproducible results; dependency risk assessment.
|
||||
|
||||
**Validation:** Contributors other than the authors maintain the workflow.
|
||||
|
||||
**Exit conditions:** The architecture shows demonstrated value and the team can maintain it.
|
||||
|
||||
**Known risks:** Vendor decisions (CrossOver licensing, Rosetta lifetime) are outside project control.
|
||||
|
||||
### H7 — Future Native Reassessment (deferred)
|
||||
|
||||
**Status:** Not started
|
||||
|
||||
**Objective:** Deferred. Reassess independent native components only on an explicit maintainer decision or when one offers a demonstrated benefit to the active architecture.
|
||||
|
||||
**Scope:** See docs/research/native-roadmap.md.
|
||||
|
||||
**Dependencies:** Explicit maintainer decision.
|
||||
|
||||
**Deliverables:** Reassessment record.
|
||||
|
||||
**Validation:** Maintainer decision recorded in an ADR.
|
||||
|
||||
**Exit conditions:** A recorded decision to continue, resume specific native work, or archive components.
|
||||
|
||||
**Known risks:** Premature reinvention of mature infrastructure.
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
[{"closed_issues":15,"description":"G1–G15 for the bounded native ARM64 and Metal graphics foundation. Release acceptance requires all gates on the exact candidate.","html_url":"https://github.com/MacosPorters/betterxen/milestone/1","number":1,"open_issues":0,"state":"open","title":"Phase 01 - Native Graphics Foundation"},{"closed_issues":7,"description":"Develop independently authored interoperability tests and fixtures from public specifications. External emulator results may inform test selection. Xenora owns its Rust ARM64 runtime, decoder, typed IR, shader compiler and Metal backend. Emulator code, ports, decoder tables, internal metadata and platform-specific dependencies are outside scope.","html_url":"https://github.com/MacosPorters/betterxen/milestone/2","number":2,"open_issues":0,"state":"open","title":"Phase 02 - Ecosystem Integration"},{"closed_issues":8,"description":"Expand independently verified gfx1030 semantics, resource access, wave behavior and native offscreen drawing.\n\n### Deferred engineering\n- [#25](https://github.com/ranveersoni98/Xenora/issues/25) · Verify Wave64 pairing on native Metal. Exercise both halves, cross-half operations, asymmetric masks and barrier safety with 64-lane readback.\n- [#27](https://github.com/ranveersoni98/Xenora/issues/27) · Translate bounded vertex and fragment fixtures. Define stage IO and interpolation from public specifications; verify exact offscreen pixels.","html_url":"https://github.com/MacosPorters/betterxen/milestone/3","number":3,"open_issues":0,"state":"open","title":"Phase 03 - Graphics Maturation"},{"closed_issues":6,"description":"Measure correctness-gated CPU, translation and GPU behavior under reproducible host conditions. Track capability and failure evidence.\n\n### Deferred engineering\n- [#33](https://github.com/ranveersoni98/Xenora/issues/33) · Measure Metal pipeline reuse and cache identity. Separate cold and warm timing; test cache invalidation and verify shared output expectations.","html_url":"https://github.com/MacosPorters/betterxen/milestone/4","number":4,"open_issues":0,"state":"open","title":"Phase 04 - Performance and Compatibility"},{"closed_issues":7,"description":"Grow the bounded interpreter and independently demonstrate ARM64 recompilation, with precise state and fault behavior.\n\n### Deferred engineering\n- [#40](https://github.com/ranveersoni98/Xenora/issues/40) · Choose first measured recompilation target. Use interpreter profiles to choose one bounded basic block and document precise state and fault requirements.\n- [#41](https://github.com/ranveersoni98/Xenora/issues/41) · Execute one translated ARM64 guest basic block. Execute emitted ARM64 code natively, compare registers, flags, memory and traps with interpreter and independent vectors.\n- [#42](https://github.com/ranveersoni98/Xenora/issues/42) · Verify code cache and executable memory policy. Validate mapping permissions, publication, invalidation and dependency provenance on macOS.\n- [#43](https://github.com/ranveersoni98/Xenora/issues/43) · Measure ARM64 translation performance. Compare correctness-gated translated and interpreted inputs with matched native runs and resource records.","html_url":"https://github.com/MacosPorters/betterxen/milestone/5","number":5,"open_issues":0,"state":"open","title":"Phase 05 - CPU Recompilation"},{"closed_issues":6,"description":"Build isolated guest loading, memory, services and checked CPU-to-GPU commands using original inputs.\n\n### Deferred engineering\n- [#49](https://github.com/ranveersoni98/Xenora/issues/49) · Expand synthetic services and authorized runtime boundaries. Define explicit service ABI, faults and lifetimes with original inputs. Document evidence gaps for authentic Xbox platform contracts.\n\nFuture import behavior is tracked in [#55](https://github.com/ranveersoni98/Xenora/issues/55). Compatibility checks do not inspect user acquisition or ownership.","html_url":"https://github.com/MacosPorters/betterxen/milestone/6","number":6,"open_issues":0,"state":"open","title":"Phase 06 - Runtime Infrastructure"},{"closed_issues":5,"description":"Validate the integrated execution path and exact release candidate. Project-run title testing requires suitable inputs and independent evidence. The loader evaluates format and compatibility without checking where user files came from.","html_url":"https://github.com/MacosPorters/betterxen/milestone/7","number":7,"open_issues":1,"state":"open","title":"Phase 07 - Integrated Validation"}]
|
||||
@@ -0,0 +1,70 @@
|
||||
# Native-first README milestones (archived)
|
||||
|
||||
**Archived 2026-11-25; paused native research, not the active plan.** This section was the README's "Milestones" content on `main` when BetterXen moved to the CrossOver-based hybrid direction. Statuses describe the native implementation only, with synthetic evidence. The active plan is the [roadmap](../roadmap.md). Links below were written for the repository root README and may need adjusting.
|
||||
|
||||
## Native-first milestones
|
||||
|
||||
BetterXen's work order is the six [development phases](development-phases-native-first.md), which lead to one concrete target: the **first launchable application** (tracker [#311](https://github.com/MacosPorters/betterxen/issues/311)). That target is an original C program, built with native ARM64 tools, that runs through the ARM64 translator, controls its own translated shader pipeline, and shows its Metal frame in the native app window. It is **not** a commercial or authentic Xbox title, and no date or percentage is attached to it.
|
||||
|
||||
```mermaid
|
||||
%%{init: {'theme':'base','themeVariables':{'fontFamily':'system-ui, sans-serif','lineColor':'#6e7781'}}}%%
|
||||
flowchart LR
|
||||
P1["<b>Phase 1</b><br/>Trustworthy baseline"]:::wip --> P2["<b>Phase 2</b><br/>Hosted C application"]:::wip
|
||||
P2 --> P3["<b>Phase 3</b><br/>Coherent threading"]:::wip
|
||||
P3 --> P4["<b>Phase 4</b><br/>Resource updates<br/>to translated rendering"]:::wip
|
||||
P4 --> P5["<b>Phase 5</b><br/>One integrated<br/>interactive application"]:::plan
|
||||
P5 --> P6["<b>Phase 6</b><br/>Measured performance"]:::plan
|
||||
P2 --> L(["<b>First launchable app</b><br/>issue 311"]):::goal
|
||||
P4 --> L
|
||||
classDef wip fill:#fff8c5,stroke:#9a6700,color:#4d2d00
|
||||
classDef plan fill:#eaeef2,stroke:#8c959f,color:#24292f
|
||||
classDef goal fill:#dafbe1,stroke:#1a7f37,color:#0f5323,stroke-width:3px
|
||||
```
|
||||
|
||||
<sub>🟨 work under way · ⬜ not started · 🟩 the next original-workload target. Nothing here is independently accepted.</sub>
|
||||
|
||||
| Phase | Goal | State | What exists now |
|
||||
| --- | --- | --- | --- |
|
||||
| **1 · Baseline** | Contributors can tell what exists on `main`, what is pending review, and which checks ran | 🟡 In progress | CODEOWNERS review, a fast repository hygiene check, claim-before-work rules, generated status tables and claim audits |
|
||||
| **2 · Hosted C application** | An original hosted C program starts, uses the runtime, reports results and exits with checked cleanup | 🟡 In progress | CRT startup, arguments, exit handlers, formatted output, file streams and the hosted-C fixture (A2) are integrated; a stdio follow-up is still open and the result is not independently accepted |
|
||||
| **3 · Threaded behavior** | A worker-based application can block and resume without stalling other guest work | 🟡 In progress | Deterministic scheduler, guest thread contexts, guarded stacks and thread services. Guest `Sleep` still delays all guest threads (#304); worker TLS and callback lifecycle is a design draft (#312) |
|
||||
| **4 · Resource updates to rendering** | A guest updates a texture and geometry, submits translated rendering and gets a checked frame | 🟡 In progress | Persistent resources, descriptor-table texture binding, translated vertex and pixel stages, blend, depth and indexed draws. Guest-selected pipelines and the typed graphics bridge are open (#314–#316) |
|
||||
| **5 · Integrated interactive app** | Guest execution, rendering, input, audio, filesystem and lifecycle in one session | ⚪ Planned | Swift app with frame loop, input, audio and sandboxed filesystem fixtures exists, but those demonstrations are not guest-integration evidence |
|
||||
| **6 · Measured performance** | Faster execution of workloads whose correctness is already checked | ⚪ Planned | Startup, DBT and TLS measurements recorded; bottlenecks are chosen from measurements, not assumed |
|
||||
|
||||
The launch milestone's proposed acceptance is **60 bounded frames containing two independently distinguishable guest-controlled states, then a clean close and one restart**. Sixty is a fixture criterion, not a measured frame rate. The work is tracked as issues [#313](https://github.com/MacosPorters/betterxen/issues/313)–[#323](https://github.com/MacosPorters/betterxen/issues/323).
|
||||
|
||||
<details>
|
||||
<summary><b>Capability reference: the original X1–X25 map</b></summary>
|
||||
|
||||
The X1–X25 names are an older, broad capability map. Keep them as a reference; use the phases above for the next work order. X10–X25 are proposed engineering milestones, not completed implementations or a guaranteed sequence.
|
||||
|
||||
| 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 | One translated `image_sample_lz` pixel stage with point/clamp sampling of RGBA8 and BC1 2D textures bound through descriptor tables, locally verified on Apple M5 Pro; upload, readback and decode of BC compressed formats (see [Texture support](#texture-support)). Other image instructions and formats are not implemented | Implemented subset |
|
||||
| X11 — Graphics pipeline | Bounded multi-draw passes into offscreen RGBA8 targets: translated vertex and pixel stages, indexed triangle draws, colour write masks and blend state | Implemented |
|
||||
| X12 — Wave execution | Expand Wave32/Wave64 semantics, divergent control flow, cross-lane operations, LDS and barriers | Planned |
|
||||
| X13 — Advanced shaders | Mesh, geometry and additional compute shader capabilities with verified Metal execution | Planned |
|
||||
| X14 — CPU recompilation | Native ARM64 dynamic recompilation of supported x86-64 instructions in synthetic fixtures | Implemented subset |
|
||||
| X15 — Executable compatibility | Static PE inspection reports sections, relocations, thread-local storage (TLS) callbacks, imports and entry-point instructions | Static probe implemented |
|
||||
| X16 — Guest memory and threading | Virtual memory mapping, thread scheduling, synchronization primitives and atomic operations | Implemented subset |
|
||||
| X17 — System services | Implement a tested subset of Xbox-compatible runtime APIs, memory services, filesystem access and application lifecycle | Implemented subset |
|
||||
| X18 — Graphics API translation | Translate supported Xbox graphics commands, resource descriptors, command queues, barriers and fences into Metal operations | Planned |
|
||||
| X19 — Advanced GPU features | Indirect rendering, asynchronous compute, additional texture formats and ray-tracing compatibility research | Planned |
|
||||
| X20 — Integrated guest runtime | Connect CPU recompilation, executable loading, system services and graphics translation into one persistent runtime | Planned |
|
||||
| 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 |
|
||||
|
||||
</details>
|
||||
@@ -36,10 +36,9 @@ pending-run replay and exact head-SHA verification against a real repository.
|
||||
|
||||
## Production follow-ups
|
||||
|
||||
1. Keep `agent-pr-checks` advisory until this evidence is reviewed.
|
||||
2. Coordinate adding `pull-requests: read` to the production audit job permissions
|
||||
1. Coordinate adding `pull-requests: read` to the production audit job permissions
|
||||
(same defect as the smoke audit failure).
|
||||
3. Add a second QA-eligible verifier before treating `/verified` as smoke-complete.
|
||||
2. Add a second QA-eligible verifier before treating `/verified` as smoke-complete.
|
||||
|
||||
## Local unit suite
|
||||
|
||||
|
||||
@@ -90,22 +90,6 @@ cycles `agent:invalid` (and restores them when fixed), flags overlapping claims
|
||||
writes a JSON summary to the run summary. `scripts/agent-queue.sh status --json` prints the same
|
||||
machine-readable summary (counts and lists per area, priority and state).
|
||||
|
||||
## Pull request checks
|
||||
|
||||
`agent-pr-checks` fails a pull request when: it has no `Closes #N` for a claimed task; the task is held
|
||||
by someone else; it changes files outside the task's patterns; it changes a file that another open
|
||||
pull request also changes; the claim has lapsed without a push; or no eligible `/verified <current
|
||||
head sha>` exists. The SHA must be the full 40 characters and the only argument: a commit with the
|
||||
same short prefix is cheap to make. After an accepted `/verified` (an eligible verifier, the current
|
||||
head) the verify job evaluates the same check again and writes it to its run summary; the earlier
|
||||
check run is not re-run, since `pull_request_target` runs are recorded against the base branch and
|
||||
cannot be found by the pull request head. Refused, stale, malformed or unauthorized `/verified`
|
||||
comments get a reply and nothing else, and other pull request comments start no job.
|
||||
|
||||
The check is advisory for now: a failure is shown as a warning and in the run summary, and the job
|
||||
still succeeds. It becomes blocking (fail on problems, then a required check) only after a live smoke
|
||||
test on GitHub and the migration of existing issues into the queue.
|
||||
|
||||
## Forks and upstream sync
|
||||
|
||||
Work from a fork, but synchronise against the real upstream (`ranveersoni98/Xenora` in the
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
# Proposed AVX and AVX2 guest contract
|
||||
|
||||
[Issue #299](https://github.com/MacosPorters/betterxen/issues/299) defines a
|
||||
reviewable first step for Advanced Vector Extensions (AVX) in the x86-64 guest.
|
||||
The current [instruction registry](instruction-registry.md) rejects VEX prefixes.
|
||||
[`CpuState`](../../crates/loader/src/cpu.rs) holds 16 XMM registers and MXCSR,
|
||||
the SIMD floating-point control and status register. The synthetic `CPUID`
|
||||
advertises basic leaves through 1 and reports no AVX or extended-state support.
|
||||
|
||||
The architectural expectations come from the public Intel Software Developer's
|
||||
Manual and apply to BetterXen's synthetic x86-64 guest profile. Which AVX and
|
||||
AVX2 features Xbox Series X|S CPUs expose, and which extended register state
|
||||
the console OS enables for applications, remain open research questions.
|
||||
Resolving them requires public platform documentation or authorized hardware
|
||||
evidence.
|
||||
|
||||
## Architectural state and encoding
|
||||
|
||||
In 64-bit mode, XMM0–XMM15 alias bits 127:0 of YMM0–YMM15. A legacy SSE
|
||||
instruction that writes an XMM destination preserves bits 255:128. For the
|
||||
packed VEX.128 forms in this proposal, writing an XMM destination clears that
|
||||
register's upper 128 bits. A VEX.256 register destination replaces all 256 bits.
|
||||
A store to memory leaves its source vector register intact. The proposed moves
|
||||
and integer add leave RFLAGS and MXCSR unchanged. [Intel SDM Vol. 1, §14.8,
|
||||
Accessing YMM Registers][sdm-ymm]. [Intel SDM Vol. 2B, MOVDQU and PADDD][sdm-2b].
|
||||
|
||||
The shared [decoder](../../crates/loader/src/x86_decode.rs) should retain the
|
||||
prefix family, opcode map, mandatory prefix, operand width and register
|
||||
extensions until it selects the form. In 64-bit mode the VEX lead byte
|
||||
identifies the prefix length. The table lists each payload byte's fields
|
||||
from bit 7 to bit 0.
|
||||
|
||||
| Lead byte | Payload byte 1 | Payload byte 2 | Implied fields |
|
||||
| --- | --- | --- | --- |
|
||||
| `C5` | `~R ~vvvv L pp` | — | Map `0F`, `W=0`, logical `X=B=0` |
|
||||
| `C4` | `~R ~X ~B mmmmm` | `W ~vvvv L pp` | Map selected by `mmmmm` |
|
||||
|
||||
The tilde indicates an inverted encoding. `R` extends ModRM.reg, while `X`
|
||||
and `B` extend the applicable index and r/m or base fields. `vvvv` supplies
|
||||
the first source of `VPADDD`. For `VMOVDQU` its encoded bits must be `1111b`.
|
||||
`L=0` selects 128 bits and `L=1` selects 256 bits for these forms. The three
|
||||
standard VEX maps are `00001b` (`0F`), `00010b` (`0F 38`) and `00011b`
|
||||
(`0F 3A`). `pp` values 0 through 3 represent no mandatory prefix, `66`, `F3`
|
||||
and `F2`. Both initial opcodes are in `0F`, with `W` ignored (`WIG`). Decode
|
||||
both valid prefix lengths for them. Reject reserved maps and encodings,
|
||||
including a physical `LOCK`, `66`, `F2`, `F3` or REX prefix before VEX, through
|
||||
the existing illegal-instruction path. Legal forms outside the implemented
|
||||
subset also stop explicitly. Keep the existing register and effective-address
|
||||
rules and 15-byte fetch limit. [Intel SDM Vol. 2A, §2.3, VEX encoding][sdm-2a].
|
||||
[Intel SDM Vol. 2B, MOVDQU and PADDD][sdm-2b].
|
||||
|
||||
## First implementation increments
|
||||
|
||||
1. Append one upper 128-bit half per vector register to `CpuState`, retaining
|
||||
the existing XMM storage as the low halves. Add layout assertions for the
|
||||
offsets the dynamic binary translator (DBT) uses. Initialize both halves
|
||||
in a fresh guest thread and carry them with the thread state when switching
|
||||
or resuming. Add the shared VEX decoder and encoding controls before execution.
|
||||
2. Implement `VMOVDQU` (128 and 256 bits, `F3.0F`, `6F /r` and `7F /r`,
|
||||
register and checked memory forms) and `VPADDD` (128 and 256 bits,
|
||||
`66.0F`, `FE /r`, register sources initially). The instruction entries
|
||||
assign both move widths and 128-bit `VPADDD` to AVX, and 256-bit `VPADDD`
|
||||
to AVX2. Read all sources before publishing the destination, including
|
||||
when the destination aliases a source. Compare both engines with the
|
||||
[original fixture specification](../../tests/compat_fixtures/avx/README.md).
|
||||
3. After shared semantics pass, lower register moves and `VPADDD` to native
|
||||
ARM64 vector operations on one or two 128-bit halves. Each `VPADDD` half
|
||||
is four independent 32-bit additions modulo 2³². Use the checked-memory
|
||||
helper for loads and stores. Check the DBT's fallback counter so a run
|
||||
through that helper establishes only helper coverage for those forms.
|
||||
|
||||
Stage memory-source `VPADDD` and aligned moves separately. Reject masked
|
||||
moves, gathers, cross-half permutations, floating-point forms, FMA, EVEX
|
||||
and guest extended-state instructions in the initial slice. AMD64 bytes
|
||||
remain guest data. All host execution uses native ARM64 code or checked
|
||||
Rust helpers.
|
||||
|
||||
## Memory, faults and instruction budget
|
||||
|
||||
`VMOVDQU` permits unaligned operands. Check the complete 16- or 32-byte
|
||||
guest span before publishing a load result or writing a store. A split
|
||||
span across adjacent permitted mappings succeeds. A missing or protected
|
||||
mapping produces the existing guest memory fault at the first inaccessible
|
||||
byte. For a later `VMOVDQA` form, a memory operand must be aligned to its
|
||||
width (16 or 32 bytes), with a misaligned operand raising
|
||||
`GeneralProtection`. [Intel SDM Vol. 2B, MOVDQU and MOVDQA][sdm-2b].
|
||||
|
||||
Intel's Type 4 rules for `VMOVDQU` specify `#SS(0)` when a memory reference
|
||||
through the stack segment (SS) has a noncanonical address and `#GP(0)`
|
||||
for other noncanonical references. The initial BetterXen profile uses the
|
||||
[existing 48-bit guest address check](../../crates/loader/src/x86_exec.rs)
|
||||
and reports `GeneralProtection` for either segment case, including a span
|
||||
whose first byte is canonical and whose last byte is noncanonical. Check
|
||||
canonicality before guest memory lookup and before committing the move.
|
||||
Distinct stack-segment exception reporting remains outside this profile.
|
||||
[Intel SDM Vol. 2A, Table 2-21, Type 4 exceptions][sdm-2a].
|
||||
|
||||
Before adding masked moves, use a separate per-lane access contract. For
|
||||
`VPMASKMOVD`, only lanes with the high mask bit set may access memory or
|
||||
report a memory fault. A clear bit zeroes a load lane and leaves a store
|
||||
lane untouched. A test with lane 4 on an unmapped page must pass with that
|
||||
lane disabled and fault with it enabled. A full-width span check would
|
||||
incorrectly reject the disabled case. Specify store commit behavior before
|
||||
admitting that form. [Intel SDM Vol. 2C, VPMASKMOV][sdm-2c].
|
||||
|
||||
Require interpreter and DBT parity for the exit reason, fault address when
|
||||
reported, RIP, instruction count and complete guest register and memory
|
||||
state. A rejected move or add has no partial destination update and does
|
||||
not retire. A successful 256-bit instruction consumes one guest step even
|
||||
when the DBT emits two halves. With an exhausted budget, stop at the next
|
||||
guest RIP before decoding or executing that instruction. Check cold and warm
|
||||
DBT paths and resume in the middle of the same sequence.
|
||||
|
||||
## Feature exposure
|
||||
|
||||
Run the initial forms only in explicitly enabled synthetic test cases.
|
||||
Keep normal guest `CPUID` and extended-state behavior at the current baseline.
|
||||
Before guest-visible AVX support, the guest OS model needs coherent reporting
|
||||
for `CPUID.1:ECX` bits 26 (XSAVE), 27 (OSXSAVE) and 28 (AVX), and `XGETBV`
|
||||
with `ECX=0` must report both XMM and YMM state enabled in `XCR0[2:1]`. The
|
||||
extended-state layout reported by `CPUID.0Dh`, save and restore behavior,
|
||||
and per-thread ownership must agree. Verify the exception behavior for
|
||||
disabled state and invalid `XGETBV` selectors before exposing the facility.
|
||||
AVX2 separately requires `CPUID.(7,0):EBX[5]` and the same OS state. Gate
|
||||
each advertised feature on its full instruction and state contract,
|
||||
with probes for enabled and disabled combinations. [Intel SDM Vol. 1,
|
||||
§14.3, AVX detection][sdm-avx]. [Intel SDM Vol. 1, §14.7.1, AVX2 detection][sdm-avx2].
|
||||
[Intel SDM Vol. 2A, CPUID][sdm-2a]. [Intel SDM Vol. 2D, XGETBV, XSAVE and XRSTOR][sdm-2d].
|
||||
|
||||
[sdm-ymm]: https://cdrdv2-public.intel.com/843827/253665-sdm-vol-1-dec-24.pdf#page=376
|
||||
[sdm-avx]: https://cdrdv2-public.intel.com/843827/253665-sdm-vol-1-dec-24.pdf#page=359
|
||||
[sdm-avx2]: https://cdrdv2-public.intel.com/843827/253665-sdm-vol-1-dec-24.pdf#page=375
|
||||
[sdm-2a]: https://cdrdv2-public.intel.com/929353/253666-093-sdm-vol-2a.pdf
|
||||
[sdm-2b]: https://cdrdv2-public.intel.com/929354/253667-093-sdm-vol-2b.pdf
|
||||
[sdm-2c]: https://cdrdv2-public.intel.com/929355/326018-093-sdm-vol-2c.pdf
|
||||
[sdm-2d]: https://cdrdv2-public.intel.com/929356/334569-093-sdm-vol-2d.pdf
|
||||
@@ -141,6 +141,31 @@ pages count toward the 256 MiB mapping budget of one image, which is checked
|
||||
before anything is mapped. `ParsedPe::parse` does not make these checks, so
|
||||
static inspection of a file is unchanged.
|
||||
|
||||
`betterxen run --experimental --pe <trusted-fixture> --startup-report <path>`
|
||||
writes a versioned JSON summary after the worker stops. The supervisor creates the new report path before launching the worker.
|
||||
The report is optional and uses the same exact-byte fixture admission, startup
|
||||
observer and wall deadline as an ordinary run.
|
||||
|
||||
Schema version 1 lists the observed stages in order in `stages` and copies
|
||||
the last valid stage to `last_completed_stage` (null if none). The order is
|
||||
`parsed`, `mapped`, `relocated`, `imports_bound`, `tls_completed`, `entry`,
|
||||
`exit`, and `framebuffer`. `entry` records the handoff to guest entry.
|
||||
`exit` records the fixture halt, and `framebuffer` records verification of its
|
||||
offscreen readback. The supervisor reports an `outcome` of `verified`,
|
||||
`stage_failure`, `early_exit`, `timeout`, or `unknown`. It includes the
|
||||
worker exit code when available, termination detail when applicable, and the
|
||||
original reported error when available. Errors are capped at 2 KiB of UTF-8
|
||||
and carry an `error_truncated` flag.
|
||||
|
||||
The supervisor reads at most 8 KiB plus one byte from the worker journal.
|
||||
`record_integrity` reports `complete`, `truncated`, `malformed`, `oversized`,
|
||||
`unreadable`, or `unwritable`. Worker exit codes 124 and 125 are reserved for
|
||||
its watchdog and journal I/O errors, respectively. `--startup-journal` is an
|
||||
internal worker option. Only the valid ordered prefix counts toward progress. A
|
||||
complete journal may still contain only a partial startup if the worker
|
||||
stopped between records. These records describe runtime observations from
|
||||
the trusted fixtures.
|
||||
|
||||
`betterxen probe --mode static` inventories ordinary and delay-loaded PE imports
|
||||
without guest execution. Without `--report` it writes to `diagnostics/probe`,
|
||||
where `betterxen imports sync` also looks. `missing_imports.csv` lists unresolved ordinary keys
|
||||
|
||||
@@ -12,6 +12,9 @@ The workspace is GPL-3.0-or-later. The following is the lead's preliminary compa
|
||||
| bitflags | 2.13.2, `80ce9b545acb0bd42150695fc351889cac1d8eb4` | MIT from MIT OR Apache-2.0 | Runtime transitive dependency |
|
||||
| AMD RDNA 2 ISA XML | 2026-02-20, schema 1.1.1 | MIT | Source for generated decoder constants |
|
||||
| LLVM AMDGPU tools | 23.1.6 | Apache-2.0 WITH LLVM-exception | External fixture tool, not linked |
|
||||
| victory-shader (vendored) | victory-mac `22b3f8e45a59`, directory snapshot | GPL-3.0 (same as BetterXen's GPL-3.0-or-later); Mesa-derived opcode table MIT | GFX10-to-DXIL shader recompiler; see its UPSTREAM.md |
|
||||
| thiserror, zlib-rs, windows, windows-sys | 2.0.21, 0.6.8, 0.62.2, 0.61.2 | MIT OR Apache-2.0; Zlib; MIT OR Apache-2.0 | Dependencies of victory-shader; licences from each crate's metadata, not independently audited |
|
||||
| DirectX Shader Compiler | v1.9.2609, `dxc_2026_09_29.zip` (sha256 `ad31b1fc…a7e7f1`) | University of Illinois/NCSA plus MIT components (per its licence files) | External tool for compiling HLSL probes under CrossOver; not vendored, not distributed |
|
||||
| Xcode and Metal tools | Xcode 27.2 | Apple proprietary terms | External host tools, not distributed |
|
||||
|
||||
## Runtime redistribution review
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
# Project board setup
|
||||
|
||||
Status: **not configured, and not an engineering blocker.** The token used so far lacks the GitHub `project` scope, and GitHub's API cannot create views. Tracked by [#346](https://github.com/MacosPorters/betterxen/issues/346).
|
||||
|
||||
One simple board for active work only:
|
||||
|
||||
1. `gh auth refresh -s project`, then create a project named "BetterXen Development".
|
||||
2. Status (single select): Backlog, Ready, In Progress, In Review, Blocked, Done.
|
||||
3. Fields: Priority (p1, p2, p3), Area (text), and the built-in Milestone, Assignees and Status. No other custom fields.
|
||||
4. Add the open issues and pull requests (`gh project item-add`). Closed native issues stay out; they are indexed in [the native issue archive](../research/native-issue-archive.md).
|
||||
5. Optional view in the web UI: a table filtered to the current milestone and sorted by Priority. No phase views and no native board.
|
||||
@@ -0,0 +1,23 @@
|
||||
# Component reuse matrix
|
||||
|
||||
Companion to the [upstream registry](upstream-registry.md); same evidence limits (class D, nothing run, not legal advice). "External" means installed or supplied by the user and invoked, never bundled or copied. GPL-3.0-or-later is BetterXen's license.
|
||||
|
||||
| Need | Candidate | Decision | Reason and condition |
|
||||
| --- | --- | --- | --- |
|
||||
| Windows runtime APIs | CrossOver (Wine-based) | **Adopt as external dependency** (strategic decision, ADR 0005) | Proprietary product; do not bundle or redistribute. Capabilities and interfaces unverified (#348, #350). |
|
||||
| Windows runtime APIs | Upstream Wine | Reference; source may be consulted | LGPL 2.1. Copying source would need per-file review and a recorded pin. Not needed for the current plan. |
|
||||
| x86-64 on ARM64 | Rosetta 2 | **Permitted where Apple supports it**; external | Apple component; support lifetime unknown (#349). BetterXen's own code stays ARM64. |
|
||||
| x86-64 on ARM64 | FEX | **Not applicable now** | README targets ARM64 Linux. Re-check only if a macOS host path appears. |
|
||||
| Direct3D 12 to Metal | D3DMetal | **Evaluate as external**, subject to license | Not in CodeWeavers' FOSS list; terms and availability to verify (#349, #354). Not redistributable until proven. |
|
||||
| Direct3D 11/10 to Metal | DXMT | **Evaluate** as external binary or build | LGPL 2.1-or-later; usable as a separate process or library under LGPL terms; linking or copying needs legal review (#354). |
|
||||
| Direct3D to Vulkan | DXVK | **Evaluate** only together with MoltenVK | zlib/libpng is permissive and GPL-compatible. Value on macOS unknown. |
|
||||
| Direct3D 12 to Vulkan | VKD3D-Proton | **Evaluate**; blocked on a Vulkan 1.3 provider | Depends on MoltenVK feature coverage, unknown. |
|
||||
| Vulkan on Metal | MoltenVK | **Evaluate** | Apache-2.0 (compatible with GPLv3). Subset of Vulkan; coverage vs consumers unknown. |
|
||||
| Shader compiler / runtime | VIctory, VIctory-macOS | **Rejected for reuse** | Built for a specific commercial game's Xbox Series build whose provenance is not established as authorized. Ideas only. |
|
||||
| GFX10 to DXIL recompiler | victory-mac `crates/victory-shader` (VIctory family) | **Not approved: maintainer decision pending** (the rejection above stands until then) | PR #394 proposes vendoring it. The [per-file review](victory-shader-provenance.md) finds GPL-3.0 licensing but development against one commercial title's shaders; read plainly, the engineering rules exclude it. |
|
||||
| Project discovery | PortWatch VI | Reference only | Editorial tracker; not engineering evidence; nothing imported. |
|
||||
| x86-64 decode and ARM64 translation, runtime, gfx1030 compiler, Metal backend | BetterXen native implementation | **Preserved, paused** | Reuse only where hybrid needs it and it shows a demonstrated advantage; not forced into the architecture. |
|
||||
| Test and diagnostics methodology | BetterXen existing audits, benchmark harness, claims registry | **Reuse** | Existing evidence classes, claims audit and benchmark gating apply to hybrid work (Phase 1 onward). |
|
||||
| Configuration, diagnostics, benchmarking around CrossOver | BetterXen | **Build** (Phase 2, provisional) | Only after Phase 1 shows what CrossOver does not already provide (#351). |
|
||||
|
||||
Open items: license text for every selected component must be read from the exact release used; DXMT, DXVK and Wine contributor and file-level notices are not reviewed.
|
||||
@@ -0,0 +1,41 @@
|
||||
# Hybrid backlog research record (2026-11-25)
|
||||
|
||||
Evidence class D: public documentation and repository metadata, plus search summaries; see [primary-source-verification-2026-11-25.md](primary-source-verification-2026-11-25.md) for the re-check. Nothing was installed, built or run. Not legal advice. Candidate registry rows are listed here; merge them into [upstream-registry.md](upstream-registry.md) once that file's pending commit has landed.
|
||||
|
||||
## Findings that created issues
|
||||
|
||||
| Finding | Source | Consequence |
|
||||
| --- | --- | --- |
|
||||
| CrossOver 27 reportedly requires Apple silicon and macOS Sonoma+, drops 32-bit bottles, and an ARM64 build without Rosetta 2 is planned; Apple keeps Rosetta fully through macOS 27, a subset after | CodeWeavers blog 2026-06-11 and Apple WWDC 2025 (search summaries; primary pages not retrieved) | [#374](https://github.com/MacosPorters/betterxen/issues/374), comment on #349 |
|
||||
| Bottle backend is reportedly set by `CX_GRAPHICS_BACKEND` (d3dmetal, dxmt, dxvk, wined3d) in `cxbottle.conf`; no official documentation found | Third-party projects | Unverified; #350 must confirm before [#366](https://github.com/MacosPorters/betterxen/issues/366) relies on it |
|
||||
| Cross-building anything for Wine needs mingw-w64 or llvm-mingw | DXMT `docs/DEVELOPMENT.md` | [#364](https://github.com/MacosPorters/betterxen/issues/364) |
|
||||
| Wine and vkd3d-proton ship Direct3D conformance tests that can be built as standalone PE programs | `wine-mirror/wine` `dlls/d3d11/tests`, `vkd3d-proton` `tests/` | [#369](https://github.com/MacosPorters/betterxen/issues/369) |
|
||||
| DXMT offers Metal-coordinated frame pacing and MetalFX upscaling; DXMT is D3D11/10 only | DXMT `docs/CUSTOMIZATION.md`, README | [#370](https://github.com/MacosPorters/betterxen/issues/370) |
|
||||
| DXMT compiles shaders at runtime with an LLVM-based compiler | DXMT `src/airconv` | [#371](https://github.com/MacosPorters/betterxen/issues/371) (hypothesis to test) |
|
||||
| Metal HUD frame data is logged with `MTL_HUD_ENABLED`; logging variable name differs between sources; frame data may be redacted in the unified log | Apple tech talk, community tools | #145, [#372](https://github.com/MacosPorters/betterxen/issues/372) |
|
||||
| D3DMetal license reportedly limits use to evaluation and restricts redistribution | Secondary sources | #354 must read Apple's License.pdf; never bundle |
|
||||
|
||||
## Registry candidates
|
||||
|
||||
| Project | Pin / state observed | License as reported | Classification | Issue |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| llvm-mingw / mingw-w64 | not pinned yet | to read per release | External dependency | #364 |
|
||||
| Wine conformance tests | `wine-mirror/wine`, pushed 2026-11-24 | LGPL-2.1-or-later | Run as external programs, not copied | #369 |
|
||||
| vkd3d-proton tests | pushed 2026-11-25 | LGPL-2.1 | Requires feasibility validation (D3D12 path unconfirmed) | #369 |
|
||||
| DXMT | v0.80 (2026-04-23) | LGPL-2.1-or-later | Requires feasibility validation; external | #370, #371 |
|
||||
| Apple Game Porting Toolkit / D3DMetal | not retrieved | Apple license, reportedly restrictive | Requires licensing clarification; user-supplied only | #354 |
|
||||
| Whisky | archived 2025-05-11 | GPL-3.0 | Technical reference only | #366 |
|
||||
| Gcenx macOS Wine builds, Sikarugir | Sikarugir reports no license | unknown | Technical reference only; no reuse | none |
|
||||
| MetalHUDLogger and similar community tools | not reviewed | unknown | Technical reference only | #145 |
|
||||
| FEX, QEMU, LLVM, MoltenVK, DXVK, Xenia | see upstream registry | see registry | FEX: not applicable on macOS. Others: no change from existing registry | none |
|
||||
| VIctory family, PortWatch VI | see upstream registry | GPL-3.0 (repos) | Rejected for reuse: the tracker describes efforts built around a leaked Xbox Series build of a commercial game; PortWatch is used for discovery only | none |
|
||||
|
||||
Not investigated in depth: Xenia internals and QEMU, because neither runs Windows x86-64 programs on macOS ARM64 in a way relevant to the CrossOver architecture; this is a judgement, not a finding.
|
||||
|
||||
## Issues created
|
||||
|
||||
Existing hybrid issues #344 to #355, #363, #145, #204, #257, #303 were left to the other planning session. New: #364 to #374, and phase trackers #375 (H3), #376 (H4), #377 (H5). Dependencies are recorded as GitHub blocked-by and sub-issue relationships.
|
||||
|
||||
## Conditional work deliberately not filed
|
||||
|
||||
D3D12 workloads (after #349 confirms a path), input-injection tests, a compatibility matrix generator (after #368), upstream contributions to DXMT or Wine (after #369 and #370 produce concrete findings), and release engineering (H6).
|
||||
@@ -0,0 +1,183 @@
|
||||
# Native issue archive
|
||||
|
||||
**Preserved history, not a backlog.** BetterXen's active direction is the CrossOver-based hybrid architecture ([roadmap](../roadmap.md)). The independent native implementation is paused indefinitely; this page replaces its GitHub issue backlog so the work can be found without occupying the active Issues tab. Native source code, tests, benchmarks, Git history and attribution are untouched. Resuming native work needs an explicit maintainer decision ([native roadmap](native-roadmap.md)).
|
||||
|
||||
Every issue below keeps its full text, comments and attribution on GitHub and can be reopened; closing used the reason "not planned". Issues imported from the earlier Xenora repository say so in their first lines, and their original author is recorded below. Excerpts are the first sentence of the issue's objective, not a summary of acceptance criteria.
|
||||
|
||||
## Active-work transitions
|
||||
|
||||
Four native issues stay open because a contributor is assigned and has an open pull request. They are the only open native-only issues and each carries a comment asking the contributor to say whether to continue as archived native research, re-scope, or withdraw:
|
||||
|
||||
| Issue | Assignee | Pull request |
|
||||
| --- | --- | --- |
|
||||
| [#247](https://github.com/MacosPorters/betterxen/issues/247) native app quick start | atesahmet0 | [#310](https://github.com/MacosPorters/betterxen/pull/310) |
|
||||
| [#291](https://github.com/MacosPorters/betterxen/issues/291) executable writes inside a translated block | maridogolpeador | [#327](https://github.com/MacosPorters/betterxen/pull/327) |
|
||||
| [#307](https://github.com/MacosPorters/betterxen/issues/307) CRT stdio follow-up | soggyramennoodle | [#263](https://github.com/MacosPorters/betterxen/pull/263), [#290](https://github.com/MacosPorters/betterxen/pull/290) |
|
||||
| [#313](https://github.com/MacosPorters/betterxen/issues/313) original compiled C guest | soggyramennoodle | [#330](https://github.com/MacosPorters/betterxen/pull/330) |
|
||||
|
||||
Open pull requests for issues that were closed (#308, #312, #328, #329, #339, #340, #341, #342) were left untouched; each received a comment explaining the transition so maintainers and authors can decide whether to merge them as research or close them.
|
||||
|
||||
## Native pieces hybrid development might use
|
||||
|
||||
Nothing in the native backlog is a prerequisite for the hybrid phases. One possible reuse is already noted: the original compiled C guest fixture of #313/#330 could serve as one authorized test workload for hybrid baselines ([#364](https://github.com/MacosPorters/betterxen/issues/364)). If hybrid work needs any other native component, it should be filed as a focused hybrid issue.
|
||||
|
||||
## Findings preserved from discussions
|
||||
|
||||
- **Remill evaluation ([#324](https://github.com/MacosPorters/betterxen/issues/324)).** An isolated, native ARM64 evaluation pinned Remill at `66c488c9911fd9b368e4d0c9647d74239f8bba8b`. Five original AMD64 traces lifted and ran with 32 passing case/path checks. A second pass recorded eight floating-point mismatches (guest rounding, MXCSR sticky flags, denormals-are-zeros, an unmasked precision exception) and a loop that needed external termination; the decision was to retain the existing CPU path, and the failing gate was left failing. An adapter design was written. Published on branch `research/remill-arm64` (commit `e50268d8723a29a365a36c6b665db6d4e3733f6b`; `experiments/remill/`). Local test results, not CI; no independent acceptance.
|
||||
- **VIctory shader-compiler feasibility ([#261](https://github.com/MacosPorters/betterxen/issues/261)).** Local experiments (`experiments/victory-native/`, uncommitted, on a local branch) built a pinned shader compiler natively, translated original gfx1030 fixtures to DXIL, converted them with Apple's Metal shader converter and checked native Metal readback (a 4x4 pixel probe and a 32-word buffer transform) on an M4, plus a review of an upstream Xenora snapshot (114 tests passed). Those materials depend on VIctory-family source whose input provenance the [upstream registry](upstream-registry.md) does not clear for reuse; they are not part of this branch and nothing from them is adopted.
|
||||
- **PortWatch review and native plan ([#298](https://github.com/MacosPorters/betterxen/issues/298), [PR #308](https://github.com/MacosPorters/betterxen/pull/308)).** Produced [portwatch-native-macos.md](portwatch-native-macos.md) and a seven-phase native plan (open PR #308, which replaces the README X1 to X25 table). The native plan is superseded by the hybrid roadmap; the PortWatch screening facts remain useful.
|
||||
- **Metal buffer pool ([#130](https://github.com/MacosPorters/betterxen/issues/130)).** A bounded completed-buffer pool imported from upstream Xenora commit `4f3d0ae1ca44ff5e01e569eab07f776af43d2f8e` (author Vedant Dadhich, GPL-3.0-or-later attribution retained) passed 58 native tests locally with a negative control; a pipeline-selection fixture was added under [#315](https://github.com/MacosPorters/betterxen/issues/315). Local branch `integration/xenora-metal-pool`, not pushed.
|
||||
- **C++ unwind prerequisite ([#343](https://github.com/MacosPorters/betterxen/issues/343)).** An isolated `experiments/cpp-unwind` workspace adapting restricted prolog-restoration logic from upstream Xenora (Swastick Chowdhury, SPDX notice retained); local branch `integration/cpp-unwind`, not pushed.
|
||||
|
||||
Local branches and worktrees named above are not on GitHub; their owners decide whether to publish them.
|
||||
|
||||
## Index
|
||||
|
||||
|
||||
### CPU correctness and translation
|
||||
|
||||
| Issue | Original author | Comments | Pull requests | After this change | Objective excerpt |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| [#62](https://github.com/MacosPorters/betterxen/issues/62) [CPU] Verify RIP-relative effective-address computation | ranveersoni98 | 1 | - | closed, not planned | Audit the shared effective-address emitter for RIP-relative operands. Verify positive and negative displacements and instruction-end address |
|
||||
| [#63](https://github.com/MacosPorters/betterxen/issues/63) [CPU] Correct legacy high-byte register semantics | ranveersoni98 | 1 | - | closed, not planned | Verify AH, CH, DH and BH handling without REX and SPL, BPL, SIL and DIL with REX. Reject unsupported combinations explicitly. |
|
||||
| [#64](https://github.com/MacosPorters/betterxen/issues/64) [CPU] Implement bounded x86 instruction prefix decoding | ranveersoni98 | 1 | - | closed, not planned | Enforce architectural instruction-length limits and validate repeated or conflicting prefixes. Add truncated-input and boundary regression t |
|
||||
| [#65](https://github.com/MacosPorters/betterxen/issues/65) [CPU] Verify guest flags across translated block boundaries | ranveersoni98 | 1 | - | closed, not planned | Verify architectural flags survive translated block transitions, helper calls and subsequent conditional branches. Use independent expected |
|
||||
| [#66](https://github.com/MacosPorters/betterxen/issues/66) [CPU] Add parity flag and parity-dependent branch semantics | ranveersoni98 | 1 | - | closed, not planned | Implement a documented and tested parity-flag subset, including JP and JNP. Preserve existing CPU state layout contracts. |
|
||||
| [#68](https://github.com/MacosPorters/betterxen/issues/68) [CPU] Correct LEA effective-address semantics | ranveersoni98 | 1 | - | closed, not planned | Verify LEA operand widths, SIB calculations, RIP-relative addressing and the distinction between effective-address computation and segment-r |
|
||||
| [#113](https://github.com/MacosPorters/betterxen/issues/113) [CPU-NEXT] Add independently verified MOVSXD semantics | ranveersoni98 | 1 | - | closed, not planned | Verify signed 32-to-64 extension for register and memory operands, both signs, and fault-state preservation. |
|
||||
| [#114](https://github.com/MacosPorters/betterxen/issues/114) [CPU-NEXT] Add 16-bit operand-size semantics for bounded integer instr | ranveersoni98 | 1 | - | closed, not planned | Test low-word updates, preservation of upper bits, immediate length, and unsupported prefix combinations; compare native and independent exp |
|
||||
| [#115](https://github.com/MacosPorters/betterxen/issues/115) [CPU-NEXT] Implement CMP and TEST memory operand coverage | ranveersoni98 | 1 | - | closed, not planned | Verify 8/16/32/64-bit forms within the supported subset, taken and untaken branches, flags, no memory writes, and precise faults. |
|
||||
| [#116](https://github.com/MacosPorters/betterxen/issues/116) [CPU-NEXT] Implement memory operand integer ALU subset | ranveersoni98 | 1 | - | closed, not planned | Add independently verified ADD/SUB/AND/OR/XOR memory forms; verify read-modify-write boundaries, flags, widths and no partial side effects o |
|
||||
| [#118](https://github.com/MacosPorters/betterxen/issues/118) [CPU-NEXT] Implement integer multiply and divide semantics | ranveersoni98 | 1 | - | closed, not planned | Cover selected documented MUL/IMUL/DIV/IDIV forms, signedness, implicit registers, quotient overflow and divide-by-zero guest faults. |
|
||||
| [#119](https://github.com/MacosPorters/betterxen/issues/119) [CPU-NEXT] Implement conditional moves and SETcc | ranveersoni98 | 1 | - | closed, not planned | Test supported conditions across signed/unsigned boundaries, aliasing, byte register writes and documented memory-fault behavior. |
|
||||
| [#120](https://github.com/MacosPorters/betterxen/issues/120) [CPU-NEXT] Define and verify guest SIMD architectural state | ranveersoni98 | 1 | - | closed, not planned | Introduce a bounded, documented XMM state representation with layout assertions and correct save/preservation across helpers. No instruction |
|
||||
| [#121](https://github.com/MacosPorters/betterxen/issues/121) [CPU-NEXT] Implement bounded SSE2 vector move and bitwise operations | ranveersoni98 | 1 | - | closed, not planned | Verify selected aligned/unaligned vector moves and packed AND/OR/XOR against original known answers, including aliasing and memory faults. |
|
||||
| [#122](https://github.com/MacosPorters/betterxen/issues/122) [CPU-NEXT] Implement bounded SSE2 packed integer arithmetic | ranveersoni98 | 1 | - | closed, not planned | Verify selected packed adds/subtracts, comparisons and lane widths against independently derived vectors; no unsupported saturation behavior |
|
||||
| [#123](https://github.com/MacosPorters/betterxen/issues/123) [CPU-NEXT] Implement verified scalar SSE floating-point subset | ranveersoni98 | 1 | - | closed, not planned | Define rounding and supported FP domain before implementing selected scalar operations. Test signed zero, finite boundary values and explici |
|
||||
| [#124](https://github.com/MacosPorters/betterxen/issues/124) [CPU-NEXT] Define guest floating-point control and exception state | ranveersoni98 | 1 | - | closed, not planned | Verify documented MXCSR subset, reserved bits, reset state, preservation and unsupported-mode diagnostics; do not globally modify host FP mo |
|
||||
| [#127](https://github.com/MacosPorters/betterxen/issues/127) [CPU-NEXT] Audit ARM64 assembler encoding coverage for new CPU operati | ranveersoni98 | 1 | - | closed, not planned | Compare representative legal encodings with native LLVM assembler results; reject invalid ranges and preserve existing independently derived |
|
||||
| [#191](https://github.com/MacosPorters/betterxen/issues/191) [CPU] Model guest memory ordering and fence instructions | ranveersoni98 | 1 | - | closed, not planned | criteria |
|
||||
| [#291](https://github.com/MacosPorters/betterxen/issues/291) Handle executable writes within an active translated block | Arths17 | 3 | #327 | open (active work) | PR #269 revalidates translated code at dispatch boundaries. A guest store that modifies a later instruction in the currently executing trans |
|
||||
| [#300](https://github.com/MacosPorters/betterxen/issues/300) [CPU RESEARCH] Specify bounded AMD64 unwind before guest exception dis | Arths17 | 2 | #329 | closed, not planned | Guest faults currently terminate execution; the hosted-C A2 fixture imports __C_specific_handler but never calls it. That stub traps. Window |
|
||||
| [#324](https://github.com/MacosPorters/betterxen/issues/324) [CPU RESEARCH] Evaluate Remill in an isolated native ARM64 experiment | Arths17 | 9 | - | closed, not planned | Evaluate Remill as an isolated native Apple Silicon CPU-backend experiment. Requested by the maintainer; do not replace the production DBT o |
|
||||
| [#343](https://github.com/MacosPorters/betterxen/issues/343) [C++ INTEGRATION] Add isolated bounded unwind prerequisite | Arths17 | 3 | - | closed, not planned | User-authorized first C++ integration slice: a bounded, read-only AMD64 unwind prerequisite, adapted from the pinned native Xenora implement |
|
||||
|
||||
### DBT performance
|
||||
|
||||
| Issue | Original author | Comments | Pull requests | After this change | Objective excerpt |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| [#80](https://github.com/MacosPorters/betterxen/issues/80) [CPU] Add native DBT performance regression benchmarks | ranveersoni98 | 1 | #341 | closed, not planned | Expand original CPU benchmarks to measure cold translation, cached execution, branch-heavy workloads and checked memory operations. Report r |
|
||||
| [#82](https://github.com/MacosPorters/betterxen/issues/82) [PERF-CPU] Implement adaptive DBT basic-block sizing | ranveersoni98 | 1 | - | closed, not planned | Benchmark alternatives to the fixed 16-instruction block limit. Preserve instruction budgets, fault accounting and deterministic execution. |
|
||||
| [#84](https://github.com/MacosPorters/betterxen/issues/84) [PERF-CPU] Implement guest-to-host register allocation | ranveersoni98 | 1 | - | closed, not planned | Investigate keeping frequently accessed guest registers in ARM64 registers. Implement correct spilling, helper-call preservation and archite |
|
||||
| [#85](https://github.com/MacosPorters/betterxen/issues/85) [PERF-CPU] Eliminate redundant guest register loads and stores | ranveersoni98 | 1 | - | closed, not planned | Track register values within translated blocks and eliminate redundant CPU-state accesses without changing observable guest behavior. |
|
||||
| [#86](https://github.com/MacosPorters/betterxen/issues/86) [PERF-CPU] Implement conservative DBT dead-store elimination | ranveersoni98 | 1 | - | closed, not planned | Eliminate overwritten register assignments where safe. Preserve state at faults, service calls and block exits. |
|
||||
| [#87](https://github.com/MacosPorters/betterxen/issues/87) [PERF-CPU] Implement lightweight leaf-block generation | ranveersoni98 | 1 | - | closed, not planned | Avoid unnecessary stack-frame operations in translated blocks that do not call host helpers. Verify ARM64 ABI compliance. |
|
||||
| [#90](https://github.com/MacosPorters/betterxen/issues/90) [PERF-CPU] Investigate safe direct basic-block linking | ranveersoni98 | 1 | - | closed, not planned | Reduce dispatcher overhead through validated block linking. Preserve cache invalidation, instruction limits and executable-memory protection |
|
||||
| [#91](https://github.com/MacosPorters/betterxen/issues/91) [PERF-CPU] Implement hot-block execution profiling | ranveersoni98 | 1 | - | closed, not planned | Measure guest block execution frequencies and identify expensive frequently executed blocks. Keep instrumentation optional and bounded. |
|
||||
| [#92](https://github.com/MacosPorters/betterxen/issues/92) [PERF-CPU] Investigate tiered native translation | ranveersoni98 | 1 | - | closed, not planned | Design a lightweight first-tier translator and optional optimized translation for measured hot blocks. Implement only after profiling and co |
|
||||
| [#93](https://github.com/MacosPorters/betterxen/issues/93) [PERF-CPU] Implement fast DBT dispatch lookup cache | ranveersoni98 | 1 | - | closed, not planned | Benchmark a small front cache ahead of existing HashMap lookups. Preserve complete cache identity and invalidation. |
|
||||
| [#94](https://github.com/MacosPorters/betterxen/issues/94) [PERF-CPU] Reduce budget-limited translation duplication | ranveersoni98 | 1 | - | closed, not planned | Measure duplicate translations in limited_block_cache. Safely reuse compatible blocks only where instruction accounting remains exact. |
|
||||
| [#95](https://github.com/MacosPorters/betterxen/issues/95) [PERF-CPU] Implement bounded JIT cache reclamation | ranveersoni98 | 1 | - | closed, not planned | Design safe reclamation for exhausted code caches. Ensure no live translated pointer references reclaimed code. |
|
||||
| [#96](https://github.com/MacosPorters/betterxen/issues/96) [PERF-CPU] Measure and optimize JIT code publication | ranveersoni98 | 1 | - | closed, not planned | Measure code-copy and instruction-cache synchronization costs. Investigate bounded batching while retaining all macOS JIT protections. |
|
||||
| [#97](https://github.com/MacosPorters/betterxen/issues/97) [PERF-CPU] Reuse DBT fault-guard scratch storage | ranveersoni98 | 1 | - | closed, not planned | Measure allocation overhead from per-block fault_guards vectors. Reuse bounded scratch storage without retaining stale patch locations. |
|
||||
| [#98](https://github.com/MacosPorters/betterxen/issues/98) [PERF-CPU] Replace linear guest memory lookup with indexed regions | ranveersoni98 | 1 | - | closed, not planned | Compare sorted-region binary search with the current linear region scan. Preserve permissions, overflow checks and exact fault behavior. |
|
||||
| [#99](https://github.com/MacosPorters/betterxen/issues/99) [PERF-CPU] Implement checked guest memory locality cache | ranveersoni98 | 1 | - | closed, not planned | Cache recently accessed guest region identities. Invalidate on mapping changes and revalidate permissions and access bounds. |
|
||||
| [#100](https://github.com/MacosPorters/betterxen/issues/100) [PERF-CPU] Optimize guest instruction-byte fetch | ranveersoni98 | 1 | - | closed, not planned | Reduce repeated region lookups during sequential instruction decoding using bounded, execute-permission-checked fetch windows. |
|
||||
| [#102](https://github.com/MacosPorters/betterxen/issues/102) [PERF-CPU] Optimize mapped-region insertion and removal | ranveersoni98 | 1 | - | closed, not planned | Benchmark mapping operations across realistic synthetic region counts. Improve lookup and maintenance costs while preserving overlap rejecti |
|
||||
| [#103](https://github.com/MacosPorters/betterxen/issues/103) [PERF-CPU] Measure guest memory allocation and copying costs | ranveersoni98 | 1 | - | closed, not planned | Identify avoidable allocations and copies in original memory workloads. Preserve zero initialization and guest isolation. |
|
||||
| [#104](https://github.com/MacosPorters/betterxen/issues/104) [PERF-CPU] Optimize repeated PE RVA resolution | ranveersoni98 | 1 | - | closed, not planned | Benchmark section lookup and introduce a validated indexed representation where beneficial. Depend on checked PE range validation. |
|
||||
| [#106](https://github.com/MacosPorters/betterxen/issues/106) [PERF-CPU] Profile PE loading and startup stages | ranveersoni98 | 1 | - | closed, not planned | Measure parsing, mapping, relocation, import binding, TLS setup and entry execution separately. Use original fixtures only. |
|
||||
| [#111](https://github.com/MacosPorters/betterxen/issues/111) [PERF-CPU] Expand DBT performance instrumentation | ranveersoni98 | 1 | - | closed, not planned | Track translation time, dispatch time, guest-memory helper calls, cache-hit ratios, emitted bytes per guest instruction and code-cache utili |
|
||||
| [#169](https://github.com/MacosPorters/betterxen/issues/169) [CPU] Measure native code expansion by guest instruction family | ranveersoni98 | 1 | #342 | closed, not planned | criteria |
|
||||
|
||||
### GPU, shader and Metal
|
||||
|
||||
| Issue | Original author | Comments | Pull requests | After this change | Objective excerpt |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| [#129](https://github.com/MacosPorters/betterxen/issues/129) [GPU-NEXT] Benchmark Metal render pipeline reuse | ranveersoni98 | 1 | - | closed, not planned | Measure repeated render setup separately from GPU time; verify complete pipeline identity, output pixels and cache lifetime. |
|
||||
| [#130](https://github.com/MacosPorters/betterxen/issues/130) [GPU-NEXT] Reduce verified Metal buffer allocation churn | ranveersoni98 | 4 | - | closed, not planned | Profile allocation count and latency in repeated original compute/render fixtures; implement bounded reuse with initialization and completio |
|
||||
| [#132](https://github.com/MacosPorters/betterxen/issues/132) [GPU-NEXT] Measure and reduce synchronous GPU readback overhead | ranveersoni98 | 1 | - | closed, not planned | Separate submission, completion and readback timings. Add a bounded opt-in asynchronous original-fixture path only if justified; verify outp |
|
||||
| [#133](https://github.com/MacosPorters/betterxen/issues/133) [GPU-NEXT] Benchmark multi-command Metal submission batching | ranveersoni98 | 1 | - | closed, not planned | Compare individual versus batched independent original commands; verify barriers, ordering, bounded queue depth and matching outputs. |
|
||||
| [#135](https://github.com/MacosPorters/betterxen/issues/135) [GPU-NEXT] Separate shader translation validation from reusable compil | ranveersoni98 | 1 | - | closed, not planned | Measure repeated translation of identical original inputs; define complete validated artifact identity including architecture and semantic o |
|
||||
| [#136](https://github.com/MacosPorters/betterxen/issues/136) [GPU-NEXT] Measure shader IR allocation and MSL emission costs | ranveersoni98 | 1 | - | closed, not planned | Profile decode, lift, analysis and emission separately on original workloads; reduce demonstrated temporary allocation costs without changin |
|
||||
| [#139](https://github.com/MacosPorters/betterxen/issues/139) [GPU-NEXT] Benchmark bounded BC1 linearization and upload paths | ranveersoni98 | 1 | - | closed, not planned | Measure untile, staging and upload costs on original texture patterns across sizes, mips and layers; verify pixel equality and malformed-inp |
|
||||
| [#141](https://github.com/MacosPorters/betterxen/issues/141) [GPU-NEXT] Benchmark partial mip updates and upload coalescing | ranveersoni98 | 1 | - | closed, not planned | Compare whole and selected-mip updates; verify dimensions, row pitch, unchanged neighboring mips and completion semantics. |
|
||||
| [#142](https://github.com/MacosPorters/betterxen/issues/142) [GPU-NEXT] Measure shader and graphics resource budget scaling | ranveersoni98 | 1 | - | closed, not planned | Characterize existing 4096-scale fixture limits and resource use. If justified, add configurable bounded synthetic workload tiers with check |
|
||||
| [#179](https://github.com/MacosPorters/betterxen/issues/179) [GPU] Implement runtime-dependent uniform shader branches | ranveersoni98 | 1 | - | closed, not planned | criteria |
|
||||
| [#180](https://github.com/MacosPorters/betterxen/issues/180) [GPU] Add bounded shader loop semantics and termination checks | ranveersoni98 | 1 | - | closed, not planned | criteria |
|
||||
| [#181](https://github.com/MacosPorters/betterxen/issues/181) [GPU] Implement typed scalar buffer reads with checked resource ranges | ranveersoni98 | 1 | - | closed, not planned | criteria |
|
||||
| [#182](https://github.com/MacosPorters/betterxen/issues/182) [GPU] Add vector multiply-add and explicit floating-point rounding con | ranveersoni98 | 1 | - | closed, not planned | criteria |
|
||||
| [#205](https://github.com/MacosPorters/betterxen/issues/205) [GPU] Build a metadata-driven RDNA2 semantic expansion pipeline | ranveersoni98 | 1 | - | closed, not planned | Xenora currently identifies approximately 1,460 RDNA2 instruction forms but semantically decodes only 25. |
|
||||
| [#208](https://github.com/MacosPorters/betterxen/issues/208) [GPU] Decode BC6H two-region modes (CPU) | elforeign | 1 | - | closed, not planned | criteria |
|
||||
| [#209](https://github.com/MacosPorters/betterxen/issues/209) [GPU] Native Metal upload and readback of BC6H and BC7 | elforeign | 1 | - | closed, not planned | criteria |
|
||||
| [#224](https://github.com/MacosPorters/betterxen/issues/224) [GPU] Guest graphics fences with Metal shared events | elforeign | 1 | - | closed, not planned | ## Goal Give the guest graphics runtime (`crates/loader/src/graphics.rs`) a fence object with the publicly documented D3D12 contract: a que |
|
||||
| [#225](https://github.com/MacosPorters/betterxen/issues/225) [QA] Define and run acceptance for the 86 locally verified gfx1030 for | elforeign | 1 | - | closed, not planned | ## Area QA / GPU ## Problem `docs/status.toml` at `eb85731` lists 104 gfx1030 forms. Only 18 count as accepted (`gpu = "fixture verified"`) |
|
||||
| [#258](https://github.com/MacosPorters/betterxen/issues/258) [PERF] Evaluate bounded Metal cache prewarming and persistence after s | Arths17 | 1 | - | closed, not planned | Xenora already has a [bounded context-local compute cache](https://github.com/ranveersoni98/Xenora/blob/3b47c21bb008dcb38be704d540776f7cd046 |
|
||||
| [#302](https://github.com/MacosPorters/betterxen/issues/302) [GPU RESEARCH] Define explicit shader entry and resource bindings beyo | Arths17 | 1 | #340 | closed, not planned | graphics.rs already translates image_sample_lz and #226 added guest texture/sampler descriptor tables. The remaining gap is not “add texture |
|
||||
|
||||
### Integration workloads and shared accounting
|
||||
|
||||
| Issue | Original author | Comments | Pull requests | After this change | Objective excerpt |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| [#143](https://github.com/MacosPorters/betterxen/issues/143) [INTEGRATION-NEXT] Add original CPU-to-GPU mixed workload benchmark | ranveersoni98 | 1 | - | closed, not planned | Create a small original synthetic workload that executes verified CPU arithmetic, checked buffer updates and native rendering; validate know |
|
||||
| [#146](https://github.com/MacosPorters/betterxen/issues/146) [INTEGRATION-NEXT] Add deterministic synthetic transform workload | ranveersoni98 | 1 | - | closed, not planned | Use independently authored integer and supported finite FP transforms with known expected outputs; compare supported CPU and GPU implementat |
|
||||
| [#147](https://github.com/MacosPorters/betterxen/issues/147) [INTEGRATION-NEXT] Add original texture-update and draw workload | ranveersoni98 | 1 | - | closed, not planned | Build an original multi-frame texture update/draw case with known texels and pixels, bounded resources and explicit native verification. |
|
||||
| [#148](https://github.com/MacosPorters/betterxen/issues/148) [INTEGRATION-NEXT] Verify CPU and GPU shared resource ownership under | ranveersoni98 | 1 | - | closed, not planned | Use synthetic resources to verify permitted transitions, stale-handle rejection, completion-aware cleanup and deterministic failure without |
|
||||
| [#149](https://github.com/MacosPorters/betterxen/issues/149) [INTEGRATION-NEXT] Add long-running bounded original workload soak tes | ranveersoni98 | 1 | - | closed, not planned | Run a fixed number of validated synthetic iterations; report peak memory, cache growth, handles and deterministic outputs. Enforce time/reso |
|
||||
| [#150](https://github.com/MacosPorters/betterxen/issues/150) [INTEGRATION-NEXT] Add replayable original workload input corpus | ranveersoni98 | 1 | - | closed, not planned | Define versioned independently authored fixture inputs, deterministic seeds and expected outcomes. Replay only original data; verify limits |
|
||||
| [#159](https://github.com/MacosPorters/betterxen/issues/159) [SHARED-NEXT] Define shared CPU/GPU frame workload and timing interfac | ranveersoni98 | 1 | #328 | closed, not planned | Agree on bounded original workload inputs, frame completion, metrics units, resource lifetime and deterministic failure contracts before any |
|
||||
| [#160](https://github.com/MacosPorters/betterxen/issues/160) [SHARED-NEXT] Define bounded native GPU workload resource budget contr | ranveersoni98 | 1 | - | closed, not planned | Document limits for buffers, textures, queued work, compilation and staging; define explicit resource-exhaustion behavior and compatibility |
|
||||
| [#199](https://github.com/MacosPorters/betterxen/issues/199) [SHARED] Define unified CPU JIT and GPU allocation accounting | ranveersoni98 | 1 | - | closed, not planned | criteria |
|
||||
|
||||
### Runtime and loader
|
||||
|
||||
| Issue | Original author | Comments | Pull requests | After this change | Objective excerpt |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| [#195](https://github.com/MacosPorters/betterxen/issues/195) [RUNTIME] Add virtual memory reserve commit decommit state tests | ranveersoni98 | 1 | - | closed, not planned | criteria |
|
||||
| [#198](https://github.com/MacosPorters/betterxen/issues/198) [RUNTIME] Add CRT overlapping memory move and bounded string edge case | ranveersoni98 | 1 | - | closed, not planned | criteria |
|
||||
| [#211](https://github.com/MacosPorters/betterxen/issues/211) feat: Add a read-only dependency census for PE packages | elforeign | 1 | - | closed, not planned | The static probe takes one PE file at a time. With an EXE and companion DLLs, it takes a separate manual pass to tell which symbols the pack |
|
||||
| [#212](https://github.com/MacosPorters/betterxen/issues/212) [SHARED] Decide whether to relax the CLI runner's exact-bytes trust ga | Swastickc | 1 | - | closed, not planned | ## Question for the maintainer Should the CLI runner's exact-bytes trust gate be relaxed? A contributor asked for this error to be removed: |
|
||||
| [#227](https://github.com/MacosPorters/betterxen/issues/227) Audio: native PCM mixer and CoreAudio output (location and Gate 6 brid | elforeign | 1 | - | closed, not planned | ### Area audio ### Summary I have a standalone prototype of a native PCM mixer with opt-in CoreAudio output for Apple Silicon: a bounded co |
|
||||
| [#228](https://github.com/MacosPorters/betterxen/issues/228) [RUNTIME] Deterministic guest thread scheduler | jelly013 | 1 | - | closed, not planned | guest threads do not exist yet: CreateThread is absent and, as synch.rs states, a call that would block another guest thread stops the gues |
|
||||
| [#301](https://github.com/MacosPorters/betterxen/issues/301) [LOADER] Specify and test an original two-DLL startup graph | Arths17 | 1 | - | closed, not planned | run_synthetic_startup accepts one image, and services/modules.rs exposes built-in service modules. Those are not general guest DLL mapping, |
|
||||
| [#304](https://github.com/MacosPorters/betterxen/issues/304) [RUNTIME] Make guest Sleep yield without blocking other scheduled thre | Arths17 | 1 | - | closed, not planned | docs/runtime/threads.md explicitly says Sleep delays every guest thread. A deterministic single-host-thread scheduler is already implemented |
|
||||
| [#305](https://github.com/MacosPorters/betterxen/issues/305) [RUNTIME RESEARCH] Specify static TLS and callback lifecycle for sched | Arths17 | 1 | #312 | closed, not planned | the scheduler already gives each worker a TEB, stack, dynamic TLS/FLS values and cleanup, but docs/runtime/threads.md explicitly excludes PE |
|
||||
| [#307](https://github.com/MacosPorters/betterxen/issues/307) [RUNTIME] CRT stdio follow-up: fread/fseek/ftell, fgetc/ungetc and hos | soggyramennoodle | 1 | #263, #290 | open (active work) | PR #290 took its own CRT stdio module (`crt_stdio.rs`) out in `e1f7176`, because `main` gained its own `fopen`/`fclose`/`fwrite`/`__acrt_iob |
|
||||
| [#322](https://github.com/MacosPorters/betterxen/issues/322) [RUNTIME] Replace the VirtualQuery trap for a documented guest-memory | Arths17 | 1 | - | closed, not planned | ## Outcome and readiness Ready for memory-query contract and failing guest tests. Production metadata changes coordinate #195 and memory.rs |
|
||||
| [#323](https://github.com/MacosPorters/betterxen/issues/323) [RUNTIME] Implement a bounded data-page VirtualProtect subset with tra | Arths17 | 1 | - | closed, not planned | ## Outcome and readiness Ready for protection contract/failing-test design. Implementation follows the agreed memory metadata model in #322/ |
|
||||
| [#331](https://github.com/MacosPorters/betterxen/issues/331) Keep host-mounted file opens nonblocking | soggyramennoodle | 1 | - | closed, not planned | Follow-up from the review of #290. Harden regular-file opens so a host-side file type change cannot leave a BetterXen host thread waiting in |
|
||||
| [#332](https://github.com/MacosPorters/betterxen/issues/332) Bound the cost of lookups in large host-mounted directories | soggyramennoodle | 1 | - | closed, not planned | Follow-up from the review of #290. Host-backed drive lookup currently enumerates an entire directory and refuses directories exceeding 4,096 |
|
||||
| [#333](https://github.com/MacosPorters/betterxen/issues/333) Runtime compatibility follow-ups from PR #290 | soggyramennoodle | 1 | - | closed, not planned | Track the remaining nonblocking review items from #290. - Invalidate aligned-allocation tracking in shared guest heap free paths and test ow |
|
||||
| [#336](https://github.com/MacosPorters/betterxen/issues/336) [RUNTIME] SetFilePointerEx should fail a negative distance from FILE_B | Arths17 | 1 | #339 | closed, not planned | Found while auditing #290. This behaviour already exists on `main` (`crates/loader/src/services/files.rs`), so it is not part of that PR. Th |
|
||||
|
||||
### Compiled launch milestone and native app
|
||||
|
||||
| Issue | Original author | Comments | Pull requests | After this change | Objective excerpt |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| [#247](https://github.com/MacosPorters/betterxen/issues/247) [DOCS] Add a native app quick start ending in a synthetic frame | Arths17 | 2 | #310 | open (active work) | The [README build section](https://github.com/ranveersoni98/Xenora/blob/3b47c21bb008dcb38be704d540776f7cd046681e/README.md#building-xenora) |
|
||||
| [#249](https://github.com/MacosPorters/betterxen/issues/249) [APP] Avoid unchanged-frame image copies and reduce paused polling | Arths17 | 1 | - | closed, not planned | [`FrameLoopModel.startPolling`](https://github.com/ranveersoni98/Xenora/blob/3b47c21bb008dcb38be704d540776f7cd046681e/app/Sources/Xenora/mai |
|
||||
| [#250](https://github.com/MacosPorters/betterxen/issues/250) [APP] Surface session command failures and centralize loop lifecycle | Arths17 | 1 | - | closed, not planned | [`FrameLoopModel`](https://github.com/ranveersoni98/Xenora/blob/3b47c21bb008dcb38be704d540776f7cd046681e/app/Sources/Xenora/main.swift#L441) |
|
||||
| [#253](https://github.com/MacosPorters/betterxen/issues/253) [APP] Audit inspector and fixture controls with keyboard and VoiceOver | Arths17 | 1 | - | closed, not planned | The comparison found native controls and frame accessibility labels, but VoiceOver, keyboard navigation, text scaling and dark-mode behavior |
|
||||
| [#254](https://github.com/MacosPorters/betterxen/issues/254) [DIAGNOSTICS] Share a versioned static compatibility report across CLI | Arths17 | 1 | - | closed, not planned | Xenora already exposes metadata, loader validation, imports, relocations, TLS and a bounded first-unsupported-instruction finding through it |
|
||||
| [#256](https://github.com/MacosPorters/betterxen/issues/256) [INTEGRATION] Prove a multi-module synthetic startup through a checked | Arths17 | 1 | - | closed, not planned | Existing trusted startup and app fixtures establish bounded pieces. The comparison proposes one original integration scenario connecting exe |
|
||||
| [#259](https://github.com/MacosPorters/betterxen/issues/259) [RELEASE] Prepare versioned, signed and notarized contributor previews | Arths17 | 1 | - | closed, not planned | The [app build script](https://github.com/ranveersoni98/Xenora/blob/3b47c21bb008dcb38be704d540776f7cd046681e/scripts/build-app.sh) hardcodes |
|
||||
| [#311](https://github.com/MacosPorters/betterxen/issues/311) [LAUNCH TRACKER] First compiled guest application through native ARM64 | Arths17 | 2 | - | closed, not planned | / --- / / Build and admit / Source/tool/file-license identity, native host tools, exact admitted profile; unsupported input refused. / / En |
|
||||
| [#313](https://github.com/MacosPorters/betterxen/issues/313) [LAUNCH] Build an original compiled C guest for the launch milestone | Arths17 | 3 | #330 | open (active work) | ## Outcome and readiness Ready for fixture specification and native build-recipe work. Runtime execution waits for the agreed frame/service |
|
||||
| [#314](https://github.com/MacosPorters/betterxen/issues/314) [GPU] Add bounded creation and explicit release for guest graphics obj | Arths17 | 1 | - | closed, not planned | ## Outcome and readiness Ready for a narrow lifetime/budget design and failing tests. Agree budget values through #160 and coordinate graphi |
|
||||
| [#315](https://github.com/MacosPorters/betterxen/issues/315) [GPU] Let a bounded guest pipeline select original translated vertex a | Arths17 | 4 | - | closed, not planned | ## Outcome and readiness Design/fixture work can start. Production changes follow #159 contract agreement and #314; serialize graphics.rs ed |
|
||||
| [#316](https://github.com/MacosPorters/betterxen/issues/316) [RUNTIME/GPU] Expose the minimal typed graphics command bridge to comp | Arths17 | 2 | - | closed, not planned | ## Outcome and readiness ABI review and original failing guest tests can start. Implementation waits for #159 plus #315/#314 and coordinatio |
|
||||
| [#317](https://github.com/MacosPorters/betterxen/issues/317) [SESSION] Run the compiled launch fixture through a bounded built-in w | Arths17 | 1 | - | closed, not planned | ## Outcome and readiness Profile design can begin. Worker execution integration is blocked on #313/#316, the required #212 maintainer admiss |
|
||||
| [#318](https://github.com/MacosPorters/betterxen/issues/318) [SESSION] Bound stop and failure recovery when the compiled guest does | Arths17 | 1 | - | closed, not planned | ## Outcome and readiness Design and hostile-original-fixture specifications can start; implementation follows #317 and coordination with its |
|
||||
| [#319](https://github.com/MacosPorters/betterxen/issues/319) [INPUT] Verify compiled guest input snapshots change guest state and r | Arths17 | 1 | - | closed, not planned | ## Outcome and readiness Original C test/expected-state design can start after the fixture/header contract is agreed. End-to-end execution w |
|
||||
| [#320](https://github.com/MacosPorters/betterxen/issues/320) [APP] Present actual compiled-guest frames in a native launch session | Arths17 | 1 | - | closed, not planned | ## Outcome and readiness UI acceptance specification can start. Swift implementation waits for #317/#318, #250 lifecycle agreement and overl |
|
||||
| [#321](https://github.com/MacosPorters/betterxen/issues/321) [QA] Independently gate first compiled launch from source build throug | Arths17 | 1 | #328 | closed, not planned | ## Outcome and readiness Ready for acceptance-protocol/independent expected-value work. The executable harness runs only after #313/#316/#31 |
|
||||
|
||||
### Roadmap and ecosystem research
|
||||
|
||||
| Issue | Original author | Comments | Pull requests | After this change | Objective excerpt |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| [#261](https://github.com/MacosPorters/betterxen/issues/261) [ROADMAP] Native workflow and runtime integration improvements from th | Arths17 | 9 | - | closed, not planned | Turn the supplied Victory for macOS teardown and integration map into actionable Xenora improvements, preserving original implementation, na |
|
||||
| [#298](https://github.com/MacosPorters/betterxen/issues/298) [RESEARCH] Review PortWatch projects and revise the native macOS execu | Arths17 | 7 | #308 | closed, not planned | / --- / --- / / CPU / Guest x86-64 runs on a matching x86-64 CPU; several projects require AVX2 / Decode/execute or translate each supporte |
|
||||
| [#306](https://github.com/MacosPorters/betterxen/issues/306) [RESEARCH] Track public evidence for console launch and graphics ABI b | Arths17 | 1 | - | closed, not planned | BetterXen's tested contracts are synthetic PE32+/gfx1030 contracts. They do not establish the Xbox launch environment, shader entry state, d |
|
||||
|
||||
#158 (native optimization evidence audit) was also closed as obsolete and belongs with DBT performance. The seven earlier "[Deferred native research]" umbrella issues were replaced by one closed index issue.
|
||||
@@ -0,0 +1,27 @@
|
||||
# Native research roadmap
|
||||
|
||||
**Deferred — not part of the active development roadmap, and paused indefinitely.** The active direction is the [CrossOver-based hybrid roadmap](../roadmap.md). Native work resumes only after an explicit maintainer decision, with no date. Native tasks needed by hybrid work are filed as focused hybrid issues instead.
|
||||
|
||||
## Existing implementation (preserved in the workspace)
|
||||
|
||||
Rust crates under `crates/` and `app/`, tests under `tests/`, fixtures, fuzz targets and benchmarks. The last `main` commit before the hybrid transition is tagged `native-first-final`. Contributor history is untouched.
|
||||
|
||||
## Verified achievements (synthetic evidence only)
|
||||
|
||||
Per [docs/progress.md](../progress.md) and the [status registry](../status.toml): translated gfx1030 shaders executing on native Metal on Apple M5 for synthetic fixtures, bounded x86-64 guest execution, an ARM64 dynamic binary translator for supported instruction subsets, a deterministic scheduler running guest threads serially on one host thread. No Xbox title runs. These are the original evidence classes, not new verification.
|
||||
|
||||
## Known limitations
|
||||
|
||||
See the archived [native-first plan](../archive/development-phases-native-first.md) and [README current limitations](../../README.md#current-limitations): serial guest threading, partial runtime services, partial RDNA2 coverage, unknown console launch ABI.
|
||||
|
||||
## Previously planned work
|
||||
|
||||
The native-first phases 1 to 6 (trustworthy baseline, hosted C application, threaded behavior, translated rendering, integrated interactive application, measured bottlenecks) and the X1 to X25 capability map, kept in the archive. The issue backlog was closed as not planned and is indexed, with preserved findings, in the [native issue archive](native-issue-archive.md).
|
||||
|
||||
## Potential future architecture
|
||||
|
||||
Independent CPU translation and Metal components that could replace or complement CrossOver, Rosetta 2 or D3DMetal where a demonstrated limitation or availability risk justifies it.
|
||||
|
||||
## Conditions for resuming (maintainer decision, not automatic)
|
||||
|
||||
Hybrid reaches verified maturity; reliable baselines exist; a native component solves a demonstrated hybrid limitation; a dependency imposes an unavoidable constraint or becomes unavailable; or resources allow it without slowing hybrid work.
|
||||
@@ -19,16 +19,16 @@ Request original gfx1030 Wave64 assembly, a mask/lane design note and per-lane e
|
||||
|
||||
KyTx declares GPL-2.0. Tx's conditional GPL-2.0-or-later offer covers only material they own and can license. Require file-level authorship, explicit compatible terms (GPL-3.0-or-later preferred for new Xenora fixtures), preserved notices and DCO. Inherited GPL-2.0-only code cannot enter the GPL-3.0-or-later combined work under those terms. The separate Kyty MIT notice does not settle a derived file's full provenance. No KyTx submodule is justified for the fixture. [KyTx license and notices](https://github.com/TxCsOffc/KyTx/tree/10f50d3eff0c0df36ee5d7007848a7b0b15072eb/LICENSES), [KyTx license](https://github.com/TxCsOffc/KyTx/blob/10f50d3eff0c0df36ee5d7007848a7b0b15072eb/LICENSE)
|
||||
|
||||
## Leonida
|
||||
## PE-Vulkan project
|
||||
|
||||
Public revision `2d3369a4c82e6f36c5190c4c534d3df600e135ec`. Candidate study surfaces and limits:
|
||||
|
||||
| Surface | Evidence and disposition |
|
||||
| --- | --- |
|
||||
| Decode and translation | `decode_bytes` decodes RDNA words with an explicit wave-mode argument. The SPIR-V generator exposes `Gen` and `assemble`. Compare supported operand forms on independent synthetic inputs. Keep Xenora's typed decoder and MSL backend. [Decoder](https://github.com/ItsNotRexed/Leonida/blob/2d3369a4c82e6f36c5190c4c534d3df600e135ec/tools/rdna2_decode.py#L1397), [Generator](https://github.com/ItsNotRexed/Leonida/blob/2d3369a4c82e6f36c5190c4c534d3df600e135ec/tools/rdna2spirv.py#L219) |
|
||||
| Containers and GPU API | `wave_size` and `binding_table` expose Leonida's FSSM interpretation. The D3D12 Vulkan shim and its device test are concrete source paths. Their existence does not establish a public authoritative Xbox ABI or PM4 contract. Keep metadata and guest handles outside Xenora's decoder, with explicit wave size, checked byte ranges and validated resource bindings. [FSSM reader](https://github.com/ItsNotRexed/Leonida/blob/2d3369a4c82e6f36c5190c4c534d3df600e135ec/tools/fssm_header.py#L155), [Device shim](https://github.com/ItsNotRexed/Leonida/blob/2d3369a4c82e6f36c5190c4c534d3df600e135ec/runtime/shims/d3d12_vulkan_device.cpp), [Device test](https://github.com/ItsNotRexed/Leonida/blob/2d3369a4c82e6f36c5190c4c534d3df600e135ec/runtime/test/d3d12_vulkan_device_test.cpp) |
|
||||
| Containers and GPU API | `wave_size` and `binding_table` expose PE-Vulkan project's FSSM interpretation. The D3D12 Vulkan shim and its device test are concrete source paths. Their existence does not establish a public authoritative Xbox ABI or PM4 contract. Keep metadata and guest handles outside Xenora's decoder, with explicit wave size, checked byte ranges and validated resource bindings. [FSSM reader](https://github.com/ItsNotRexed/Leonida/blob/2d3369a4c82e6f36c5190c4c534d3df600e135ec/tools/fssm_header.py#L155), [Device shim](https://github.com/ItsNotRexed/Leonida/blob/2d3369a4c82e6f36c5190c4c534d3df600e135ec/runtime/shims/d3d12_vulkan_device.cpp), [Device test](https://github.com/ItsNotRexed/Leonida/blob/2d3369a4c82e6f36c5190c4c534d3df600e135ec/runtime/test/d3d12_vulkan_device_test.cpp) |
|
||||
| Executable and services | `Loader::load` and `Loader::load_runtime_module` establish an implemented Windows PE loading and shim boundary. CMake registers loader, bounds and TLS tests. The upstream stand-in run is reported. For Xenora, study the boundary using original PE fixtures, with checked image metadata, guest address translation and explicit service dispatch. Native Windows execution and the Vulkan runtime conflict with Xenora's host contract. [PE loader](https://github.com/ItsNotRexed/Leonida/blob/2d3369a4c82e6f36c5190c4c534d3df600e135ec/runtime/src/pe_loader.cpp#L608), [Test registration](https://github.com/ItsNotRexed/Leonida/blob/2d3369a4c82e6f36c5190c4c534d3df600e135ec/runtime/CMakeLists.txt#L516) |
|
||||
|
||||
The README reports 26,503 translations and SPIR-V validation at specific earlier revisions. It contains conflicting Wave64 counts, so leave that count unresolved. The linked GPU reports cover synthetic cases and include a MoltenVK path. Validation and pipeline creation do not check game shader output. The pinned status explicitly says the game does not boot. Xenora's GTA VI intro remains unverified, and no authorized test input was established in this review. [Pinned status](https://github.com/ItsNotRexed/Leonida/blob/2d3369a4c82e6f36c5190c4c534d3df600e135ec/README.md#project-status), [Reported validator run](https://github.com/ItsNotRexed/Leonida/issues/644#issuecomment-7072972586), [Upstream GPU reports](https://github.com/ItsNotRexed/Leonida/issues/166)
|
||||
The README reports 26,503 translations and SPIR-V validation at specific earlier revisions. It contains conflicting Wave64 counts, so leave that count unresolved. The linked GPU reports cover synthetic cases and include a MoltenVK path. Validation and pipeline creation do not check game shader output. The pinned status explicitly says the game does not boot. Xenora's commercial-title intro remains unverified, and no authorized test input was established in this review. [Pinned status](https://github.com/ItsNotRexed/Leonida/blob/2d3369a4c82e6f36c5190c4c534d3df600e135ec/README.md#project-status), [Reported validator run](https://github.com/ItsNotRexed/Leonida/issues/644#issuecomment-7072972586), [Upstream GPU reports](https://github.com/ItsNotRexed/Leonida/issues/166)
|
||||
|
||||
Leonida carries GPL v3 text at the inspected pin. Any adoption still requires R1 to establish exact file terms and ownership, check generated tables and SDK-derived material, and review the separate `third_party/rpf9-explorer` gitlink at `e2939175c36a02d6ed25fa2c217b9d6ddcb8b516`. Game-derived metadata, shaders and asset outputs are outside this collaboration. Use public design references and original synthetic inputs. No Leonida submodule is justified. [Leonida license](https://github.com/ItsNotRexed/Leonida/blob/2d3369a4c82e6f36c5190c4c534d3df600e135ec/LICENSE), [Submodule declaration](https://github.com/ItsNotRexed/Leonida/blob/2d3369a4c82e6f36c5190c4c534d3df600e135ec/.gitmodules)
|
||||
PE-Vulkan project carries GPL v3 text at the inspected pin. Any adoption still requires R1 to establish exact file terms and ownership, check generated tables and SDK-derived material, and review the separate `third_party/rpf9-explorer` gitlink at `e2939175c36a02d6ed25fa2c217b9d6ddcb8b516`. Game-derived metadata, shaders and asset outputs are outside this collaboration. Use public design references and original synthetic inputs. No PE-Vulkan project submodule is justified. [PE-Vulkan project license](https://github.com/ItsNotRexed/Leonida/blob/2d3369a4c82e6f36c5190c4c534d3df600e135ec/LICENSE), [Submodule declaration](https://github.com/ItsNotRexed/Leonida/blob/2d3369a4c82e6f36c5190c4c534d3df600e135ec/.gitmodules)
|
||||
@@ -5,7 +5,7 @@ Historical reuse discussion records the earlier survey. Xenora uses
|
||||
public specifications and original fixtures, with other emulator
|
||||
projects serving only as references for test selection.
|
||||
|
||||
Screened the eight A3 leads on 2026-11-23 against section 6 of the dual-track brief. The pins below identify the default-branch snapshots and their latest observed commits in UTC. The OpenScarlett tip changes documentation. A recent tip establishes activity, and its commit message records the subject of that activity. See the companion notes for [KyTx and Leonida](phase02-collaboration.md) and [CPU engine selection and original interpreter fixture](phase02-cpu-feasibility.md).
|
||||
Screened the eight A3 leads on 2026-11-23 against section 6 of the dual-track brief. The pins below identify the default-branch snapshots and their latest observed commits in UTC. The OpenScarlett tip changes documentation. A recent tip establishes activity, and its commit message records the subject of that activity. See the companion notes for [KyTx and PE-Vulkan project](phase02-collaboration.md) and [CPU engine selection and original interpreter fixture](phase02-cpu-feasibility.md).
|
||||
|
||||
GitHub metadata and tree entries establish availability and paths. Pinned text inspection establishes what a selected function does in source. Upstream test counts, captures and README statements remain upstream reports. No upstream code, builds, fixtures or GPU workloads were executed here. Repository-level license labels are provisional for reuse. File-specific grants, origin and transitive terms remain unverified for every code surface below.
|
||||
|
||||
|
||||
@@ -0,0 +1,356 @@
|
||||
> **Superseded in part (2026-11-25).** This review recommended against Rosetta, Wine and CrossOver under the native-first plan. BetterXen's direction is now the CrossOver-based hybrid architecture ([roadmap](../roadmap.md), [ADR 0005](../adr/0005-crossover-hybrid-direction.md)); the screening facts below remain useful, the native-first recommendations do not. See the [upstream registry](upstream-registry.md) for the current provenance decision on VIctory-family projects.
|
||||
|
||||
# PortWatch review and a native macOS execution plan
|
||||
|
||||
Reviewed November 24, 2026 (America/Chicago). This is a public-documentation and
|
||||
source-boundary review, not a competitor execution campaign or independent
|
||||
acceptance. **BetterXen does not support commercial Xbox game execution.**
|
||||
|
||||
## Recommendation
|
||||
|
||||
Continue BetterXen as an original ARM64 runtime with its own x86-64 CPU
|
||||
translation and direct Metal backend. The Windows projects expose useful
|
||||
engineering questions, test structures and failure categories. Their code is
|
||||
not a drop-in native port. Do not fork a Windows emulator into this repository,
|
||||
replace the CPU with Rosetta, or add a Vulkan/Windows compatibility runtime.
|
||||
|
||||
The next useful result is an original compiled application that starts through
|
||||
a checked module/runtime path and reaches a translated, checked Metal frame.
|
||||
Broader vector instructions, thread lifecycle, binding metadata and console
|
||||
contracts must advance through explicit fixture-backed increments. Completing
|
||||
synthetic applications alone cannot prove Xbox compatibility.
|
||||
|
||||
## What was inspected
|
||||
|
||||
The tracker snapshot is [PortWatch 2cedf62a](https://github.com/4lwayz/portwatch-vi/blob/2cedf62a16b63697f096763ecb99b4c10d4dbccc/data/tracker.json),
|
||||
whose update timestamp is `2026-11-25T04:22:56.289Z` (November 24 locally).
|
||||
Its 35 efforts, 22 tools and 30 candidates were screened. One candidate repeats
|
||||
XCL. Three efforts have no public repository; seven repository endpoints were
|
||||
unavailable across the combined list. Available repositories were pinned to
|
||||
their observed default-branch commit; their metadata, README and public tree
|
||||
were used to classify target, host assumptions, lineage and evidence scope.
|
||||
The per-project tables below include every entry in these three lists: 85
|
||||
unique repository endpoints were checked, 78 available and seven unavailable.
|
||||
|
||||
This is not a line-by-line audit of every source file, proof of all contributor
|
||||
provenance, or a claim to understand unavailable/private code. No upstream
|
||||
project, setup script, Windows executable, game, shader corpus, asset collection,
|
||||
restricted SDK or decryption tool was run. Archive and protection-related entries
|
||||
were screened at metadata/README level only; no mirrored implementation or
|
||||
restricted payload was recovered. The tracker's flagged/ignored discovery/spam
|
||||
queues are not endorsed engineering candidates and were not imported.
|
||||
|
||||
Selected public architecture/status documentation was read more deeply for
|
||||
VIctory, VIctory-macOS, TuxBox, NativeX, SeriesX and XValkyrie; XSXEmu's README
|
||||
provides detailed admission, TLS and graphics boundaries. Those documents
|
||||
explain their own designs; they do not verify their claimed test/hardware results.
|
||||
The supplied `/so` website URL was unavailable to the web reader; the public,
|
||||
pinned repository data was accessible and matched the initial screened JSON.
|
||||
|
||||
BetterXen's working tree started at `f02eb2678e76e91876be5706ce91dca25dcc3017`
|
||||
with existing local documentation edits. Read-only `git fetch` found newer main
|
||||
[`b2654e93`](https://github.com/MacosPorters/betterxen/tree/b2654e93a42e74e29570183da1f31bb8cdc6f721).
|
||||
A separate ignored source snapshot was inspected without switching, resetting
|
||||
or merging the working tree. This distinction changes the hosted-C status.
|
||||
Local documentation edits from this review do not install that newer runtime.
|
||||
|
||||
## Why the PC results do not transfer directly
|
||||
|
||||
| Layer | Common PC approach described upstream | Native ARM64 BetterXen requirement |
|
||||
| --- | --- | --- |
|
||||
| CPU | Guest x86-64 runs on a matching x86-64 CPU; several projects require AVX2 | Decode/execute or translate each supported form, preserve precise state/faults, and advertise only satisfied guest features. |
|
||||
| Loader/runtime | Windows APIs or Wine/Proton supply much of PE startup, TLS, exceptions, threads, files and CRT behavior | Original checked guest memory, module lifecycle, service implementations, callback bridges and guest exception design. |
|
||||
| Graphics API | Console-facing objects dispatch onto desktop D3D12, sometimes through Vulkan | Explicit validated guest handles/commands and native Metal objects, lifetime, resource state and completion. |
|
||||
| Shaders | RDNA machine code becomes HLSL/DXIL or SPIR-V | Independently verified RDNA-to-IR-to-MSL behavior, entry state and resource bindings. SPIR-V may be an intermediate, not a Vulkan runtime requirement. |
|
||||
| Assets | Title supplies its own loaders or tools convert game-specific data | No need to become an archive viewer to prove guest execution; codecs/layouts require public contracts and demonstrated workload needs. |
|
||||
| Evidence | README milestones, streams, screenshots, compilation counts or self-reported FPS | Pinned original fixtures, independent expectations, actual native execution/readback and candidate-specific receipts. |
|
||||
|
||||
PortWatch is a discovery/editorial service. Its percentages are not compatibility
|
||||
measurements. The observed entries label their verification self-reported;
|
||||
phrases such as “confirmed” inside editorial summaries do not become BetterXen
|
||||
acceptance. Several forks share VIctory/XCL/Leonida lineage: ten forks are not
|
||||
ten independent confirmations. Compilation, shader validation, first pixels,
|
||||
scene completeness, interactive progress and stable play are distinct outcomes.
|
||||
|
||||
## macOS efforts and what “native” means here
|
||||
|
||||
[VIctory-macOS edba53dd](https://github.com/pragyaangaur/VIctory-macOS/blob/edba53ddc2207e6c537679f4ce06f966b7a63a59/README.md)
|
||||
uses Rosetta, CrossOver Wine and D3DMetal for the guest route. Native builds of
|
||||
its portable crates are a different result. Its reported passing tests neither
|
||||
establish a fully ARM64 runtime nor demonstrate playable game execution here.
|
||||
Its [port notes](https://github.com/pragyaangaur/VIctory-macOS/blob/edba53ddc2207e6c537679f4ce06f966b7a63a59/docs/macos.md)
|
||||
provide leads for cache identity, upload visibility, floating-point edge cases,
|
||||
capability/behavior mismatches and masked-store page faults. Reproduce relevant
|
||||
questions with original Metal/CPU fixtures; do not copy its workarounds or assume
|
||||
a D3DMetal defect exists in BetterXen's direct Metal path.
|
||||
|
||||
[XSXEmu 2d937f83](https://github.com/daeken/XSXEmu/blob/2d937f8360fbcdac368a0e363c24df322fa24db2/README.md)
|
||||
is another macOS effort, so “nobody is working on Mac” would be inaccurate.
|
||||
Its guest path uses an x86-64 Mach-O process and Rosetta, while owned shader
|
||||
translation fixtures use Metal. It explicitly separates static audit from
|
||||
execution admission and says no game frame has been produced. Its useful
|
||||
lesson is that entry/binding information and DLL/TLS lifecycle are separate
|
||||
contracts; its Rosetta guest route does not satisfy BetterXen's ARM64 rule.
|
||||
|
||||
[6stars 480d9a4d](https://github.com/meetox80/6stars/blob/480d9a4d00ed11560f7b4d989643723a0f5c451c/README.md)
|
||||
and the separately listed 6stars engine candidate describe Swift/Metal world-data
|
||||
rendering. An independent renderer may produce a convincing scene while never
|
||||
executing the original game program. That is valuable work with a different
|
||||
scope. No verified reusable component or file-level license clearance was
|
||||
established by this review.
|
||||
|
||||
[nativ64 3b826108](https://github.com/Ybucaille/nativ64/blob/3b82610882bc55cb27f0ec563c126a226855a8ea/README.md)
|
||||
targets Linux x86-64. Its central observation is relevant: host Windows APIs
|
||||
that a Windows project forwards still need implementation on a different OS.
|
||||
Its Linux syscalls/futexes and x64 ABI are not native Darwin ARM64 services.
|
||||
BetterXen should prioritize from its own import/fixture failures, not copy that
|
||||
project's title-specific API totals or implementation.
|
||||
|
||||
## BetterXen's actual starting point
|
||||
|
||||
| Area | Observed on current main b2654e93 | Consequence |
|
||||
| --- | --- | --- |
|
||||
| CPU inventory | 498 declared forms, 213 operations; tool classifies 93 operations native and 120 shared-semantics | These are inventory/lowering categories, not 498 independently accepted instructions or a compatibility percentage. VEX remains rejected. |
|
||||
| Typed runtime registry | 47 services: 7 implemented, 37 partial, 3 stubs; tool reports 0 verified entries | This is the typed subset, not the total handwritten runtime. Named exports alone do not prove behavior. |
|
||||
| Hosted C | A1 and A2 are present; PR #283 merged as d26af53c. Gate A records local passes awaiting independent review | Do not open another “implement hosted C” issue. Reproduce/accept the candidate and expand from a failing original workload. |
|
||||
| Modules | startup.rs accepts one image; modules.rs exposes built-in service modules | Built-in LoadLibrary/GetProcAddress is not general EXE plus guest-DLL startup and teardown. |
|
||||
| Threads | Deterministic serial guest scheduler with worker stacks/TEBs, waits and handles | Sleep can stall all workers; static worker TLS and thread/FLS callbacks remain documented gaps. Serial scheduling does not prove parallel x86 memory ordering. |
|
||||
| Graphics | Translated image_sample_lz pixel stage, native texture tests and guest descriptor-table bindings already exist | README X10 and generic “no sampling” descriptions are stale for this bounded path. Broader bindings, control flow and sampling still need contracts. |
|
||||
| Shader inventory | Table records 1,465 identified forms, 189 decoded, 185 IR/MSL, 18 accepted Metal forms; reconciliation finds zero mismatches | Different domains and acceptance stages must stay separate. The compute inventory does not fully describe graphics-only sampling. #225 owns pending acceptance. |
|
||||
| Texture/resource work | Packed BC footprints and bounded private texture staging merged; original resource/draw tests exist | Reuse them. Do not duplicate #260's active format inventory or assume guest/console integration from host upload success. |
|
||||
| Native app | Existing Swift/FFI fixtures; app/CI and usability PRs remain separate | UI/audio/input fixtures are not one integrated compiled guest application. #256 is the existing integration task. |
|
||||
| Console contract | Public AMD desktop ISA/PE/D3D12 documentation and explicit synthetic ABIs | Authentic launch, descriptors/commands and console-specific behavior remain unknown or unverified. No Xbox hardware access exists. |
|
||||
|
||||
Evidence for these boundaries: current-main
|
||||
[CPU registry](https://github.com/MacosPorters/betterxen/blob/b2654e93a42e74e29570183da1f31bb8cdc6f721/docs/cpu/instruction-registry.md),
|
||||
[Gate A](https://github.com/MacosPorters/betterxen/blob/b2654e93a42e74e29570183da1f31bb8cdc6f721/docs/testing/gate-a.md),
|
||||
[startup](https://github.com/MacosPorters/betterxen/blob/b2654e93a42e74e29570183da1f31bb8cdc6f721/crates/loader/src/startup.rs),
|
||||
[module services](https://github.com/MacosPorters/betterxen/blob/b2654e93a42e74e29570183da1f31bb8cdc6f721/crates/loader/src/services/modules.rs),
|
||||
[threads](https://github.com/MacosPorters/betterxen/blob/b2654e93a42e74e29570183da1f31bb8cdc6f721/docs/runtime/threads.md),
|
||||
[graphics compiler](https://github.com/MacosPorters/betterxen/blob/b2654e93a42e74e29570183da1f31bb8cdc6f721/crates/shader/src/graphics.rs),
|
||||
and [semantic coverage](https://github.com/MacosPorters/betterxen/blob/b2654e93a42e74e29570183da1f31bb8cdc6f721/docs/shaders/semantic-coverage.md).
|
||||
These are source/inventory observations. Historical hardware results retain
|
||||
their existing class A scope; none was rerun or independently certified here.
|
||||
|
||||
## What to take forward
|
||||
|
||||
Take **questions and test designs**, then implement independently from primary
|
||||
sources. No emulator source was copied, ported, translated, vendored or adapted.
|
||||
Repository-level license labels below are metadata only. They do not establish
|
||||
per-file grants, GPL-3.0-or-later compatibility or rights to fixtures/data.
|
||||
|
||||
1. Build a small, falsifiable workload before expanding an entire subsystem.
|
||||
TuxBox/NativeX-style separation of loader, ABI, GPU and presentation tests is
|
||||
useful; their own expected outputs cannot become BetterXen's oracle.
|
||||
2. Treat unresolved host services as a concrete inventory. Reuse #211's package
|
||||
census, #254's report schema and #255's startup diagnostics. Keep unsupported
|
||||
calls explicit; never return success merely to get farther.
|
||||
3. Model CPU state and faults before optimizing translation. AVX/YMM, masked
|
||||
memory accesses, unwinding and lifecycle cannot be supplied by ARM64 host
|
||||
calling conventions or a renamed Windows DLL.
|
||||
4. Make shader entry state, resources and pipeline identity explicit. A shader
|
||||
can compile and still read the wrong descriptor or run under the wrong mask.
|
||||
A replaced/skipped shader or an empty draw cannot pass a correctness gate.
|
||||
5. Validate resource ownership and completion before pursuing zero-copy. Apple
|
||||
unified memory does not remove guest/host address translation, storage modes,
|
||||
alignment, cache visibility or in-flight lifetime requirements.
|
||||
6. Expand wave behavior, loops, mesh and ray tracing only as separate reviewed
|
||||
contracts. A first simple scene does not require all of them; future console
|
||||
workloads may. Do not infer optional Metal features from a product name.
|
||||
7. Measure startup/steady-state and correctness separately, with actual host
|
||||
receipts. Cache keys must cover full relevant identity; prewarming is an
|
||||
experiment under #258, not a prerequisite or promised performance win.
|
||||
|
||||
Primary semantic authorities are the [Intel SDM](https://www.intel.com/content/www/us/en/developer/articles/technical/intel-sdm.html),
|
||||
[public PE format](https://learn.microsoft.com/en-us/windows/win32/debug/pe-format),
|
||||
[Microsoft x64 exception handling](https://learn.microsoft.com/en-us/cpp/build/exception-handling-x64),
|
||||
[AMD ISA publications](https://gpuopen.com/amd-gpu-architecture-programming-documentation/),
|
||||
[public resource-binding specification](https://microsoft.github.io/DirectX-Specs/d3d/ResourceBinding.html),
|
||||
and [Apple Metal feature tables](https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf).
|
||||
Class B applies only to what the relevant public specification documents;
|
||||
applying desktop behavior to Xbox needs separate evidence (often C or U).
|
||||
Feature tables are documentation, not our execution evidence across M1–M5.
|
||||
|
||||
## Contributor work and dependencies
|
||||
|
||||
The review is tracked in [#298](https://github.com/MacosPorters/betterxen/issues/298).
|
||||
The new tasks below have bounded deliverables, proposed paths, public references,
|
||||
negative controls and acceptance limits. They are unclaimed implementation work.
|
||||
Design tasks can begin with public documentation; runtime changes must respect
|
||||
parent claims and shared-file ownership. Read every issue comment and linked PR
|
||||
before claiming. Do not claim several tasks in one comment.
|
||||
|
||||
| Priority/order | Work | Dependency and boundary |
|
||||
| --- | --- | --- |
|
||||
| First, research | [#299 AVX/AVX2 state and decode contract](https://github.com/MacosPorters/betterxen/issues/299) | Extends beyond existing #120–#124; keeps CPUID honest. No blanket AVX2 implementation claim. |
|
||||
| First, research | [#300 bounded AMD64 unwind](https://github.com/MacosPorters/betterxen/issues/300) | Separates metadata/stack walking from SEH and C++ exceptions; existing trap stubs remain. |
|
||||
| First, loader contract/fixtures | [#301 original EXE plus two-DLL startup](https://github.com/MacosPorters/betterxen/issues/301) | Reuses #211 census and supplies a prerequisite to #256. Production mapping changes are separately coordinated. |
|
||||
| First, GPU contract | [#302 shader entry and resource bindings](https://github.com/MacosPorters/betterxen/issues/302) | Builds on existing #226 sampling/table work; coordinates #205, #179, #180 and #224. |
|
||||
| First, QA design | [#303 native capability receipts](https://github.com/MacosPorters/betterxen/issues/303) | Reuses #254 schema, #248 app CI and #158 dependency evidence. No automatic fleet posting. |
|
||||
| Next, scheduler implementation | [#304 Sleep yields ready workers](https://github.com/MacosPorters/betterxen/issues/304) | Narrow #228 child; coordinate parent and runtime PRs before code edits. |
|
||||
| First, lifecycle design | [#305 worker static TLS and callbacks](https://github.com/MacosPorters/betterxen/issues/305) | Depends on module/scheduler contracts for production; no competing scheduler. |
|
||||
| Parallel, public research | [#306 console launch/graphics evidence ledger](https://github.com/MacosPorters/betterxen/issues/306) | Links existing public research; unknown console details remain blockers rather than guesses. |
|
||||
|
||||
Reuse existing tasks rather than adding duplicates: #179 runtime uniform
|
||||
branches, #180 bounded loops, #205 semantic expansion, #225 independent shader
|
||||
acceptance, #224 fences, #147 resource-update workload, #148 shared lifetime,
|
||||
#256 startup-to-frame integration, #260 format inventory, #247 quick start,
|
||||
#250 session errors, #254 compatibility reports and #255 worker diagnostics.
|
||||
PRs #293–#297 already cover app CI, CPU coverage, selection ordering, Open and
|
||||
texture inventory respectively. Runtime PRs #263/#290 overlap substantially;
|
||||
their author/maintainer must resolve them before new runtime edits. These
|
||||
references are destination-repository numbers, not imported source numbers.
|
||||
|
||||
The replacement [development phases](../archive/development-phases-native-first.md) define the sole
|
||||
active work order, from compiled guest boot through modular workers, a
|
||||
guest-controlled Metal scene, an interactive application, a compatibility
|
||||
corpus, sustained native execution and conditional Xbox experiments.
|
||||
Hosted C is implemented on inspected main, awaiting independent acceptance;
|
||||
it is no longer an untouched prerequisite. Original integration, then measured
|
||||
optimization, then only evidence-admissible compatibility experiments is the
|
||||
path. There is no supported date or estimate for running a commercial game.
|
||||
|
||||
## Complete project screen
|
||||
|
||||
Each pin links to the exact README reviewed. “Unavailable” means that the
|
||||
observed public GitHub endpoint returned 404; it does not prove why or justify
|
||||
looking for restricted mirrors. “Unresolved” licenses and NOASSERTION are not
|
||||
reuse permission. Descriptions below classify documentation, not executed code.
|
||||
|
||||
### Tracker efforts (35)
|
||||
|
||||
| Entry | Pinned public documentation | Classification and BetterXen decision |
|
||||
| --- | --- | --- |
|
||||
| ZETTROX (`Zettrox/ztrx`) | [`90b529f8`](https://github.com/Zettrox/ztrx/blob/90b529f878a470fec9bf07b7be316bc769a12232/README.md); license metadata: `GPL-3.0` | VIctory/victory-fork lineage; Windows x64 + D3D12. Hardware tuning and reported gameplay are not independent native-Mac evidence. |
|
||||
| Uilian (`uiliannn/VItoriaBr`) | [`c2485475`](https://github.com/uiliannn/VItoriaBr/blob/c24854750132af24c10e954765047525e0249bd3/README.md); license metadata: `GPL-3.0` | VIctory-family Windows/DXIL fork; README and tracker differ on readiness. Keep results self-reported; no ARM64 execution path. |
|
||||
| suri | No public repository in tracker | Private/stream report only; no implementation inspection or reproducibility. No source/fixture reuse proposed. |
|
||||
| omonkey | No public repository in tracker | Private/stream report only; no implementation inspection or reproducibility. No source/fixture reuse proposed. |
|
||||
| CGBJ | No public repository in tracker | Private/stream report only; no implementation inspection or reproducibility. No source/fixture reuse proposed. |
|
||||
| hyphennn (`fxceless/victory-fork`) | [`310c6eb6`](https://github.com/fxceless/victory-fork/blob/310c6eb6c16822ab95076aad61fce19bba86bb98/README.md); license metadata: `GPL-3.0` | VIctory rendering fork, Windows x64/D3D12; useful failure categories include bindings and mesh work. No implementation reuse. |
|
||||
| VIctory (`Marvisak/VIctory`) | [`940d32f6`](https://github.com/Marvisak/VIctory/blob/940d32f69b22265690a0b5a15d6ded572ba33baf/README.md); license metadata: `GPL-3.0` | Windows x64 direct guest execution, HLE and D3D12/DXIL. Public architecture documents host pass-through and title-specific work. |
|
||||
| xbox-emulator (`omonkeyz/xbox-emulator`) | [`f89e4106`](https://github.com/omonkeyz/xbox-emulator/blob/f89e4106fe8a1728515afa34ceb5097132cadcda/README.md); license metadata: `GPL-3.0` | TomBox continuation; Windows-process runtime and RDNA shader work. README title reports are unverified here; assets/captures are excluded. |
|
||||
| XCL (`xcl-dev/xcl`) | [`f5c5bdf0`](https://github.com/xcl-dev/xcl/blob/f5c5bdf0e91035f8f1404f46f4f2f7aedc259e7f/README.md); license metadata: `GPL-2.0` | Windows x64 direct execution plus D3D12/DXIL; host services and pipeline behavior matter. GPL-2.0-only README; no reuse clearance. |
|
||||
| ScarlettX (`Freminet/ScarlettX`) | [`01c642cf`](https://github.com/Freminet/ScarlettX/blob/01c642cf62a6d9978f535e2c438c488ebcb4cd39/README.md); license metadata: `unresolved` | Windows x64 HLE/D3D12; separates console precompiled-shader gaps from desktop paths. Console-binary-derived findings need independent public evidence. |
|
||||
| TuxBox (`brcly/TuxBox`) | [`97b8ad31`](https://github.com/brcly/TuxBox/blob/97b8ad3192def18d491fe72ea3a55e204bc77a5d/README.md); license metadata: `Apache-2.0` | x86-64 Windows and Linux/Proton; owned guest fixtures and provider-specific failures are useful testing patterns, not an ARM64 solution. |
|
||||
| americas-recomp (`realdody/americas-recomp`) | Unavailable (404); no source recovered | Unavailable public endpoint; implementation, provenance and current execution status remain unknown. |
|
||||
| PE-Vulkan project (`ItsNotRexed/Leonida`) | Unavailable (404); no source recovered | Unavailable public endpoint; implementation, provenance and current execution status remain unknown. |
|
||||
| OpenScarlett (`californiaAlmonds/OpenScarlett`) | [`022a8b25`](https://github.com/californiaAlmonds/OpenScarlett/blob/022a8b25148cc08412df8ac7e752b9efed4cd819/README.md); license metadata: `MIT` | Windows x64, D3D12/Vulkan; broad completeness claims are upstream reports. Public-spec-backed original fixtures are the only proposed transfer. |
|
||||
| scarlett-layer (`jadeowaowa/scarlett-layer`) | [`0e436b3e`](https://github.com/jadeowaowa/scarlett-layer/blob/0e436b3e1c654765b193c1cb705918fbf101b10b/README.md); license metadata: `Apache-2.0` | Windows import interception/shims, D3D12 and synthetic test tiers; useful distinction between desktop samples and console compatibility. |
|
||||
| Xbox2Windows (`R0Y00/Xbox2Windows`) | [`ab9a020c`](https://github.com/R0Y00/Xbox2Windows/blob/ab9a020c0783f9ce1dd10876cbeb119707b9ada9/README.md); license metadata: `MIT` | x64-to-C++ AOT/loader and DXIL research; distinguishes modified diagnostic startup from original executable compatibility. Host ABI still differs. |
|
||||
| AnyXboxX (`LooperSalty/AnyXboxX`) | [`b92a71b9`](https://github.com/LooperSalty/AnyXboxX/blob/b92a71b9308e76f8ec9059c01d6e18f21611dc20/README.md); license metadata: `GPL-3.0` | Unicorn research and native Windows routes; current README also uses VIctory lineage. Do not treat its older interpreter label as ARM64 readiness. |
|
||||
| XValkyrie (`sammwyy/xvalkyrie`) | [`c4c04970`](https://github.com/sammwyy/xvalkyrie/blob/c4c04970930d029a25622743e3ff4ef873ac17a6/README.md); license metadata: `GPL-3.0` | Windows x64 console API and shader translation; useful subsystem boundaries. Console/title-specific ABI claims remain unverified. |
|
||||
| GTAVI-Recomp (`JamesCicada/GTAVI-Recomp`) | [`71766d8b`](https://github.com/JamesCicada/GTAVI-Recomp/blob/71766d8b5c669bc44639ad85bfd84edd8337c75a/README.md); license metadata: `GPL-2.0` | PS5/AnyPS5 route, not an Xbox launch contract; do not adapt emulator source or transfer PS5 APIs to Series. |
|
||||
| AnyXboxSeries (`edupode/anyxboxseries`) | [`9ca2d053`](https://github.com/edupode/anyxboxseries/blob/9ca2d05329fe878db6abea6060889f9a95566719/README.md); license metadata: `NOASSERTION` | Windows D3D12 loader/inspection and an original sample; sample presentation does not establish Xbox guest execution. |
|
||||
| SCARAB (`p-portela/SCARAB`) | [`8140e0be`](https://github.com/p-portela/SCARAB/blob/8140e0be4908499a5c4381eb4532410f05e39369/README.md); license metadata: `GPL-3.0` | Windows/D3D12 bridge, Linux through vkd3d-proton; memory/presentation incompleteness is explicit. Not native ARM64. |
|
||||
| AnyBox (`Dark3581/AnyBox`) | Unavailable (404); no source recovered | Unavailable public endpoint; implementation, provenance and current execution status remain unknown. |
|
||||
| PercyScarlett (`rpatty-dev/PercyScarlett`) | [`64719f96`](https://github.com/rpatty-dev/PercyScarlett/blob/64719f96d32f74d9d68cec69243b515ba675741f/README.md); license metadata: `GPL-2.0` | Windows x64/D3D12; README distinguishes existing DXIL titles from RDNA lifting and reports instability. GPL-2.0-only; no reuse. |
|
||||
| GrandTheftXbox (`zohaiblazuli/GrandTheftXbox`) | Unavailable (404); no source recovered | Unavailable public endpoint; implementation, provenance and current execution status remain unknown. |
|
||||
| Scarlett Windows Compat (`ProhorovIlja/NativeX-Runtime`) | [`b3087ce0`](https://github.com/ProhorovIlja/NativeX-Runtime/blob/b3087ce0ab191227dc9e7af37cab97a0b097bb98/README.md); license metadata: `MIT` | Portable inspection and separate Windows/Linux ABI/graphics probes. Useful test decomposition; not a complete application runtime. |
|
||||
| DedSec (`Hylanderry/DedSec`) | [`c44b38ca`](https://github.com/Hylanderry/DedSec/blob/c44b38ca0207900cd27c687bb9213a6c8474bc69/README.md); license metadata: `MIT` | Windows x64/direct execution and D3D12; performance/feature claims need reproducible evidence. No Mac execution established. |
|
||||
| Xbgtasix (`ljm-233/Xbgtasix`) | [`1a767872`](https://github.com/ljm-233/Xbgtasix/blob/1a7678729cd436f9adaa9772b76d97af3d292321/README.md); license metadata: `GPL-3.0` | Windows compatibility DLLs rely on the Windows loader for imports, relocation and TLS. This omitted host work is required on Darwin. |
|
||||
| SeriesX Emulator (`anrq0/SeriesX-Emulator`) | [`4f07d76f`](https://github.com/anrq0/SeriesX-Emulator/blob/4f07d76f9f641ce85ce4238081c06d1cef1b7521/README.md); license metadata: `MIT` | Interpreter, original test applications and desktop launcher; README explicitly excludes commercial compatibility. Reported vectors are not our oracle. |
|
||||
| GTA6-COMPAT-LAYER (ScarlettCompat) (`SSTGxf/ScarlettCompat`) | [`b92f060b`](https://github.com/SSTGxf/ScarlettCompat/blob/b92f060b1754580338dc30f57bb50777af38749d/README.md); license metadata: `MIT` | Windows native loader and console shims. Diagnostic bootstrap is a useful stage model; passing imports is not an implemented API. |
|
||||
| XlaunchVI (`JPTuba9/xlaunch-vi`) | [`40feebd7`](https://github.com/JPTuba9/xlaunch-vi/blob/40feebd73a59c13ac5d65c3e61d21906111294e7/README.md); license metadata: `unresolved` | Windows x64, D3D12/Vulkan and frontend. README explicitly denies game compatibility; UI work is separate from guest execution. |
|
||||
| OpenScarlett (Community Edition) (`OpenCommunityEdition/OpenScarlett`) | [`d1285fdd`](https://github.com/OpenCommunityEdition/OpenScarlett/blob/d1285fddbe399927581a772f536239b33a1e2cf4/README.md); license metadata: `AGPL-3.0` | Windows/Linux API layer; README build requires GDKX. Do not follow restricted tooling dependencies or import its sources. |
|
||||
| Five Star Recomp (`ThatRecompDev/five-star-recomp`) | [`fb3b3a2d`](https://github.com/ThatRecompDev/five-star-recomp/blob/fb3b3a2def5af6eef6004c954c11f2cd22574168/README.md); license metadata: `GPL-3.0` | Windows platform, shader and asset tools; title startup claims do not establish a complete scene or native Mac execution. |
|
||||
| G6Recomp (`Kajcsi/G6Recomp`) | [`82ccaa5d`](https://github.com/Kajcsi/G6Recomp/blob/82ccaa5d4b3fdc1edb9cdd95c8dbab4ee7cde352/README.md); license metadata: `GPL-3.0` | Windows AVX2/direct-execution loader with fixture tests; static-recompilation name does not remove reliance on x64/Windows ABI. |
|
||||
| GTA6-BootTest (`OnlyMoisties/GTA6-BootTest`) | [`32683d8f`](https://github.com/OnlyMoisties/GTA6-BootTest/blob/32683d8fe2841bddeb0b437109e97bc32cf55724/README.md); license metadata: `unresolved` | Windows debugger/shim/GPU startup harness. Reported first UI frame is not full scene correctness; no root license identified by metadata. |
|
||||
| Palmetto (`luizwidmer/palmetto`) | [`6416a273`](https://github.com/luizwidmer/palmetto/blob/6416a273336599341dfd31e64cc3da3fd1b855ed/README.md); license metadata: `GPL-3.0` | Windows runtime and RDNA-to-SPIR-V/Vulkan path; behavior-stage reporting is useful, runtime/backend is incompatible with our target. |
|
||||
|
||||
### Tracker tools (22)
|
||||
|
||||
| Entry | Pinned public documentation | Classification and BetterXen decision |
|
||||
| --- | --- | --- |
|
||||
| `lynxnathan/rage-tools-vi` | [`547ee9ba`](https://github.com/lynxnathan/rage-tools-vi/blob/547ee9ba2dde236644a597cef65a18f7bd5549be/README.md); license metadata: `MIT` | Asset/catalog tooling; README mentions executable-derived information. No derived corpus imported; not a CPU/runtime shortcut. |
|
||||
| `fishingpvalues/gta6-pc-port-hub` | [`3a7d8d18`](https://github.com/fishingpvalues/gta6-pc-port-hub/blob/3a7d8d18f6fdc2071f8609f35153fb07ac25d1b5/README.md); license metadata: `CC0-1.0` | Archived coordination hub. Its missing-executable snapshot is historical, not evidence of current file availability or native compatibility. |
|
||||
| `holdmysocks/SixNG` | [`8897a1f6`](https://github.com/holdmysocks/SixNG/blob/8897a1f60c6700553987954f567d9146f898d882/README.md); license metadata: `GPL-3.0` | Asset exporter with explicit texture fallback limitations; fallback pixels must never become BetterXen correctness evidence. Defer format work to #260. |
|
||||
| `rpatty-dev/PercyStar` | [`ca4cd4c0`](https://github.com/rpatty-dev/PercyStar/blob/ca4cd4c09bb3a4e29cc2d33e69385725c5fb2220/README.md); license metadata: `NOASSERTION` | Asset/shader/media tools with custom attribution terms. macOS tooling does not establish guest execution or GPL-compatible reuse. |
|
||||
| `breadbbbb/rpf9-explorer` | [`cab9bb6e`](https://github.com/breadbbbb/rpf9-explorer/blob/cab9bb6ebe6d46fec6ac90ee5004bdd8cfd9e31a/README.md); license metadata: `unresolved` | Cross-platform asset viewer/exporter; root grant unresolved in metadata. Exclude code/assets; sample viewing is not guest execution. |
|
||||
| `Ahmet-Dedeler/bcpack-rs` | [`b1c3099a`](https://github.com/Ahmet-Dedeler/bcpack-rs/blob/b1c3099a3402de8b76c9263a828791bd8bc0c930/README.md); license metadata: `NOASSERTION` | Texture codec research with reported synthetic tests; useful codec boundary, but exact tables/provenance/file licenses are unreviewed. Defer to #260. |
|
||||
| `nullbrik/RageForge` | Unavailable (404); no source recovered | Unavailable public endpoint; implementation, provenance and current execution status remain unknown. |
|
||||
| `woreksami/ttpf-studio` | [`a2fe110d`](https://github.com/woreksami/ttpf-studio/blob/a2fe110d8e7aeb8ed3be37c365c75078a408c089/README.md); license metadata: `MIT` | Texture/archive/video tooling. No original executable execution; no proprietary payload or replacement asset imported. |
|
||||
| `walkthestars/GTA6-Asset-Info` | [`bad5bc21`](https://github.com/walkthestars/GTA6-Asset-Info/blob/bad5bc2180ade416eafdb50aa21e21eeec5adbda/README.md); license metadata: `GPL-3.0` | Asset-format notes for SixNG. Discovery only; derived samples/tables remain outside this review. |
|
||||
| `Ahmet-Dedeler/awesome-gta6-reverse-engineering` | [`34a6e945`](https://github.com/Ahmet-Dedeler/awesome-gta6-reverse-engineering/blob/34a6e945b9698975ccd4e0c2e039034914dcc278/README.md); license metadata: `NOASSERTION` | Discovery index. Linked tools, code and asset claims have separate provenance and terms; no linked payloads were obtained. |
|
||||
| `HolyRoses/gta6-explorer` | [`8e383a49`](https://github.com/HolyRoses/gta6-explorer/blob/8e383a49d07da5068fa30ebf208025e307018fcc/README.md); license metadata: `MIT` | Read-only package/asset inspection; not a guest runtime. No package bytes or format-derived corpus imported. |
|
||||
| `meetox80/6stars` | [`480d9a4d`](https://github.com/meetox80/6stars/blob/480d9a4d00ed11560f7b4d989643723a0f5c451c/README.md); license metadata: `unresolved` | Swift/Metal world-data renderer. Native graphics demonstration is a different objective from executing original Xbox CPU/shader code. |
|
||||
| `Ahmet-Dedeler/rage9-re` | [`30c6d215`](https://github.com/Ahmet-Dedeler/rage9-re/blob/30c6d2150ad9d3021802f509ff3ee232d466f499/README.md); license metadata: `NOASSERTION` | Animation/script asset-format tools, not executable compatibility. No asset samples or derived format tables imported. |
|
||||
| `Albotterin/AWC_from_RPF9_Extractor` | [`decfde54`](https://github.com/Albotterin/AWC_from_RPF9_Extractor/blob/decfde54243d9a982550b08c7db21c34a20a1775/README.md); license metadata: `MIT` | Audio extraction tooling with upstream dependency/license scopes. Does not implement guest audio APIs; no extracted audio or code reuse. |
|
||||
| `SentinelInteractive/0x52504639` | [`f1a383a7`](https://github.com/SentinelInteractive/0x52504639/blob/f1a383a72e90706b88d82f0ed1a674a0d7fcba58/README.md); license metadata: `MIT` | Format notes/catalogs, no execution evidence. Do not promote derived counts into console support. |
|
||||
| `JoshRob297/rpf9-research` | [`144d3451`](https://github.com/JoshRob297/rpf9-research/blob/144d345191bd37de3f6bd5e85df3e8ae8815552e/README.md); license metadata: `GPL-3.0` | Container research/catalogs; protected-index/key questions are outside BetterXen scope. No derived indexes imported. |
|
||||
| `Librett0/vice-lens` | [`8b8c8a84`](https://github.com/Librett0/vice-lens/blob/8b8c8a847ef926d8d6298ecfade142db19cfce5d/README.md); license metadata: `MIT` | Asset viewer/world renderer and media tooling; viewing a scene is not original-game execution. No asset/capture reuse. |
|
||||
| `batatinhafcbatatinha-pixel/xseriesrecomp` | Unavailable (404); no source recovered | Unavailable public endpoint; implementation, provenance and current execution status remain unknown. |
|
||||
| `sub-north/xbox-hle-lab` | [`8863028b`](https://github.com/sub-north/xbox-hle-lab/blob/8863028b486dedf660303fcd3c756b05bbbebf91/README.md); license metadata: `MIT` | Separate original probes, docs and XCL patches with different license scopes. Useful falsifiable-reproduction discipline; no patch reuse. |
|
||||
| `kry-vex-gta/XBOX-Inspector` | [`0a3d067f`](https://github.com/kry-vex-gta/XBOX-Inspector/blob/0a3d067f7167a30b5e2517a4e781ec1ada3006d7/README.md); license metadata: `MIT` | Static inspection/recompilation prechecks. Metadata analysis is not guest execution; existing #211/#254 own comparable BetterXen work. |
|
||||
| `nineforge0/forge9` | [`f40381ca`](https://github.com/nineforge0/forge9/blob/f40381cac62ade007a62e728eaa988fd9677bec4/README.md); license metadata: `MIT` | README advertises decryption and executable-derived key/table workflow. Excluded from implementation/input research; no such code or inputs accessed. |
|
||||
| `TheoBIET/OpenVI` | [`fd415911`](https://github.com/TheoBIET/OpenVI/blob/fd4159118e750084451b9bad364169660daaa5e2/README.md); license metadata: `GPL-3.0` | Cross-platform asset explorer. macOS UI availability is not native emulation; no content or auto-update workflow executed. |
|
||||
|
||||
|
||||
### Tracker candidates (30, including repeated XCL)
|
||||
|
||||
| Entry | Pinned public documentation | Classification and BetterXen decision |
|
||||
| --- | --- | --- |
|
||||
| `edsuuu/VI-BR-PORT` | [`7a30f506`](https://github.com/edsuuu/VI-BR-PORT/blob/7a30f5063dafeda1ceab84d251c22dc581d4dfc6/README.md); license metadata: `GPL-3.0` | VIctory-family Windows/NVIDIA memory tuning; wave32 assumptions must not be transferred to Apple GPU capability claims. |
|
||||
| `xcl-dev/xcl` | [`f5c5bdf0`](https://github.com/xcl-dev/xcl/blob/f5c5bdf0e91035f8f1404f46f4f2f7aedc259e7f/README.md); license metadata: `GPL-2.0` | Windows x64 direct execution plus D3D12/DXIL; host services and pipeline behavior matter. GPL-2.0-only README; no reuse clearance. |
|
||||
| `ZigZagBoi1/ScarlettPort` | [`48ba23a9`](https://github.com/ZigZagBoi1/ScarlettPort/blob/48ba23a91a83121f8d0625a633e88fa463d5a0ca/README.md); license metadata: `NOASSERTION` | Windows x64/D3D12 compatibility route; no native Darwin CPU/runtime established. |
|
||||
| `Steinkoloss/port-of-the-americas` | [`0f3be36a`](https://github.com/Steinkoloss/port-of-the-americas/blob/0f3be36aaefe69c25f06e05222b88453f3557acd/README.md); license metadata: `unresolved` | Linux x64/Proton/vkd3d-proton shims; README names PE-Vulkan project shader conversion. No implementation reuse. |
|
||||
| `Leucodermique/VIce` | [`8c7b24fd`](https://github.com/Leucodermique/VIce/blob/8c7b24fda90eb08fe64044726b7c880065a86ee0/README.md); license metadata: `GPL-3.0` | VIctory-based Windows distribution/frontend; consolidation does not independently validate combined changes. |
|
||||
| `flipflapov/DSTN` | [`7066ae66`](https://github.com/flipflapov/DSTN/blob/7066ae669c7b0e20d0b05675826169cdc7442883/README.md); license metadata: `GPL-3.0` | PE-Vulkan project fork; tool portability on macOS does not establish native guest execution. No implementation reuse. |
|
||||
| `daeken/XSXEmu` | [`2d937f83`](https://github.com/daeken/XSXEmu/blob/2d937f8360fbcdac368a0e363c24df322fa24db2/README.md); license metadata: `MIT` | macOS Rust host with Rosetta guest execution and separate native Metal shader fixtures; not a fully ARM64 guest CPU path. No game frame claimed. |
|
||||
| `SixLauncher/VILauncher` | [`bf2f6ca9`](https://github.com/SixLauncher/VILauncher/blob/bf2f6ca9a6445aee6ebdff2b1cef87266f9cf1f4/README.md); license metadata: `GPL-3.0` | Linux launcher selecting VIctory/XCL under Wine/Proton. Not a new guest execution or Metal implementation. |
|
||||
| `4Sakens/Project-Kalaga` | [`56b41fb4`](https://github.com/4Sakens/Project-Kalaga/blob/56b41fb4a68b89e5e356c1445699ba4ac6b8cc83/README.md); license metadata: `unresolved` | Windows consolidation of existing efforts; aggregated subsystems and local paths are not independent compatibility evidence. |
|
||||
| `idvwork/rebox` | [`a833078e`](https://github.com/idvwork/rebox/blob/a833078e3366a70a74edef0cbfe01b80a81dd55c/README.md); license metadata: `GPL-2.0` | WineGDK/vkd3d-proton and AnyPS5 shader lineage; incompatible runtime and no emulator adaptation permitted. |
|
||||
| `Yhozen/series-web` | [`d7512b29`](https://github.com/Yhozen/series-web/blob/d7512b299fe2836e08783665308cd8c4bb924345/README.md); license metadata: `GPL-2.0` | PISCO AOT x86-to-WebAssembly/runtime research; original browser workloads differ from native ARM64/Metal and Xbox compatibility. |
|
||||
| `DesignWithTommy/Neonbridge` | [`954c00c5`](https://github.com/DesignWithTommy/Neonbridge/blob/954c00c506a8616e985e94e8ea6bcbfba7f80f48/README.md); license metadata: `GPL-3.0` | Windows VIctory-family launcher/runtime; frontend and startup improvements are not CPU translation for ARM64. |
|
||||
| `moonrelax/basalt` | [`8af09135`](https://github.com/moonrelax/basalt/blob/8af091350e0d5cdf89f3736a756235a72b67bea9/README.md); license metadata: `MIT` | Original interpreter/cooperative scheduler research; GPU objects are fake and no rendering is claimed. Do not reuse stubs as acceptance. |
|
||||
| `ka1qux/victory-ka1qux` | [`77b8a9eb`](https://github.com/ka1qux/victory-ka1qux/blob/77b8a9eb0d29521f34ffe6061530cc873090e844/README.md); license metadata: `GPL-3.0` | VIctory-family AMD Windows rendering fork. Vendor-specific counters and claimed fixes need independent original tests. |
|
||||
| `ethan00013/keylime` | [`361c7e94`](https://github.com/ethan00013/keylime/blob/361c7e94ab9d29d88cb1e5bfaadc8c3fb909bebc/README.md); license metadata: `GPL-3.0` | Windows x64 runtime with Vulkan/SPIR-V; no native Mac route. Backend and console-specific claims need independent contracts. |
|
||||
| `Joaco9020/mangrove` | [`d16326c6`](https://github.com/Joaco9020/mangrove/blob/d16326c652b6f82e7b59b390f63e37cab816acd3/README.md); license metadata: `GPL-3.0` | VIctory-family Windows fork tuned for lower-VRAM NVIDIA GPUs. Settings are not portable Metal correctness work. |
|
||||
| `chvabalo-interactive/sludgemu` | [`29cf795e`](https://github.com/chvabalo-interactive/sludgemu/blob/29cf795e23bb4917b9a8acd6be95d38a0f3b99b1/README.md); license metadata: `unresolved` | Windows direct guest execution and D3D12/DXIL, early startup with logging stubs. Stubs are not behavior support. |
|
||||
| `larpingvibecoder/sonoma` | [`835f386a`](https://github.com/larpingvibecoder/sonoma/blob/835f386a144eca0b903b8bec63c0a003d7e07071/README.md); license metadata: `Apache-2.0` | Windows Rust runtime/direct DXIL, early proof of concept; name does not indicate macOS support. |
|
||||
| `7jycwjmbfn-eng/scenegate-vi` | [`d5908947`](https://github.com/7jycwjmbfn-eng/scenegate-vi/blob/d590894710631a3c6adc6cca526c44d3c0c2bd41/README.md); license metadata: `MIT` | Windows/Vulkan startup and scene work based on PE-Vulkan project; retain only documented failure categories, not code or title-derived inputs. |
|
||||
| `TaynanGT/victory-windows-anterior-20261125` | Unavailable (404); no source recovered | Unavailable public endpoint; implementation, provenance and current execution status remain unknown. |
|
||||
| `TaynanGT/victory-windows` | [`cdcff8fe`](https://github.com/TaynanGT/victory-windows/blob/cdcff8fe96182bade41343a10b985c028e9e8968/README.md); license metadata: `GPL-3.0` | VIctory-family Windows work on a non-main default branch; pin the actual branch, not its name. |
|
||||
| `Archivist-Atlas/gta-vi-astral` | [`ff21332e`](https://github.com/Archivist-Atlas/gta-vi-astral/blob/ff21332e5ea2ea1c254a97c0b3036d36ff8e79ce/README.md); license metadata: `unresolved` | Go Windows runtime research citing VIctory/Leonida designs; no independent ARM64/Metal execution established. |
|
||||
| `airpiglabs/crouton` | [`faad29e6`](https://github.com/airpiglabs/crouton/blob/faad29e6af4c45804cfa8a42901341a52d9c824c/README.md); license metadata: `GPL-2.0` | XCL/Bathyal lineage, Windows then Wine/Proton; GPL-2.0-only and incompatible host/runtime route. |
|
||||
| `natedemoss/vice-pc` | [`2f98c053`](https://github.com/natedemoss/vice-pc/blob/2f98c05325237bc8ed8faf0e7b95bc0e6d22b9bb/README.md); license metadata: `MIT` | Windows loader proof of concept; README says nothing boots. No ARM64 or Metal evidence. |
|
||||
| `JoseArranzSanchez/GTA6_PCPORT_INFO` | [`585b42a1`](https://github.com/JoseArranzSanchez/GTA6_PCPORT_INFO/blob/585b42a184bf1cdf1a5f8e76e0d2e7f8a9102857/README.md); license metadata: `NOASSERTION` | Secondary feasibility report, not implementation or primary legal authority. No legal conclusions adopted from it. |
|
||||
| `DBWilliamEngineering/IraRationis` | [`67106e80`](https://github.com/DBWilliamEngineering/IraRationis/blob/67106e80ef34407f545b82bbd9b2c244f304ca3c/README.md); license metadata: `GPL-3.0` | C#/.NET AOT adaptation of ztrx; Windows x64 target remains. Review mixed license scopes if ever considering unrelated tooling. |
|
||||
| `Guernica4u/GTA6-PC-Port-Archive` | [`7b69fa54`](https://github.com/Guernica4u/GTA6-PC-Port-Archive/blob/7b69fa5430ae19fd013b0ba19ffbd7badf3b93e8/README.md); license metadata: `unresolved` | Archive of other projects. Metadata/README screen only; do not use it to recover unavailable or prohibited implementation/material. |
|
||||
| `idvwork/6stars-gta-vi-engine` | [`26a52ba2`](https://github.com/idvwork/6stars-gta-vi-engine/blob/26a52ba2ce5504c2c94a77c15838573538da5b70/README.md); license metadata: `unresolved` | Swift/Metal asset-world renderer, same stated approach as 6stars. Rendering data is distinct from executing the original guest; license/provenance unresolved. |
|
||||
| `Ybucaille/nativ64` | [`3b826108`](https://github.com/Ybucaille/nativ64/blob/3b82610882bc55cb27f0ec563c126a226855a8ea/README.md); license metadata: `Apache-2.0` | Linux x86-64 Windows-API replacement library, not CPU translation. Its host-API inventory explains native-port work hidden by Windows pass-through. |
|
||||
| `sleep10dev/XPORT` | [`2baf2a0f`](https://github.com/sleep10dev/XPORT/blob/2baf2a0f7c2af9f031158e082dfc4a6bb5b8266c/README.md); license metadata: `GPL-3.0` | Windows Rust loader/HLE/partial RDNA/D3D12 research, no demonstrated game compatibility. |
|
||||
|
||||
|
||||
### Explicitly supplied Mac project and tracker
|
||||
|
||||
| Project | Pin | Decision |
|
||||
| --- | --- | --- |
|
||||
| `pragyaangaur/VIctory-macOS` | [`edba53dd`](https://github.com/pragyaangaur/VIctory-macOS/blob/edba53ddc2207e6c537679f4ce06f966b7a63a59/README.md); license metadata: `GPL-3.0` | Wine/CrossOver + Rosetta + D3DMetal guest route. Native platform unit tests are distinct from Windows-under-Wine GPU tests. |
|
||||
| `4lwayz/portwatch-vi` | [`2cedf62a`](https://github.com/4lwayz/portwatch-vi/blob/2cedf62a16b63697f096763ecb99b4c10d4dbccc/README.md); license metadata: `unresolved` | Editorial discovery site and JSON data, not an emulator. Scores and live-stream summaries are not independent acceptance. |
|
||||
|
||||
## Verification performed and remaining limits
|
||||
|
||||
Read-only inventories ran for both the working-tree baseline and the extracted
|
||||
current-main snapshot. Working-tree CPU/runtime counts were 491 forms/206
|
||||
operations and 20 typed services; current main reports 498/213 and 47. Shader
|
||||
reconciliation reported zero mismatches for both. These checks inspect catalogs;
|
||||
they are not CPU instruction execution, GPU tests or independent acceptance.
|
||||
|
||||
Documentation checks also ran successfully on the working-tree candidate:
|
||||
`python3 scripts/audit/status.py --check`, `scripts/audit/claims.sh` (22 claims),
|
||||
`scripts/audit/dependencies.sh` (five graphics crates), Markdown local-file link
|
||||
checks and `git diff --check`. These audit results do not verify runtime changes
|
||||
present only on the separately inspected newer main snapshot.
|
||||
|
||||
Research metadata and ignored raw documentation are retained locally under
|
||||
`artifacts/research-portwatch/`. GitHub API reads and issue/PR state checks
|
||||
establish accessibility and observed state. Python HTTPS initially failed
|
||||
certificate verification; authenticated `gh api` reads succeeded without
|
||||
turning off certificate checks. No dependency was installed to work around it.
|
||||
|
||||
No Rust build, CPU execution suite, native GPU test, demo, fuzz, mutation or
|
||||
benchmark ran for this documentation task. New acceptance must use the exact
|
||||
candidate, actual native tool architecture and actual eligible hardware.
|
||||
Independent reviewers have not certified this report's proposed implementations.
|
||||
Nothing was committed, pushed, merged, released or installed by this review.
|
||||
The GitHub research/follow-up issues were created at the user's request.
|
||||
@@ -0,0 +1,26 @@
|
||||
# Primary-source verification (2026-11-25)
|
||||
|
||||
Re-checks claims first taken from search summaries in [hybrid-backlog-research-2026-11-25.md](hybrid-backlog-research-2026-11-25.md). Evidence class D (public documentation read; nothing installed or run). Not legal advice. #363 still has to re-derive these independently.
|
||||
|
||||
| Claim | Result | Primary source read |
|
||||
| --- | --- | --- |
|
||||
| CrossOver offers the backends Auto, D3DMetal, DXMT, DXVK and Wine | **Confirmed.** Auto uses CodeWeavers' per-game database and wined3d if none is given; D3DMetal covers DirectX 11 and 12; DXMT is Metal-based Direct3D 11; DXVK is Vulkan-based Direct3D 10 and 11; DLSS via MetalFX applies to D3DMetal and DXMT only | support.codeweavers.com "Advanced Settings in CrossOver Mac 26" (modified 2026-02-10). That page is for CrossOver 26 and does not name MoltenVK |
|
||||
| `CX_GRAPHICS_BACKEND` in `cxbottle.conf` is a supported interface | **Not confirmed.** Neither CodeWeavers page read mentions it or `cxbottle`, `cxstart` or `cxrun`. It appears only in third-party projects. Treat as undocumented; #350 decides | Same page and support.codeweavers.com "Advanced CrossOver Mac Configuration" |
|
||||
| Documented configuration surfaces | The second page documents `defaults` keys in `~/Library/Preferences/com.codeweavers.CrossOver.plist` (BottleDir, ManagedBottleDirs) and bottle hooks run with `CX_ROOT`, `CX_BOTTLE` and `WINEPREFIX` set | Same |
|
||||
| CrossOver needs Rosetta 2; ARM64 build without it planned; CrossOver 27 requirements | **Unverified.** The CodeWeavers blog returned HTTP 403 to automated fetches, and the documentation pages above do not cover it. Read it in a browser for #348 | CodeWeavers blog (blocked) |
|
||||
| Rosetta after macOS 27 | **Sources conflict.** Apple developer news of 2026-09-01 says macOS 27 is the final release supporting Rosetta, with continued support for older unmaintained games that rely on Intel-based frameworks. News of 2026-09-09 says macOS 26 is the final release supporting Intel Macs and Rosetta, and 27 is Apple silicon only. Record both until Apple clarifies | developer.apple.com/news (ids w5ngl9k2, k1mtkt1k) |
|
||||
| D3DMetal license | **Not located.** The `apple/game-porting-toolkit` repository is Apache-2.0 and never mentions D3DMetal; D3DMetal ships in the separate Game Porting Toolkit download whose license was not read. Secondary sources describe evaluation-only use and restricted redistribution. Stays user-supplied and unbundled | github.com/apple/game-porting-toolkit, LICENSE |
|
||||
| DXMT license and scope | **Confirmed.** LGPL-2.1-or-later (copyright 2023-2026 Feifan He for CodeWeavers). README: Direct3D 11 and 10 on Metal using Wine. Wiki: macOS 14 or later, Apple silicon supported, Intel GPUs experimental and planned for removal once macOS 28 is released, Wine 8+ required, DXMT needs symbols from `winemac.so`. Cross builds need LLVM 15 and a mingw cross-compiler. Latest release v0.80 (2026-04-23) | github.com/3Shain/dxmt (LICENSE, README, wiki, docs/DEVELOPMENT.md) |
|
||||
| Wine conformance tests exist as standalone Windows programs | **Confirmed in tree.** `dlls/d3d11/tests/Makefile.in` defines a `d3d11.dll` test target from `d3d11.c`. The Wine conformance-test documentation page loaded (HTTP 200) but its requirements were not read; build and run requirements remain unverified | wine-mirror/wine |
|
||||
|
||||
## Dependencies observed
|
||||
|
||||
DXMT lists Meson 1.3+, LLVM 15, Xcode 16+ with the Metal toolchain and a Windows cross-compiler as build requirements. The Rust workspace requires `rustc` 1.100 (`rust-version` in `Cargo.toml`).
|
||||
|
||||
## Rust toolchain
|
||||
|
||||
The default `stable` on the reference machine was rustc 1.94.1, which cannot build the workspace. rustc 1.100.0 is the current official stable (channel manifest dated 2026-11-12, release 2026-11-09) and was already installed as toolchain `1.100.0-aarch64-apple-darwin`, so nothing was installed. Run `rustup run 1.100.0 cargo ...` or update `stable`. With it, `cargo test --locked -p xenora-loader --test generated_runtime_integration --test runtime_x15` passed (3 and 35 tests, 1 ignored). These native tests are not needed for hybrid development; the full workspace suite was not run.
|
||||
|
||||
## Not verified
|
||||
|
||||
CrossOver's CPU-translation internals and ARM64 plans, CrossOver 27 requirements, D3DMetal license text, `cxbottle`/`cxstart` command-line syntax, Wine conformance-test requirements, and whether D3D12 is usable under any backend on the installed version. These belong to #348, #350 and #354.
|
||||
@@ -0,0 +1,64 @@
|
||||
# Shader wave-operation failures under D3DMetal: investigation
|
||||
|
||||
Part of the shader integration PR (#394). It began as the separate investigation PR #392, whose content is carried here. Evidence class B (runs on one machine: Apple M4, 24 GiB, macOS 27.0, CrossOver 26.3.0.39832, default backend), not independently reproduced. The two failures are the ones recorded in `victory-shader-integration.md`. This note separates what is **established** from what is **a hypothesis**.
|
||||
|
||||
## Device capabilities (measured with BetterXen's own host, `workloads/d3d12-wave-probe/d3d12_run.c caps`)
|
||||
|
||||
| Field | Value |
|
||||
| --- | --- |
|
||||
| Adapter reported | "AMD Compatibility Mode", vendor 0x1002, 18,186 MB (D3DMetal's reported identity; the hardware is the M4) |
|
||||
| Device created at feature level | 12_1 |
|
||||
| Highest shader model | 6.6 |
|
||||
| `WaveOps` | supported |
|
||||
| `WaveLaneCountMin` / `Max` | 32 / 32 (waves are exactly 32 lanes; `TotalLaneCount` 1024) |
|
||||
| `DoublePrecisionFloatShaderOps` | **0** (no double-precision shader operations) |
|
||||
| `Int64ShaderOps` | supported |
|
||||
| Min-precision support | 0x2 (16-bit) |
|
||||
|
||||
## Failure 2: `a_sum_of_halves_where_lanes_have_left_is_the_consoles_tree_bit_for_bit` (established)
|
||||
|
||||
**Cause: a wrong test precondition (a subgroup-size assumption), not a translation error.**
|
||||
|
||||
1. The test lowers the program with `lowered_on(.., 64)`, "for a host of 64-lane waves (AMD)" per its own comment, then dispatches it on the default device without asking that device's wave width.
|
||||
2. The device's waves are exactly 32 lanes (table above). A program written for 64-lane waves reads lanes 32 to 63, which do not exist; the observed result was `0x0` against the expected tree `0x5914`.
|
||||
3. It is the only test in that file that lowers for 64 lanes (line 238); the sibling `a_sum_of_halves_over_the_wave_is_the_consoles_tree_bit_for_bit` lowers for 32 (line 160) and passes on the same device.
|
||||
4. Lowering this same program for a 32-lane host does not produce a wrong shader: the recompiler refuses it with `Unsupported: a wave sum of 16-bit floats where not every lane runs`. So the recompiler already behaves correctly; it states a limit instead of emitting something wrong.
|
||||
5. The expected value `0x5914` is derived on the host by integer 16-bit float arithmetic in the test itself, independent of the recompiler.
|
||||
|
||||
**Correction made (test, not recompiler):** `Host::wave_lane_count_max()` (new, from `D3D12_OPTIONS1`), and the test now checks the device first. On a device narrower than 64 lanes it asserts the refusal above and returns, printing why; on a 64-lane device it runs the original hardware comparison unchanged. After the change the test passes on this device, and what it verifies there is "the recompiler refuses a 64-lane-only program for a 32-lane host", not "the sum is correct on the GPU". The correct-sum claim stays **unverified on 32-lane hardware** and has not been run on a 64-lane device.
|
||||
|
||||
## Failure 1: `whole_wave_f64_sum_and_cvt_f32_f64` (established: unsupported double-precision operations in D3DMetal; fixed in the recompiler)
|
||||
|
||||
Observed: a Wave32 program with 4 launched threads, each contributing 1.25, should store 5.0; it stored `0x00000000`. It is a Wave32 program on a 32-lane device, so wave width was never the cause.
|
||||
|
||||
**Independent evidence** (Microsoft's DXC compiled original HLSL, BetterXen's own host dispatched it; expected values derived by hand before running; DXC v1.9.2609 digest-verified and run under CrossOver 26.3):
|
||||
|
||||
| Probe (`workloads/d3d12-wave-probe/hlsl/`) | Expected | Observed |
|
||||
| --- | --- | --- |
|
||||
| `lanes4`: wave size and lane index, 4 threads | `0x2000`..`0x2003` (wave of 32) | exactly that |
|
||||
| `sum_f32_4`: `WaveActiveSum(1.25f)`, 4 threads | `0x40a00000` in every lane | exactly that |
|
||||
| `add_f32_4`: control, run-time load, float add, store | `0x40000000`, `0` per thread | exactly that |
|
||||
| `add_f64_4`: a `double` add of run-time operands (DXIL contains `fadd fast double`) | low `0x00000000`, high `0x40000000` | **every dword still `0xDEADBEEF`: the shader wrote nothing** |
|
||||
| `sum_f64_4`: `WaveActiveSum` over a run-time `double` (DXIL `waveActiveOp.f64`) | low `0x00000000`, high `0x40140000` | **every dword still `0xDEADBEEF`: the shader wrote nothing** |
|
||||
|
||||
An earlier version of `add_f64_4` used constant operands: the compiler folded the addition to `splitDouble(2.0)` with no `fadd` (reviewer finding by atesahmet0, confirmed with `dxc -dumpbin`), so it did not show a double *addition* failing. The probes above take their operands from the buffer at run time and were rerun; the result is the same.
|
||||
|
||||
So wave operations, wave width and partial waves are fine on this device. Any shader that uses a `double` runs without effect: pipeline creation succeeds, the dispatch completes, and nothing is stored. That matches the capability record (`DoublePrecisionFloatShaderOps = 0`; Metal has no fp64). Upstream's test harness zero-fills its output buffer, which is why it saw `0` instead of the sentinel. **Conclusion:** the failure comes from unsupported double-precision operations in the backend, combined with the recompiler emitting a native `double` in one place (`active_f64_sum`) while using integer emulation everywhere else. It is not a mistranslation of the wave operation and not a wave-semantics problem.
|
||||
|
||||
**Fix (recompiler, `active_f64_sum`):** the existing integer fp64 add (`add_f64`, checked upstream against the CPU's doubles) is reused to build the console's sum, which is the balanced tree over the lanes in their order. Each lane adds its partner run's partial sum, read through `waveReadLaneAt` from the first lane of that run that is present (found with a ballot, as `half_sum_present` already does for 16-bit sums), `+0.0` where none is, which is what a lane outside EXEC adds on the console. No `double` type is emitted and the doubles feature flag is no longer set. The same code covers the console wave64 on two host waves of 32 (an integer add for the last step).
|
||||
|
||||
**Validation** (M4, CrossOver 26.3, default backend; one machine, not independently reproduced):
|
||||
- Whole suite under CrossOver: **232 passed, 0 failed, 3 ignored** (229 before the review's sampler tests) (was 224 passed, 2 failed). macOS: 179 + new tests pass (`cargo test -p victory-shader`).
|
||||
- New test `f64_wave_sums_match_the_cpu_tree_bit_for_bit`: 24 cases (1, 4, 20 and 32 launched threads; six values including ones that round: 0.1, 123456.789, a value one ulp above 1.0, -3.75e10, 1e-300), comparing all 64 bits with a CPU model of the balanced tree using the CPU's own f64 additions and `+0.0` for lanes that are not launched. All 24 match. The model is independent of the recompiler.
|
||||
- Negative controls: against the **original** lowering this GPU test fails (`got 0x0000000000000000, want 0x3ff4000000000000`) and the new `the_f64_wave_sum_is_lowered_without_native_doubles` test (the container's feature word must declare wave operations but not doubles) fails too; both pass with the fix.
|
||||
|
||||
**Limits:** (1) the tree order is what the recompiler's recognizer claims the console program computes (`wave::buddies`); this was not independently simulated from the DPP instructions, so bit-for-bit fidelity to the console for rounding values is only as good as that recognition. (2) The cost of the integer version was not measured and no performance claim is made. (3) Other fp64 wave operations (products, min/max) were not examined; only this one site emitted native doubles. (4) On a device with real fp64 the old native operation would work and is no longer used. (5) DXC is an external tool (University of Illinois/NCSA licence plus MIT components per its licence files), used only to compile probes; nothing from it is in the repository.
|
||||
|
||||
## Reproduce
|
||||
```sh
|
||||
scripts/hybrid/run-shader-gpu-tests.sh <llvm-mingw-dir> betterxen-test all # the runner script is in PR #395; or run the cross-built test executable with wine directly # expect: 0 failures with the fix in this branch (the vendored original has 2)
|
||||
# probes: compile hlsl/*.hlsl with DXC under CrossOver, then d3d12_run.exe run <file>.dxil 1 <dwords>
|
||||
# capabilities (needs the d3d12_run.exe built from workloads/d3d12-wave-probe/d3d12_run.c with llvm-mingw):
|
||||
# x86_64-w64-mingw32-clang -O2 -o d3d12_run.exe d3d12_run.c -ld3d12 -ldxgi -ldxguid
|
||||
# CrossOver bin/wine --bottle <bottle> ./d3d12_run.exe caps
|
||||
```
|
||||
@@ -11,8 +11,8 @@ in this checkout uses original fixtures and public specifications.
|
||||
| Project and audited snapshot | Type and observed evidence | Claimed-only behavior or provenance risk | Xenora work and original acceptance fixture | Priority and owner |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| [Xenora `3133d8e`](https://github.com/ranveersoni98/Xenora/tree/3133d8e) | Native Rust guest and shader research. X1–X4 fixtures and gfx1030 compiler in tree. | GPL-3.0-or-later. Console execution unsupported. | Re-run the guest and translated compute fixtures on ARM64. | Immediate, integration |
|
||||
| [Leonida `3faac55`](https://github.com/ItsNotRexed/Leonida/tree/3faac55) | Windows PE mapping, service shims and Vulkan proxy tests. | GPL-3 family and Xenora no-port rule. Commercial boot absent in audit. | Original PE startup and GPU resource contracts. | Later, CPU and Metal |
|
||||
| [Project ReCity `cb4840b`](https://github.com/pixl27/ProjectReCity/tree/cb4840b) | Windows/Vulkan implementation and PE tests. | GPL-3, Leonida-derived. Separate retail proof absent. | Same synthetic startup coverage as Leonida, no parallel benchmark. | Later, CPU |
|
||||
| [PE-Vulkan project `3faac55`](https://github.com/ItsNotRexed/Leonida/tree/3faac55) | Windows PE mapping, service shims and Vulkan proxy tests. | GPL-3 family and Xenora no-port rule. Commercial boot absent in audit. | Original PE startup and GPU resource contracts. | Later, CPU and Metal |
|
||||
| [Project ReCity `cb4840b`](https://github.com/pixl27/ProjectReCity/tree/cb4840b) | Windows/Vulkan implementation and PE tests. | GPL-3, PE-Vulkan project-derived. Separate retail proof absent. | Same synthetic startup coverage as PE-Vulkan project, no parallel benchmark. | Later, CPU |
|
||||
| [Xbox2Windows `6de5738`](https://github.com/R0Y00/Xbox2Windows/tree/6de5738) | Static recompilation tests for imports, CPU startup, TLS and GPU output. See `tests/cpu/startup_exe.cpp`. | MIT at repository level. Full title startup unverified. | Build a source-authored PE guest and test exact service results. | Immediate, CPU |
|
||||
| [americas-recomp `9bf220e`](https://github.com/realdody/americas-recomp/tree/9bf220e) | Audited main root had a license file. | GPL-2.0. Other branches uninspected. | No fixture justified by audited tree. | Deferred, research |
|
||||
| [6stars `480d9a4`](https://github.com/meetox80/6stars/tree/480d9a4) | Swift/Metal renderer and sampler mapping in `Sources/SixStars`. | No verified root license. Guest CPU execution unverified. | Original translated shader, validated resource range and known readback. | Immediate, Metal |
|
||||
@@ -63,7 +63,7 @@ in this checkout uses original fixtures and public specifications.
|
||||
services, hardware queues, formats and memory initialization need their
|
||||
own sources and tests. [Xbox GPU evidence](../research/xbox-gpu.md) ·
|
||||
[PE format](https://learn.microsoft.com/en-us/windows/win32/debug/pe-format)
|
||||
- GTA VI startup and execution remain unsupported. No authorized retail
|
||||
- Commercial-title startup and execution remain unsupported. No authorized retail
|
||||
executable was loaded. Actual title imports, startup ordering, resource
|
||||
bindings and pipeline behavior remain unverified. Relocation, thread-local
|
||||
storage, process and thread services, dynamic shader execution and
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
# Texture format and layout inventory
|
||||
|
||||
This page records which texture formats and memory layouts BetterXen handles today, and at which stage. It also records which gaps are worth closing and which are deferred. It is an inventory of the repository at the time of writing, built from the code and tests it links. It is not a support claim: a format listed here works only for the original synthetic fixtures named, on desktop specifications, and nothing here says anything about Xbox hardware or commercial titles.
|
||||
|
||||
## Stages
|
||||
|
||||
A format can be handled at one stage and missing at the next. The columns below keep them apart:
|
||||
|
||||
- **Container**: recognising a file or package format that holds textures (DDS, KTX and similar).
|
||||
- **CPU decode**: turning one compressed block into texels on the CPU, used as an independent reference.
|
||||
- **Layout**: converting between a stored memory layout and the row-major layout Metal expects.
|
||||
- **Native**: uploading to a Metal texture of that pixel format and reading it back on the GPU.
|
||||
- **Sampling**: a translated RDNA 2 image instruction reading the texture inside a shader.
|
||||
- **Host graphics API**: the D3D12-shaped `GraphicsContext` entry points, exercised by tests that call them directly from Rust. [The interface contract](../interfaces.md#guest-texture-binding-descriptor-tables) states they are not yet wired to guest imports, so this column is not guest evidence.
|
||||
- **Guest**: an original guest program (PE fixture) reaching the path through imported services, with a test that runs it.
|
||||
- **Specification**: the public sections the implementation and its expected values cite.
|
||||
|
||||
"—" means not implemented. "Rejected" means the input is refused with an error rather than handled.
|
||||
|
||||
## Formats
|
||||
|
||||
| Format | Container | CPU decode | Layout | Native | Sampling | Host graphics API | Guest | Specification |
|
||||
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
||||
| RGBA8 unorm | — | not needed | row-major mips, direct or budgeted staged upload ([`crates/metal/src/texture_pipeline.rs`](../../crates/metal/src/texture_pipeline.rs)) | upload and render target (`render_rgba8*`, [`crates/metal/tests/native/texture_sampling.rs`](../../crates/metal/tests/native/texture_sampling.rs)) | `image_sample_lz`, 2D, level 0 ([`crates/isa/src/lib.rs`](../../crates/isa/src/lib.rs), [`crates/metal/tests/native/translated_render.rs`](../../crates/metal/tests/native/translated_render.rs)) | one-level 2D SRV, `DXGI_FORMAT_R8G8B8A8_UNORM`, called from Rust ([`crates/loader/src/graphics.rs`](../../crates/loader/src/graphics.rs), [`crates/loader/tests/graphics_textures.rs`](../../crates/loader/tests/graphics_textures.rs)) | synthetic `xenora.dll` texture services (`texture_create`, `texture_update`, `frame_submit_textured`, `texture_destroy`) driven by the Gate 5 original PE fixture ([`crates/ffi/src/lib.rs`](../../crates/ffi/src/lib.rs), test `textured_pe_fixture_executes_dynamic_updates_and_retirement` in [`crates/ffi/tests/resources.rs`](../../crates/ffi/tests/resources.rs)); not through the descriptor-table API | [`MTLPixelFormat.rgba8Unorm`](https://developer.apple.com/documentation/metal/mtlpixelformat/rgba8unorm) |
|
||||
| BC1 | — | `decode_bc1` ([`crates/texture/src/lib.rs`](../../crates/texture/src/lib.rs)) | synthetic tiled layout, pitched uploads (`TiledBc1`, `Bc1Upload`) and per-subresource packed footprints (`BcTextureLayout`, `PackedBcUpload`) | `read_tiled_bc1`, `read_bc1_upload`, including packed footprints ([`crates/metal/tests/native/texture.rs`](../../crates/metal/tests/native/texture.rs), [`crates/metal/tests/packed_bc_upload.rs`](../../crates/metal/tests/packed_bc_upload.rs)) | sampled by the translated `image_sample_lz` pixel stage (`render_rgba8_sampled_bc1`, [`crates/metal/tests/native/translated_bc1.rs`](../../crates/metal/tests/native/translated_bc1.rs)) | one-level 2D SRV, `DXGI_FORMAT_BC1_UNORM`, called from Rust (same files as RGBA8) | — | [Khronos DFS 1.3, S3TC](https://registry.khronos.org/DataFormat/specs/1.3/dataformat.1.3.html#S3TC) (BC1 with and without alpha); [Microsoft, BC1](https://learn.microsoft.com/en-us/windows/win32/direct3d11/texture-block-compression-in-direct3d-11) |
|
||||
| BC2, BC3 | — | `decode_bc2`, `decode_bc3` ([`crates/texture/src/bc.rs`](../../crates/texture/src/bc.rs), [`crates/texture/tests/bc_formats.rs`](../../crates/texture/tests/bc_formats.rs)) | pitched upload (`BcAlphaUpload`) and packed footprints | `read_bc_alpha_upload`, including packed footprints ([`crates/metal/tests/native/texture_bc_alpha.rs`](../../crates/metal/tests/native/texture_bc_alpha.rs), [`crates/metal/tests/packed_bc_upload.rs`](../../crates/metal/tests/packed_bc_upload.rs)) | — | — | — | [Khronos DFS 1.3, S3TC BC2](https://registry.khronos.org/DataFormat/specs/1.3/dataformat.1.3.html#s3tc_bc2) and [BC3](https://registry.khronos.org/DataFormat/specs/1.3/dataformat.1.3.html#s3tc_bc3); [Microsoft, BC2 and BC3](https://learn.microsoft.com/en-us/windows/win32/direct3d11/texture-block-compression-in-direct3d-11) |
|
||||
| BC4, BC5 (unorm, snorm) | — | `decode_bc4_*`, `decode_bc5_*` ([`crates/texture/src/bc.rs`](../../crates/texture/src/bc.rs), [`crates/texture/tests/bc_formats.rs`](../../crates/texture/tests/bc_formats.rs)) | pitched upload (`BcChannelUpload`) and packed footprints | `read_bc_channel_upload`, including packed footprints ([`crates/metal/tests/native/texture_bc_channel.rs`](../../crates/metal/tests/native/texture_bc_channel.rs), [`crates/metal/tests/packed_bc_upload.rs`](../../crates/metal/tests/packed_bc_upload.rs)) | — | — | — | [Khronos DFS 1.3, RGTC BC4](https://registry.khronos.org/DataFormat/specs/1.3/dataformat.1.3.html#rgtc_bc4) and [BC5](https://registry.khronos.org/DataFormat/specs/1.3/dataformat.1.3.html#rgtc_bc5); [Microsoft, BC4 and BC5](https://learn.microsoft.com/en-us/windows/win32/direct3d11/texture-block-compression-in-direct3d-11) |
|
||||
| BC6H (ufloat, sfloat) | — | single-subset modes only; two-subset modes rejected ([`crates/texture/src/bc6h.rs`](../../crates/texture/src/bc6h.rs), [`crates/texture/tests/bc6h.rs`](../../crates/texture/tests/bc6h.rs), vectors [`crates/texture/tests/fixtures/bc6h_vectors.txt`](../../crates/texture/tests/fixtures/bc6h_vectors.txt)) | packed footprints only, 16-byte blocks ([`crates/texture/src/footprint.rs`](../../crates/texture/src/footprint.rs)) | — | — | — | — | [Khronos DFS 1.3, BPTC BC6H](https://registry.khronos.org/DataFormat/specs/1.3/dataformat.1.3.html#bptc_bc6h) (section 20.2, Tables 121 and 122); [Microsoft, BC6H Format](https://learn.microsoft.com/en-us/windows/win32/direct3d11/bc6h-format) |
|
||||
| BC7 unorm | — | all eight modes ([`crates/texture/src/bc7.rs`](../../crates/texture/src/bc7.rs), [`crates/texture/tests/bc7.rs`](../../crates/texture/tests/bc7.rs), vectors [`crates/texture/tests/fixtures/bc7_vectors.txt`](../../crates/texture/tests/fixtures/bc7_vectors.txt)) | packed footprints only, 16-byte blocks ([`crates/texture/src/footprint.rs`](../../crates/texture/src/footprint.rs)) | — | — | — | — | [Khronos DFS 1.3, BPTC BC7](https://registry.khronos.org/DataFormat/specs/1.3/dataformat.1.3.html#bptc_bc7) (section 20.1, Tables 109–120); [Microsoft, BC7 Format](https://learn.microsoft.com/en-us/windows/win32/direct3d11/bc7-format) |
|
||||
| BC7 sRGB | — | same bytes as BC7; the sRGB transfer function is outside the decoder | — | — | — | — | — | as BC7 |
|
||||
| Depth32Float | — | not needed | render attachment | `render_depth` with depth readback ([`crates/metal/tests/native/depth.rs`](../../crates/metal/tests/native/depth.rs)) | — | — | — | [`MTLPixelFormat.depth32Float`](https://developer.apple.com/documentation/metal/mtlpixelformat/depth32float) |
|
||||
|
||||
Sampler state is limited to nearest filtering and clamp-to-edge addressing ([`crates/texture/src/sampler.rs`](../../crates/texture/src/sampler.rs)). Other filter or address modes are rejected.
|
||||
|
||||
Native BC paths require `supportsBCTextureCompression`. A device without it fails as a capability error ([`crates/metal/src/compute.rs`](../../crates/metal/src/compute.rs)), separately from implementation failures.
|
||||
|
||||
Known source differences, recorded where they are implemented:
|
||||
|
||||
- **BC6H:** the Khronos text and Microsoft's sample code disagree on whether a negative value that rounds to zero keeps its sign (`-0.0` against `0.0`). `bc6h.rs` follows Khronos.
|
||||
- **BC1:** Apple's hardware rounds BC1's interpolated palette entries differently from the spec-exact decoder (171/84 against 170/85, see `CHANGELOG.md`). The sampled BC1 fixtures therefore use only endpoint colours.
|
||||
|
||||
## Layouts
|
||||
|
||||
| Layout | State | Where |
|
||||
| --- | --- | --- |
|
||||
| Row-major RGBA8 mips | implemented | [`crates/metal/src/texture_pipeline.rs`](../../crates/metal/src/texture_pipeline.rs) |
|
||||
| Budgeted staged RGBA8 upload | implemented | `MetalRgba8Texture::upload_staged`, [`crates/metal/src/texture_pipeline.rs`](../../crates/metal/src/texture_pipeline.rs) |
|
||||
| Pitched, layer-major BC uploads (one pitch for every mip, padded slices) | implemented for BC1–BC5 | [`crates/texture/src/upload.rs`](../../crates/texture/src/upload.rs) |
|
||||
| Per-subresource packed footprints for block-compressed mip chains (tight or aligned rows) | layout implemented for BC1–BC7; native readback covers BC1–BC5 (#241, PR #278) | [`crates/texture/src/footprint.rs`](../../crates/texture/src/footprint.rs), [`crates/texture/tests/bc_footprint.rs`](../../crates/texture/tests/bc_footprint.rs), [`crates/metal/tests/packed_bc_upload.rs`](../../crates/metal/tests/packed_bc_upload.rs) |
|
||||
| The synthetic 2×2-tile BC1 layout | implemented; defined by the project's fixtures, not by any console | [`crates/texture/src/lib.rs`](../../crates/texture/src/lib.rs) |
|
||||
| Desktop RDNA 2 surface tiling (swizzle modes) | unknown; not researched in this repository | — |
|
||||
| Console texture memory layouts | unknown; no public source reviewed | — |
|
||||
|
||||
## Public specifications
|
||||
|
||||
These are the primary sources the implementations above cite. The format rows already name them in their source files.
|
||||
|
||||
- [Khronos Data Format Specification 1.3](https://registry.khronos.org/DataFormat/specs/1.3/dataformat.1.3.html): the [S3TC](https://registry.khronos.org/DataFormat/specs/1.3/dataformat.1.3.html#S3TC) section (BC1–BC3), the [RGTC](https://registry.khronos.org/DataFormat/specs/1.3/dataformat.1.3.html#RGTC) section (BC4, BC5), section 20.1 ["BC7"](https://registry.khronos.org/DataFormat/specs/1.3/dataformat.1.3.html#bptc_bc7) and section 20.2 ["BC6H"](https://registry.khronos.org/DataFormat/specs/1.3/dataformat.1.3.html#bptc_bc6h).
|
||||
- Microsoft Direct3D documentation: ["Texture Block Compression in Direct3D 11"](https://learn.microsoft.com/en-us/windows/win32/direct3d11/texture-block-compression-in-direct3d-11), ["Block Compression (Direct3D 10)"](https://learn.microsoft.com/en-us/windows/win32/direct3d10/d3d10-graphics-programming-guide-resources-block-compression), ["BC6H Format"](https://learn.microsoft.com/en-us/windows/win32/direct3d11/bc6h-format) and ["BC7 Format"](https://learn.microsoft.com/en-us/windows/win32/direct3d11/bc7-format). These are used for the format definitions and DXGI format codes, not for console behaviour.
|
||||
- Apple Metal documentation: [`MTLPixelFormat`](https://developer.apple.com/documentation/metal/mtlpixelformat) and [`MTLDevice.supportsBCTextureCompression`](https://developer.apple.com/documentation/metal/mtldevice/supportsbctexturecompression), for the native pixel formats and the capability check.
|
||||
- AMD "RDNA 2" Instruction Set Architecture reference guide ([GPUOpen architecture documentation](https://gpuopen.com/amd-gpu-architecture-programming-documentation/)): MIMG instructions such as `image_sample_lz`, and the image resource and sampler descriptor formats. These cover desktop gfx1030 only. [Xbox GPU evidence](xbox-gpu.md) records why desktop statements do not transfer to the console without separate evidence.
|
||||
|
||||
## Unknowns
|
||||
|
||||
These are research questions, not missing features:
|
||||
|
||||
- **Console texture memory layouts and tiling.** No public specification has been reviewed. Desktop RDNA 2 tiling would be a separate research note and would still not establish console behaviour.
|
||||
- **Console resource descriptor formats.** Unknown. See [Xbox GPU evidence](xbox-gpu.md), which lists descriptor layout among the unresolved items.
|
||||
- **Asset and audio containers.** BetterXen parses none. The runtime's audio path accepts only raw PCM (`XENORA_AUDIO_FORMAT_PCM_S16LE` and `PCM_F32LE` in [`crates/ffi/include/xenora.h`](../../crates/ffi/include/xenora.h)). No original workload has shown a need for a container or a compressed audio format.
|
||||
|
||||
## Follow-ups
|
||||
|
||||
Ranked by how close each is to existing tested paths. The first item is already tracked; the others are proposals, so do not start them without an issue and a claim.
|
||||
|
||||
1. **BC6H two-subset modes and native BC6H/BC7.** Tracked in #208 (CPU decode, with an archived request to take it) and #209 (native upload and readback, whose imported proposal waits for maintainer approval). BC6H and BC7 already have packed footprints, so #209 can build on `PackedBcUpload`. Do not duplicate them.
|
||||
2. **Translated sampling of BC2–BC5.**
|
||||
- Fixture: original blocks with hand-chosen endpoints and indices, sampled by the existing `image_sample_lz` pixel stage.
|
||||
- Expected values: derived by hand from the Khronos tables. The `bc.rs` decoders must not produce them, so that the decoder and the reference stay independent.
|
||||
- Owners: Metal and Compiler.
|
||||
3. **Additional sampler state** (linear filtering, wrap and mirror addressing).
|
||||
- Fixture: a small original RGBA8 texture with distinct texels.
|
||||
- Expected values: from the public Direct3D and Metal sampling equations, computed in exact fractions.
|
||||
- Owners: Metal and Compiler.
|
||||
4. **Desktop RDNA 2 image resource descriptor decoding.** Needed before guest-supplied descriptors can select formats.
|
||||
- Fixture: original descriptor words for each supported format.
|
||||
- Expected values: from the AMD RDNA 2 ISA guide's descriptor tables.
|
||||
- Owner: ISA.
|
||||
- This does not cover console descriptors.
|
||||
|
||||
Deferred, with no demonstrated need:
|
||||
|
||||
- BC7 sRGB
|
||||
- DDS and KTX containers
|
||||
- ASTC and ETC (not part of the desktop Direct3D 12 BC set this target uses)
|
||||
- any compressed audio format
|
||||
- console tiling, until a public source exists
|
||||
@@ -0,0 +1,40 @@
|
||||
# Upstream research registry
|
||||
|
||||
Reviewed 2026-11-25. Every entry is **evidence class D** (non-normative official or project material) in the sense used by the issue templates and [claims.toml](../claims.toml): a review of public documentation and repository metadata. Nothing here was installed, built or run, so none of it is a statement that a project works for BetterXen's goals. Licenses are what the repository's own license file or GitHub's license detection reported; they still need the per-file check in the [reuse matrix](component-reuse-matrix.md) and are not legal advice. Pins are the default-branch head observed with `git ls-remote` on the review date. Independent re-derivation of this table is tracked in issue #363.
|
||||
|
||||
| Project | Source | Pin (head) | License as reported | Role for BetterXen | Findings |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| CrossOver (CodeWeavers) | [source page](https://www.codeweavers.com/crossover/source) | CrossOver 26.3.0 source listed | Proprietary product; page lists GPL/LGPL and other FOSS components it uses | Primary compatibility foundation (external install) | The page offers FOSS source for CrossOver 26.3.0 and lists Wine, Vkd3d, DXVK, MoltenVK, FAudio, SDL, LLVM, GMP and others. It says users should prefer each project's own home page. D3DMetal and Rosetta 2 are not in that list. What else is proprietary, the supported integration interfaces and redistribution terms are **unknown** (#348, #350, #354). |
|
||||
| Wine | [wine-mirror/wine](https://github.com/wine-mirror/wine) | `a79470449d03` | LGPL 2.1 (repository LICENSE and COPYING.LIB); GitHub reports NOASSERTION | Runtime APIs, via CrossOver | Upstream of CrossOver's runtime. CrossOver's exact delta from upstream is not reviewed. |
|
||||
| DXMT | [3Shain/dxmt](https://github.com/3Shain/dxmt) | `faa73e4a0686` | LGPL, version 2.1 or any later version (LICENSE text); copyright notice "for CodeWeavers" | Direct3D 11/10 to Metal under Wine; candidate backend | README: Metal-based D3D11/D3D10 layer for macOS using Wine. Status is on the project wiki (not reviewed). D3D12 is not claimed. |
|
||||
| DXVK | [doitsujin/dxvk](https://github.com/doitsujin/dxvk) | `57b2a7c1e87b` | zlib/libpng (LICENSE; GitHub: Zlib) | Direct3D to Vulkan; candidate backend only with MoltenVK | Listed among CrossOver's FOSS components. Whether it is used for any macOS path is unknown. |
|
||||
| VKD3D-Proton | [HansKristian-Work/vkd3d-proton](https://github.com/HansKristian-Work/vkd3d-proton) | `71cae091b065` | LGPL 2.1 (GitHub) | Direct3D 12 to Vulkan; candidate for evaluation | README requires Vulkan 1.3 and modern extensions. Whether MoltenVK exposes what it needs is **unknown**. CrossOver's page lists "Vkd3d" from source.winehq.org, which is the Wine vkd3d, not necessarily this fork. |
|
||||
| MoltenVK | [KhronosGroup/MoltenVK](https://github.com/KhronosGroup/MoltenVK) | `5189f8de86ec` | Apache-2.0 | Vulkan on Metal; candidate under DXVK/VKD3D-Proton | A Vulkan Portability layer, a subset of Vulkan. Listed among CrossOver's FOSS components. Last push observed 2026-10-13. |
|
||||
| FEX | [FEX-Emu/FEX](https://github.com/FEX-Emu/FEX) | `3ee25399232a` | MIT (GitHub) | x86/x86-64 emulation reference | README describes ARM64 **Linux**; tested distributions listed are Linux. No macOS host support is stated. Not a macOS option on this evidence; useful as design reference. |
|
||||
| VIctory | [Marvisak/VIctory](https://github.com/Marvisak/VIctory) | `13f91caee25f` | GPL-3.0 (GitHub); a prior local review found per-file notices (see `experiments/victory-native/licenses.md`, local, untracked) | Discovery reference only | Described as an attempt at running one commercial game on PC. Its inputs are an Xbox Series build of that game. PortWatch describes the efforts it tracks as targeting a "leaked Xbox Series build". |
|
||||
| VIctory-macOS | [pragyaangaur/VIctory-macOS](https://github.com/pragyaangaur/VIctory-macOS) | `485b230ef596` | GPL-3.0 (GitHub) | Discovery reference only | A macOS port of VIctory using Rosetta, CrossOver Wine and D3DMetal per its README (also noted in [portwatch-native-macos.md](portwatch-native-macos.md)). Same input concern. Its test and "works" claims are self-reported and not verified here. The repository has no parent fork, so the "canonical upstream" is VIctory. |
|
||||
| PortWatch VI | [portwatch-vi.xyz](https://portwatch-vi.xyz/), [4lwayz/portwatch-vi](https://github.com/4lwayz/portwatch-vi) | `ed00263cc0c9` | NOASSERTION | Project discovery reference | A tracker of community efforts; progress figures are editorial, with self-reported claims labelled. Not engineering evidence; flagged and ignored queues are not endorsed. |
|
||||
|
||||
## victory-shader import under review
|
||||
|
||||
`skakwy/victory-mac` `crates/victory-shader` at `22b3f8e45a59` is proposed for vendoring in PR #394. **Not approved.** See the [per-file provenance and licence review](victory-shader-provenance.md); the provenance decision below stands until a maintainer changes it.
|
||||
|
||||
## Additional candidates found by search (not reviewed)
|
||||
|
||||
Found by GitHub search on 2026-11-25. Only repository metadata was read; none was evaluated, installed or run, and none is a recommendation. Licenses are what GitHub reported.
|
||||
|
||||
| Project | Source | Pin (head) | License as reported | Why listed |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| llvm-mingw | [mstorsjo/llvm-mingw](https://github.com/mstorsjo/llvm-mingw) | `903f4cf7faa2` | GitHub: other (read LICENSE before use) | Cross-compiler candidate for building original Windows test programs (#364). README says its compilers come in x86_64 and aarch64 builds, built on Ubuntu; availability and behaviour on a macOS host are **unknown**. |
|
||||
| Sikarugir | [Sikarugir-App/Sikarugir](https://github.com/Sikarugir-App/Sikarugir) | `5446b7d18072` | not reported | Wine-wrapper project (successor to Wineskin per its README, macOS 14.6+): a reference for bottle and wrapper management. |
|
||||
| macOS Wine builds | [Gcenx/macOS_Wine_builds](https://github.com/Gcenx/macOS_Wine_builds) | `72f8915f2d01` | not reported | Community Wine builds for macOS: possible Wine reference builds. Provenance of the binaries is unreviewed. |
|
||||
| Mythic | [MythicApp/Mythic](https://github.com/MythicApp/Mythic) | `754223978e61` | GPL-3.0 | Open-source macOS launcher that runs Windows games through Wine: an architecture reference for configuration and launching. |
|
||||
| Playdock | [Jasonilization/Playdock](https://github.com/Jasonilization/Playdock) | `f58b8ef7fb70` | MIT | Describes itself as a free alternative to CrossOver; unreviewed. |
|
||||
|
||||
## Not yet researched
|
||||
|
||||
Apple's Game Porting Toolkit documentation and license (D3DMetal's actual terms), Rosetta 2's support lifetime, CrossOver's documented command-line interfaces and bottle management, and other established projects. These are issues #349, #350 and #354; nothing is claimed about them here.
|
||||
|
||||
## Provenance decision
|
||||
|
||||
VIctory-family projects are not adopted. Their GPL grants apply to their own source; they do not establish that the material they were built for is authorized. The registry records them for architecture ideas visible in public documentation (cache identity, upload visibility, test structure). No code, shader corpus, asset or tooling from them enters BetterXen without a recorded per-file review, and anything game-specific or decryption-related is excluded.
|
||||
@@ -0,0 +1,53 @@
|
||||
# victory-shader integration (GFX10 to DXIL recompiler)
|
||||
|
||||
Evidence: classes noted per row. Everything ran on one machine (Apple M4, 24 GiB, macOS 27.0, CrossOver 26.3.0.39832, bottle `betterxen-test`, default backend) and has **not been independently reproduced**. BetterXen's runs used no game files or leaked material. **The vendored code itself was developed against one commercial title's shaders** and is not approved for merge: see [victory-shader-provenance.md](victory-shader-provenance.md).
|
||||
|
||||
## What was integrated
|
||||
|
||||
`crates/victory-shader` is a snapshot of `crates/victory-shader/` from skakwy's [victory-mac](https://github.com/skakwy/victory-mac) (head `22b3f8e45a59`). It translates GFX10 (RDNA 2) machine code to PC DXIL, shader model 6.6, in pure Rust: a GFX10 decoder with an SP3 printer, control-flow structurizer, register spilling, wave emulation, fp64 by integer operations, its own LLVM 3.7 bitcode writer and DXIL container writer. About 43,500 lines against 4,022 in BetterXen's native `xenora-shader`. The native RDNA-to-Metal compiler is untouched and still paused; the two are different targets (DXIL for D3D12 under CrossOver versus MSL) and nothing was replaced. Provenance, authors, licences and the 19 changed lines are in [`crates/victory-shader/UPSTREAM.md`](../../crates/victory-shader/UPSTREAM.md). Licensing: GPL-3.0 upstream, GPL-3.0-or-later here, one MIT Mesa-derived table with its notice kept.
|
||||
|
||||
Left out on purpose: the upstream repository's loader, HLE, GPU runtime and game-specific code (one console title's runtime) and their provenance questions; the console shader containers the crate can also parse were not exercised, because no authorized container exists.
|
||||
|
||||
## How it connects to BetterXen
|
||||
|
||||
- `emit::translate_native` (BetterXen addition, `emit/betterxen.rs`): the crate only accepted shaders inside console containers; this entry point takes a compute program as machine code plus root layout, which is what BetterXen has.
|
||||
- `emit/betterxen_tests.rs`: BetterXen's own synthetic gfx1030 Wave32 fixtures (`fixtures/rdna2/*.bin`, original, assembled with LLVM's `llvm-mc`) are wrapped in a short descriptor-table prologue, translated to DXIL, and compared with the expected words in `fixtures/manifest.toml`. Those expectations were derived by hand in the manifest and are checked by BetterXen's independent reference; none comes from the recompiler. Six of the eleven manifest fixtures have input and expected words (add, float-exact, bitwise-branch, or, shifts, ashr); the five graphics-stage fixtures (`x9-*`) have none and are not bridged.
|
||||
- Running the cross-built Windows test executable under CrossOver is done by `scripts/hybrid/run-shader-gpu-tests.sh` through `betterxen-hybrid run`. Those live in separate pull requests (the hybrid runner, and the script on top of it); the GPU results below were produced with them.
|
||||
|
||||
## Results
|
||||
|
||||
| Check | Result | Notes |
|
||||
| --- | --- | --- |
|
||||
| Native build, aarch64-apple-darwin, Rust 1.100.0 | builds; fmt, `clippy -D warnings` clean | upstream also builds for Windows targets |
|
||||
| Upstream tests that run on macOS (CPU-side: decode, structurize, lower, emit) | 177 passed, 2 ignored | The Windows-only GPU modules are not compiled here |
|
||||
| BetterXen fixtures to DXIL on macOS | 6 of 6 translate to a DXBC container | `translate_native` |
|
||||
| BetterXen fixtures run on the GPU: D3D12 under CrossOver 26.3 (D3DMetal) | **6 of 6 output words match the manifest** | via `betterxen-hybrid run`, 2.3 to 2.6 s including bottle start; the GPU is a D3D12 device with shader model 6.6 as upstream's host layer requires |
|
||||
| Negative control | a flipped expected word is rejected; the output is not the zeroed buffer | `a_wrong_expectation_is_detected` |
|
||||
| Same GPU tests on DXMT, DXVK and wined3d (no D3D12) | fail with "no SM 6.6 D3D12 hardware device: not verified" | confirms they cannot pass by skipping; upstream's own tests print "skipped" instead |
|
||||
| Whole upstream suite, vendored unchanged, under CrossOver (default backend), 229 tests | 224 passed, **2 failed**, 3 ignored | the two failures are explained in `shader-wave-semantics.md` |
|
||||
| Whole suite with the fixes in this PR, under CrossOver | **232 tests: 229 passed, 0 failed, 3 ignored** | the 3 additional tests are BetterXen's f64 tests; see below |
|
||||
| Upstream suite on a backend without D3D12 (DXMT) | 201 passed, 25 failed, 3 ignored | see the classification below |
|
||||
|
||||
The two failures are `whole_wave_f64_sum_and_cvt_f32_f64` (a wave-wide fp64 sum returned 0, expected `0x40a00000`) and `a_sum_of_halves_where_lanes_have_left_is_the_consoles_tree_bit_for_bit` (64 lanes: got 0, expected `0x5914`). Both are cross-lane wave reductions of the console's 64-lane waves. Hypothesis, **not verified**: the host's waves are 32 lanes wide (Apple GPU) and D3DMetal does not honour the required wave size or wave operation semantics. The cause, and whether upstream passes them on a Windows GPU, were not investigated.
|
||||
|
||||
## Which tests actually executed on the GPU
|
||||
|
||||
The harness reports a test as passed whether or not it touched the GPU; many return early when no device is available. Each test was therefore run on the default backend (D3D12 via D3DMetal) and on DXMT (no D3D12), with libtest JSON output including each test's own printed output (`--format json --show-output`). A test counts as GPU-dependent if its outcome changes without D3D12 or it prints "no SM 6.6 hardware device; skipped" there. Final content of this PR (232 tests: 225 upstream, 7 BetterXen):
|
||||
|
||||
| Group | Tests |
|
||||
| --- | --- |
|
||||
| Executed on the D3D12 hardware device and passed | **31** (26 of them fail without D3D12; 5 pass only by skipping there) |
|
||||
| Executed on the D3D12 hardware device and failed | **0** |
|
||||
| Not GPU-dependent: CPU-side (decode, structurize, lower, emit, container) or ignored | 201, including 3 ignored |
|
||||
| Total | 232 |
|
||||
|
||||
For the vendored upstream code before the fixes in this PR the same method gave 229 tests: 32 GPU-dependent, 30 passed on the device and 2 failed (they "passed" without D3D12 by skipping, which hid the failures), see `shader-wave-semantics.md`. Three of the 31 are BetterXen's GPU tests (fixtures, negative control, bit-exact f64 sums). Counts are by name from the JSON events and are exact for this binary and machine. "WARP" skips (the software adapter, which Wine does not provide) and "no `dxil.dll`" skips are not GPU runs and are not counted as such.
|
||||
|
||||
## Limits
|
||||
|
||||
- Microsoft's `dxil.dll` is not present, so upstream's DXIL validation is skipped in six tests. DXIL is accepted unsigned by D3DMetal under Wine (upstream's code states this; the passing runs agree).
|
||||
- Many upstream tests also run on WARP (a software adapter) and print "no SM 6.6 warp device; skipped" because Wine has none. Those skips are expected and are not counted as GPU runs.
|
||||
- Only compute fixtures with one input and one output buffer are bridged. Graphics stages, textures, samplers, wave64 and LDS programs are exercised only by upstream's own tests.
|
||||
- No performance was measured: a six-fixture dispatch says nothing about speed or about real shaders.
|
||||
- Correctness is shown for these original fixtures, not for console shaders; the crate's real inputs (console shader containers) were not used.
|
||||
- Upstream is a snapshot; later upstream fixes must be merged by hand against the pinned commit.
|
||||
@@ -0,0 +1,66 @@
|
||||
# victory-shader: per-file provenance and licence review
|
||||
|
||||
**Status: NOT APPROVED. A maintainer decision is required before PR #394 can merge.** This is the review the engineering rules require for VIctory-family code. It records facts; it does not grant approval, and its author is the person who proposed the import, so it is not an independent review.
|
||||
|
||||
Upstream: <https://github.com/skakwy/victory-mac>, revision `22b3f8e45a59f7d11fef7718988c58d0b3f1d0f9`. Method: every tracked file of `crates/victory-shader/` at that revision; authors from `git shortlog`; licence from the repository `LICENSE` and a search of each file for other notices; title references by searching for shader names of the form `module:CS_Name` and the words title, titles, game, games. The search finds references, not every dependence: a file without one may still have been developed against the same title.
|
||||
|
||||
## Findings
|
||||
|
||||
1. **Licence:** GPL-3.0, compatible with BetterXen's GPL-3.0-or-later. One third-party notice (Mesa-derived opcode names, MIT, Valve) in `src/gfx10/opcodes.rs`, kept. Some comments cite Mesa behaviour and LLVM definitions. skakwy and the VIctory-macOS maintainer authorized reuse of their own contributions (relayed by the maintainer); other authors' lines rest on the repository licence.
|
||||
2. **The crate was developed against one commercial title's shaders.** 17 of 36 files refer to "the title" or "the game"; comments describe that title's programs, layouts and structures, and four places cite its shaders by name (`wave64_tests.rs`, `wave.rs`, `own_bits.rs`). The upstream project's stated purpose is to run that title's Xbox Series build; this registry and PortWatch record that build as leaked.
|
||||
3. **What is not in the crate:** a search found no shader binaries, shader dumps, game assets, keys or decryption code. The references are in comments, test descriptions and handling of shader constructs.
|
||||
4. **Earlier statements that were wrong:** the integration record and PR descriptions said the crate had nothing game-specific. That claim came from searching only for the game's and publisher's names. It is withdrawn.
|
||||
|
||||
## How this meets the engineering rules (`AGENTS.md`)
|
||||
|
||||
| Rule | Assessment |
|
||||
| --- | --- |
|
||||
| "Projects whose stated purpose depends on leaked or unauthorized builds ... are discovery references at documentation level; adopt nothing from them without a per-file provenance and license review recorded in the registry." | This file is that record. Recording it does not by itself approve adoption. |
|
||||
| "Game-specific, asset-specific and decryption-related code is never adopted." | Handling written for and documented against one title's shaders is present in at least some files. Whether that makes a file "game-specific code" is the decision to make; it is a general GFX10 recompiler in structure, with title-driven behaviour inside it. |
|
||||
| "Provenance first: exclude anything derived from leaked proprietary material or unauthorized software." | Layouts "as observed in shipped titles" (`native.rs`) and behaviour tuned to the title's programs are plausibly derived from that material. |
|
||||
| "Never copy, port, translate or adapt source from emulator projects built for leaked or unauthorized material." | Read plainly, this applies to this import. Author permission does not change it. |
|
||||
|
||||
**Reviewer's recommendation to the maintainer:** under the rules as written, do not merge the import. Either decline it (keep the crate as a documentation-level reference; BetterXen's own fixtures, probes and findings stand on their own), or change the rule explicitly in `AGENTS.md` with the legal question considered, and then decide file by file. This is not legal advice.
|
||||
|
||||
## Per-file record
|
||||
|
||||
| File (under `crates/victory-shader/`) | Lines | Upstream authors (commits) | Licence and third-party notes | Shader names of a title | Lines saying title/game |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| `Cargo.toml` | 40 | Marvis (2), fxceless (1) | GPL-3.0 (repository licence) | - | - |
|
||||
| `src/bvh.rs` | 696 | fxceless (2) | GPL-3.0 (repository licence) | - | 5 |
|
||||
| `src/dxbc.rs` | 181 | Marvis (2) | GPL-3.0 (repository licence) | - | - |
|
||||
| `src/dxil.rs` | 211 | Marvis (1) | GPL-3.0 (repository licence); cites LLVM | - | - |
|
||||
| `src/emit/bitcode.rs` | 1240 | Marvis (3), fxceless (2), Lyrnc (1) +2 more | GPL-3.0 (repository licence); cites LLVM | - | - |
|
||||
| `src/emit/bitcode/census.rs` | 174 | fxceless (1) | GPL-3.0 (repository licence) | - | - |
|
||||
| `src/emit/bitcode/opt.rs` | 2140 | armin (1), fxceless (1) | GPL-3.0 (repository licence) | - | 1 |
|
||||
| `src/emit/container.rs` | 419 | Duff (1), Marvis (1), fxceless (1) +1 more | GPL-3.0 (repository licence) | - | - |
|
||||
| `src/emit/diff_tests.rs` | 1287 | Marvis (3), fxceless (1) | GPL-3.0 (repository licence) | - | 5 |
|
||||
| `src/emit/f64.rs` | 409 | skakwy (1) | GPL-3.0 (repository licence) | - | - |
|
||||
| `src/emit/host.rs` | 1472 | fxceless (3), Marvis (1), skakwy (1) | GPL-3.0 (repository licence) | - | - |
|
||||
| `src/emit/intersect.rs` | 557 | fxceless (1) | GPL-3.0 (repository licence) | - | 12 |
|
||||
| `src/emit/intersect_tests.rs` | 690 | fxceless (1) | GPL-3.0 (repository licence) | - | 15 |
|
||||
| `src/emit/lower.rs` | 12268 | Marvis (21), skakwy (9), fxceless (6) +23 more | GPL-3.0 (repository licence); comment cites Mesa behaviour; cites LLVM | - | 18 |
|
||||
| `src/emit/mod.rs` | 1755 | Marvis (7), fxceless (6), skakwy (4) +8 more | GPL-3.0 (repository licence) | - | 16 |
|
||||
| `src/emit/own_bits.rs` | 914 | fxceless (1) | GPL-3.0 (repository licence) | 1 | 3 |
|
||||
| `src/emit/rect.rs` | 484 | fxceless (2) | GPL-3.0 (repository licence) | - | 2 |
|
||||
| `src/emit/sampler.rs` | 125 | Marvis (1) | GPL-3.0 (repository licence) | - | 1 |
|
||||
| `src/emit/shader.rs` | 908 | fxceless (4), Claude (1), Duff (1) +4 more | GPL-3.0 (repository licence) | - | 8 |
|
||||
| `src/emit/threading.rs` | 218 | fxceless (1) | GPL-3.0 (repository licence) | - | - |
|
||||
| `src/emit/validator.rs` | 221 | Marvis (1), lameloball2813-ui (1) | GPL-3.0 (repository licence) | - | - |
|
||||
| `src/emit/valu_tests.rs` | 1624 | Marvis (6), r4. (5), fxceless (4) +6 more | GPL-3.0 (repository licence) | - | - |
|
||||
| `src/emit/waterfall_tests.rs` | 435 | r4. (3), Marvis (1), Noname0202 (1) +1 more | GPL-3.0 (repository licence) | - | - |
|
||||
| `src/emit/wave.rs` | 1228 | fxceless (3), skakwy (2), AscilCH (1) +1 more | GPL-3.0 (repository licence) | 1 | - |
|
||||
| `src/emit/wave64_tests.rs` | 532 | fxceless (1), triippywhale (1) | GPL-3.0 (repository licence) | 2 | - |
|
||||
| `src/gfx10/fields.rs` | 815 | Marvis (1), fxceless (1) | GPL-3.0 (repository licence) | - | - |
|
||||
| `src/gfx10/mod.rs` | 496 | Marvis (3), tedin7 (1) | GPL-3.0 (repository licence) | - | - |
|
||||
| `src/gfx10/opcodes.rs` | 1333 | Duff (1), Marvis (1) | GPL-3.0 (repository licence); Mesa-derived, MIT (Valve), notice in header; cites LLVM | - | - |
|
||||
| `src/gfx10/sp3.rs` | 784 | Marvis (1) | GPL-3.0 (repository licence) | - | - |
|
||||
| `src/io.rs` | 826 | Marvis (1), fxceless (1), local (1) | GPL-3.0 (repository licence) | - | - |
|
||||
| `src/ir.rs` | 1791 | fxceless (4), Marvis (2), Yaekai (1) +1 more | GPL-3.0 (repository licence) | - | 1 |
|
||||
| `src/lib.rs` | 38 | Marvis (3), fxceless (1) | GPL-3.0 (repository licence); cites LLVM | - | - |
|
||||
| `src/native.rs` | 1103 | Marvis (4), fxceless (1), local (1) | GPL-3.0 (repository licence) | - | 1 |
|
||||
| `src/resource.rs` | 3848 | Claude (3), fxceless (3), Marvis (2) +2 more | GPL-3.0 (repository licence); cites LLVM | - | 10 |
|
||||
| `src/spill.rs` | 380 | fxceless (2) | GPL-3.0 (repository licence) | - | 1 |
|
||||
| `src/structure.rs` | 1899 | Marvis (2), fxceless (2), DexNom (1) +2 more | GPL-3.0 (repository licence) | - | - |
|
||||
|
||||
BetterXen's additions (`src/emit/betterxen.rs`, `src/emit/betterxen_tests.rs`, `Cargo.toml`, `UPSTREAM.md`) are original, GPL-3.0-or-later. Functional edits to upstream files are listed in `crates/victory-shader/UPSTREAM.md`.
|
||||
@@ -0,0 +1,96 @@
|
||||
# BetterXen roadmap
|
||||
|
||||
**This is the single authoritative active roadmap.** GitHub Issues hold the current phase's tasks, the open milestone names the current phase, and this file explains strategy, phase order, parked work and completion criteria. If another document disagrees, this one governs, except [ADR 0005](adr/0005-crossover-hybrid-direction.md) for the decision itself.
|
||||
|
||||
## Direction
|
||||
|
||||
BetterXen's active direction is a **CrossOver-based hybrid architecture for Apple Silicon**. CrossOver is the intended compatibility foundation and is an **externally installed dependency**, never bundled or redistributed. BetterXen's own work is the layer around it: integration, configuration, diagnostics, reproducible testing, benchmarking and measured optimization. The independent native implementation (x86-64 decoder, ARM64 translator, runtime, gfx1030 shader compiler, Metal backend) is **preserved but paused**; see the [native roadmap](research/native-roadmap.md) and the [native issue archive](research/native-issue-archive.md).
|
||||
|
||||
This is the intended architecture, **not a verified Xbox compatibility stack**. Nothing in this repository demonstrates that CrossOver, Rosetta 2 or D3DMetal run any Xbox title, and CrossOver is not assumed to provide Xbox runtime compatibility. All workloads must be independently authored, publicly licensed or otherwise authorized.
|
||||
|
||||
```
|
||||
BetterXen: integration, configuration, diagnostics, benchmarking, optimization
|
||||
|
|
||||
CrossOver (external): Wine-based runtime APIs | Rosetta 2 CPU translation | D3DMetal / DXMT graphics
|
||||
|
|
||||
Apple Silicon: ARM64, Metal, unified memory
|
||||
```
|
||||
|
||||
Priorities, in order: practical compatibility, functional integrated execution, rendering correctness, stability, performance, Apple Silicon-specific optimization, long-term independence. Reuse before reinvention; measure before optimizing; evidence before claims.
|
||||
|
||||
## Rolling planning
|
||||
|
||||
Only the current phase has a GitHub milestone and detailed issues. Later phases are described below and become milestones and issues only when the evidence from the current phase makes their requirements clear. Work that was specified early but depends on unverified assumptions is listed under [Parked ideas](#parked-ideas) with its closed issue, so it can be reopened rather than rewritten. Phase numbers are provisional. The earlier eight-phase plan (H0 to H7) is archived in [archive/hybrid-phases-h0-h7.md](archive/hybrid-phases-h0-h7.md).
|
||||
|
||||
## Engineering rules
|
||||
|
||||
[AGENTS.md](../AGENTS.md) (`CLAUDE.md` is a symlink to it) was rewritten to permit CrossOver, Wine-based infrastructure, Rosetta 2 and D3DMetal subject to licensing; ADR 0005 records the decision. The honesty, verification, provenance and clean-room rules are unchanged. Both are on the local branch `planning/hybrid-first-transition` and await maintainer review; nothing has been pushed.
|
||||
|
||||
## How progress is reported
|
||||
|
||||
Phase status is one of: Not started, Researching, In development, Blocked, In validation, Verified complete, Retired. A phase is Verified complete only with the evidence its completion criteria name. Progress is not derived from commits, lines of code, closed issues, instruction counts or passing isolated fixtures. No phase is currently Verified complete.
|
||||
|
||||
## Phase 1 — CrossOver Research, Feasibility and Baseline (active)
|
||||
|
||||
**Status:** Researching. **Milestone:** `Phase 1 - CrossOver Research, Feasibility and Baseline`.
|
||||
|
||||
**Objective:** Establish what the installed CrossOver version actually provides, which interfaces are supported, what may be reused or redistributed, and a reproducible baseline on authorized workloads.
|
||||
|
||||
**Completion criteria** (all required, each with recorded evidence):
|
||||
|
||||
1. CrossOver architecture, platform support, CPU translation and graphics backends documented from primary sources, with unknowns listed ([#348](https://github.com/MacosPorters/betterxen/issues/348)).
|
||||
2. Supported integration interfaces separated from undocumented behavior ([#350](https://github.com/MacosPorters/betterxen/issues/350)).
|
||||
3. Licensing and redistribution boundaries documented ([#354](https://github.com/MacosPorters/betterxen/issues/354)); the registry independently re-derived ([#363](https://github.com/MacosPorters/betterxen/issues/363)).
|
||||
4. A reproducible way to build original Windows test programs ([#364](https://github.com/MacosPorters/betterxen/issues/364)) and original graphics workloads with self-verifying output ([#365](https://github.com/MacosPorters/betterxen/issues/365)).
|
||||
5. Workload set, measurement protocol and host receipt defined ([#353](https://github.com/MacosPorters/betterxen/issues/353)) and a frame-time capture method ([#145](https://github.com/MacosPorters/betterxen/issues/145)).
|
||||
6. A reproducible CrossOver environment and a recorded baseline of CPU, GPU, memory and stability, reproduced by a second contributor ([#355](https://github.com/MacosPorters/betterxen/issues/355)).
|
||||
7. BetterXen's responsibilities versus CrossOver's recorded in an ADR a maintainer accepts ([#351](https://github.com/MacosPorters/betterxen/issues/351)).
|
||||
|
||||
**Open issues:** #145, #348, #350, #351, #353, #354, #355, #363, #364, #365, plus #346 (project board, needs the GitHub `project` token scope; does not block engineering).
|
||||
|
||||
**Known risks:** CrossOver is proprietary, so bundling or modifying may be prohibited; integration interfaces may be undocumented (see below); Xbox titles may not run at all.
|
||||
|
||||
### Critical path
|
||||
|
||||
1. Desk research needs nothing installed and can start now: #348, #350, #354, #364 (build only), #353.
|
||||
2. #363 re-derives the registry independently of its author.
|
||||
3. #365 needs #364 and #353.
|
||||
4. #355 needs #364, #353 and the interface findings of #350.
|
||||
5. #351 needs #348, #350, #354 and #355.
|
||||
|
||||
Hard dependencies are recorded as GitHub blocked-by relationships; everything else is preferred order.
|
||||
|
||||
### Verified and unverified (2026-11-25)
|
||||
|
||||
Details and sources are in [primary-source-verification-2026-11-25.md](research/primary-source-verification-2026-11-25.md). In short: CodeWeavers' public documentation names the backends Auto, D3DMetal, DXMT, DXVK and Wine, but **`CX_GRAPHICS_BACKEND` and `cxbottle.conf` are not documented there and must not be treated as a supported interface** until #350 resolves it. Apple's two September 2026 developer news items about Rosetta disagree with each other. D3DMetal's license text was not located; it stays user-supplied and unbundled.
|
||||
|
||||
## Provisional later phases (no milestone yet)
|
||||
|
||||
| Phase | Purpose | Starts when |
|
||||
| --- | --- | --- |
|
||||
| 2. Integration foundation | Only the tooling Phase 1 shows is missing: environment inspection, workload runner and run records, output-path policy | Phase 1 criteria 2 and 6 are met |
|
||||
| 3. Compatibility validation | Run authorized workloads and upstream conformance tests, record reproducible failures | A runner exists and a baseline is recorded |
|
||||
| 4. Graphics and performance | Backend comparison and measured bottleneck work; no improvement promised before measurement | Phase 3 shows what to measure |
|
||||
| 5. Stability and maturity | Soak, memory pressure, thermals, version matrices, dependency maintenance, upstream contributions | Phase 4 results exist |
|
||||
|
||||
Independent native reassessment is separate and deferred: it needs an explicit maintainer decision.
|
||||
|
||||
## Parked ideas
|
||||
|
||||
Specified in detail on 2026-11-25, then closed as premature for Phase 1 with the text preserved. Reopen when the stated prerequisite is met. Parking is not rejection.
|
||||
|
||||
| Issue | Subject | Reopen when |
|
||||
| --- | --- | --- |
|
||||
| [#366](https://github.com/MacosPorters/betterxen/issues/366) | Read-only CrossOver inspection command | The #353 receipt script proves insufficient |
|
||||
| [#367](https://github.com/MacosPorters/betterxen/issues/367) (absorbs #368) | Workload runner and run records | Phase 1 finds #350 supports scripted launches (Phase 2) |
|
||||
| [#257](https://github.com/MacosPorters/betterxen/issues/257) | Output-path policy for exports and caches | A tool that writes exports exists (Phase 2) |
|
||||
| [#369](https://github.com/MacosPorters/betterxen/issues/369) | Upstream Wine conformance subset in a bottle | Runner and baseline exist (Phase 3) |
|
||||
| [#370](https://github.com/MacosPorters/betterxen/issues/370) | Backend comparison on equal workloads | Baseline and workloads exist (Phase 4) |
|
||||
| [#371](https://github.com/MacosPorters/betterxen/issues/371), [#372](https://github.com/MacosPorters/betterxen/issues/372) | Shader-compile latency; Metal System Trace recipe | Baseline names a bottleneck (Phase 4) |
|
||||
| [#373](https://github.com/MacosPorters/betterxen/issues/373), [#204](https://github.com/MacosPorters/betterxen/issues/204) | Soak and thermal drift; memory-pressure benchmark | Workloads and baseline exist (Phase 5) |
|
||||
| [#374](https://github.com/MacosPorters/betterxen/issues/374) | Re-baseline on a Rosetta-free CrossOver build | Such a build ships (Phase 5); facts folded into #348 |
|
||||
| #173, #174, #219 | Contributor-workflow administration | A concrete need appears |
|
||||
|
||||
## Native work
|
||||
|
||||
About 110 native issues were consolidated. All are closed with their text, comments and attribution intact except four with an assignee and an open pull request (#247, #291, #307, #313), which stay open until their authors decide. See the [native issue archive](research/native-issue-archive.md). Source code, tests, benchmarks and history are untouched.
|
||||
@@ -1,9 +1,10 @@
|
||||
# CPU test runtime and shard selection
|
||||
# CPU test runtime, shards and coverage map
|
||||
|
||||
This page records what the CPU test gate costs and describes
|
||||
`scripts/cpu-tests.sh`, which splits that gate into deterministic shards. The
|
||||
shards are a convenience for local iteration and parallel runners. They do not
|
||||
replace any gate: `cargo test --locked --workspace` stays the full CPU gate, and
|
||||
This page records what the CPU test gate costs, describes
|
||||
`scripts/cpu-tests.sh`, which splits that gate into deterministic shards, and
|
||||
maps which x86-64 and loader behavior the tests verify. The shards are a
|
||||
convenience for local iteration and parallel runners. They do not replace any
|
||||
gate: `cargo test --locked --workspace` stays the full CPU gate, and
|
||||
`scripts/test-gpu.sh` stays the GPU gate.
|
||||
|
||||
## What counts as a CPU test
|
||||
@@ -96,3 +97,168 @@ than the full gate, because each target pays Cargo start-up.
|
||||
different commits are not comparable.
|
||||
- The experiment workspace `experiments/x1` is outside the selection. CI runs
|
||||
it separately.
|
||||
|
||||
## CPU and loader coverage map
|
||||
|
||||
This map inventories what the CPU and loader tests verify, per operation
|
||||
family, with the exact evidence commands and counts behind every number. It is
|
||||
documentation of verified state, not a compatibility claim, and it contains no
|
||||
percentages: every figure below is a count that a recorded command produced on
|
||||
one machine. The behavioral rules behind the map (how forms are declared, what
|
||||
"implemented" means, which forms are rejected on purpose) are documented in
|
||||
[docs/cpu/instruction-registry.md](../cpu/instruction-registry.md) and are not
|
||||
repeated here except where the map adds evidence.
|
||||
|
||||
### Method and revision
|
||||
|
||||
All commands ran on Apple M5, macOS 26.6.2, native arm64, Rust
|
||||
`1.100.0-aarch64-apple-darwin` (the revision CI pins), `CARGO_BUILD_JOBS=2`,
|
||||
on the branch holding this change, based on upstream `main` at
|
||||
`67b8cff` (2026-11-25).
|
||||
Recorded evidence commands:
|
||||
|
||||
```sh
|
||||
python3 crates/loader/generate_x86.py validate # 213 operations, 403 forms, 498 opcode slots
|
||||
python3 crates/loader/generate_x86.py --check # x86_table.rs is fresh
|
||||
PYTHONPATH=scripts python3 -m qa cpu-inventory # advisory partitions, cross-checked below
|
||||
cargo test --locked --workspace # 116 result lines: 1015 passed, 0 failed, 34 ignored
|
||||
```
|
||||
|
||||
The registry numbers are the generator's own count, not a hand count. The
|
||||
advisory `qa cpu-inventory` output was cross-checked against the code before
|
||||
use, and one stale row is called out under "Intentionally rejected forms".
|
||||
The default run recorded 34 ignored tests.
|
||||
|
||||
| Count | Category | Files |
|
||||
| --- | --- | --- |
|
||||
| 26 | Native Metal correctness | Five in `crates/loader/tests/` (`dbt_render.rs`, `graphics_d3d12.rs`, `graphics_textures.rs`, `runtime_x15.rs`), seven in `tests/validation/known_answers.rs`, and fourteen across `tests/validation/tests/` (`operand_domains.rs`, `sop1_unary.rs`, `sop2_arith.rs`, `sop2_stage_c.rs`, `sopc_stage_d.rs`, `sopk.rs`, `vop1_integer.rs`, `vop2_integer.rs`, `vop2_vcc.rs`, `vop3_compare.rs`, `vop3_integer.rs`, `vopc_f_t.rs`, `vopc_wide.rs`). |
|
||||
| 5 | LLVM AMDGPU oracle | Two in `crates/decoder/tests/gfx1030.rs` and one each in `crates/isa/tests/extension_word_negative.rs`, `meta_corpus.rs` and `meta_llvm.rs`. |
|
||||
| 3 | Manual CPU timing | Warm guest memory in `crates/loader/src/memory.rs`, relocation in `crates/loader/src/reloc.rs` and TLS templates in `crates/loader/src/tls.rs`. |
|
||||
|
||||
The two manual GPU timing tests in `crates/metal/tests/native_compute.rs`
|
||||
are outside these totals. Cargo requires the `gpu-tests` feature to build
|
||||
that target.
|
||||
|
||||
### Declared instruction inventory
|
||||
|
||||
`crates/loader/x86/instructions.toml` declares the decodable x86-64 surface.
|
||||
`generate_x86.py validate` reports **213 operations, 403 forms, 498 opcode
|
||||
slots** at this revision. By opcode map the slots split 235 one-byte and 263
|
||||
`0F`; by mandatory prefix 352 none, 107 `66`, 16 `F2`, 23 `F3`; by operand size
|
||||
96 byte (`b`), 139 variable 16/32/64 (`v`), 160 XMM 16-byte (`x`), 58 no
|
||||
operand (`n`), 22 32/64-only (`y`), 23 64-bit (`q`).
|
||||
|
||||
A declared form is decodable, not implemented. A form counts as supported only
|
||||
when it has semantics and fixture evidence. The fixture half is enforced:
|
||||
`every_declared_form_is_executed_by_a_fixture` in
|
||||
`crates/loader/tests/x86_integer.rs` decodes every line of the three assembly
|
||||
corpora (`tests/x86/integer.txt`, `vector.txt`, `float.txt`) and fails if any
|
||||
declared form is never executed. It lists the operations that are covered
|
||||
elsewhere instead (control flow and exits, `LDMXCSR`, and the
|
||||
`MOVS`/`STOS`/`CLD`/`STD` string family, which need their own memory layout and
|
||||
are covered form by form in `tests/cpu_rep.rs` and the loop tests).
|
||||
|
||||
### Engine path per operation
|
||||
|
||||
Of the 213 declared operations, **93 have at least one ARM64-lowered form**.
|
||||
Some other forms of those operations still use the shared interpreter helper.
|
||||
**119 operations use the helper for every translated form**, and **one**,
|
||||
`SYSCALL`, is decoded but refused by `is_translatable` in the DBT. Helper
|
||||
calls count toward `DbtMetrics::interpreter_fallbacks`. The conditional gates
|
||||
in `is_native` in `crates/loader/src/dbt.rs` apply at form level.
|
||||
|
||||
- `ADD`, `SUB`, `CMP`, `AND`, `OR`, `XOR`, `TEST`, `INC`, `DEC`, `NEG`, `NOT`
|
||||
and `CMOV` are native only at 32- and 64-bit width; 8- and 16-bit forms use
|
||||
the shared semantics.
|
||||
- `ADC` and `SBB` are native only for register and immediate operands; a memory
|
||||
destination stays on the helper path.
|
||||
- `BT` is native only in the `0F A3` register-index form; the `0F BA /4`
|
||||
immediate-index form can read a memory operand and uses the helper.
|
||||
- `BSF` and `BSR` are native at 16/32/64-bit width.
|
||||
- `POP` is native only in the opcode-register form.
|
||||
|
||||
`tests/x86_integer.rs` asserts the split both ways for every fixture: native
|
||||
forms must never call the helper, and helper forms always must. The interpreter
|
||||
runs all 213 operations through the shared semantics.
|
||||
|
||||
### Test evidence by artifact
|
||||
|
||||
Counts are from the full gate run recorded above (target name, tests run,
|
||||
passed/ignored). Expectation sources are named so independence can be judged.
|
||||
|
||||
| Artifact (under `crates/loader/tests/`) | Expectations derived from | Run result |
|
||||
| --- | --- | --- |
|
||||
| `x86_integer.rs` + `x86/integer.txt` (1230 fixture lines) | LLVM-assembled encodings; byte-level references written from the SDM/APM operation text, independent of the production semantics | 16 passed, 0 failed |
|
||||
| `x86_vector.rs` + `x86/vector.txt` (374 lines) | same method, SSE2 packed forms | 9 passed |
|
||||
| `x86_float.rs` + `x86/float.txt` (172), `x86/float_vectors.txt` (6824), `x86/float_reference.py` | exact-fraction reference computed by script, following SDM Vol. 1 floating-point rules | 9 passed |
|
||||
| `cpu_known_answers.rs` (50 tests, 838 named case lines) | Intel SDM and AMD APM sections cited per case; both engines run each case | 50 passed, 0 ignored |
|
||||
| `movsxd.rs` | SDM operation text; modular arithmetic in the test; LLVM-assembled encodings | 9 passed |
|
||||
| `x86_atomic.rs` | SDM LOCK/XADD/CMPXCHG rules; both compare outcomes, unaligned operands, faults | 5 passed |
|
||||
| `x86_carry_chain.rs` | widening `u128`/`i128` reference arithmetic on 256-bit chains | 8 passed |
|
||||
| `x86_prefix_length.rs` | SDM prefix and length rules | 8 passed |
|
||||
| `cpu_loop.rs` | a loop-model reference over every count, match point and budget | 3 passed |
|
||||
| `cpu_rep.rs` | a byte-array model over every MOVS/STOS form, direction and count, plus step accounting and faults | 7 passed |
|
||||
| `cpu_features.rs` | CPUID feature-bit pairing per the SDM; each reported bit requires the feature's fixtures, each commonly-tested unreported bit requires a refused witness | 4 passed |
|
||||
| `cpu_differential.rs` | interpreter and DBT must agree on shared fixtures | 5 passed |
|
||||
| `arm64_encodings.rs` | LLVM encodings for the assembler's emitted ARM64 | 3 passed |
|
||||
| `memory_page_boundaries.rs`, `memory_validation.rs` | mapping/permission/boundary contracts | 8 + 9 passed |
|
||||
| `generated_conformance.rs`, `bootstrap.rs`, `gate_a1.rs`, `gate_a2.rs`, `indirect_control.rs`, `bswap.rs`, `dbt_render.rs`, `process_exit.rs` | per-file documented contracts (generated conformance vectors, startup gates, control flow) | all passed except one Metal-gated ignore in `dbt_render.rs` |
|
||||
|
||||
Count named known-answer rows, including both byte-encoded and decoded cases,
|
||||
with the following command. This excludes section directives, format comments
|
||||
and Rust match arms.
|
||||
|
||||
```sh
|
||||
rg -c '^[A-Za-z0-9_]+:.*=>' crates/loader/tests/cpu_known_answers.rs
|
||||
```
|
||||
|
||||
The cache revalidation change in [PR #269](https://github.com/MacosPorters/betterxen/pull/269)
|
||||
restored `dbt_executes_modified_code_after_a_jump`. It passed in this run,
|
||||
and `cpu_known_answers.rs` reported 50 passes and zero ignores.
|
||||
|
||||
### Operations covered by model tests instead of the fixture corpus
|
||||
|
||||
The mnemonic-level fixture scan behind the advisory
|
||||
`PYTHONPATH=scripts python3 -m qa cpu-inventory` reports no assembly-text
|
||||
fixture for eight operations: `cld`, `std`, `jrcxz`, `loop`, `loope`,
|
||||
`loopne`, `movs`, `stos`. That is by design, not a gap: those operations need
|
||||
their own memory layout or counter model and are covered form by form in
|
||||
`tests/cpu_rep.rs` (MOVS/STOS/REP, the direction flag set by `STD` and cleared
|
||||
by `CLD`) and `tests/cpu_loop.rs` (LOOP/LOOPE/LOOPNE, JRCXZ on zero RCX). The
|
||||
declared-form enforcement test also exempts `LDMXCSR`, `Jcc`, `JMP`,
|
||||
`CALL`, `RET`, `HLT` and `SYSCALL`. It checks the remaining forms against the
|
||||
corpora.
|
||||
|
||||
### Intentionally rejected forms
|
||||
|
||||
The rejection list with its scope rules (LOCK limited to the memory forms of
|
||||
XADD and CMPXCHG, every x87 instruction except FNINIT,
|
||||
LODS/CMPS/SCAS/REPE/REPNE, MMX, RCP/RSQRT approximations, SSE3 and later,
|
||||
VEX, address-size overrides, 16-bit stack/branch forms, 16-bit BSWAP and
|
||||
MOVSXD, bit tests of memory by register index, CMPXCHG8B/16B, and the DBT
|
||||
refusing raw SYSCALL) is maintained in
|
||||
[docs/cpu/instruction-registry.md](../cpu/instruction-registry.md) and is
|
||||
tested by refusal cases inside the files above; this map does not duplicate it.
|
||||
|
||||
One advisory-tool discrepancy is recorded for its owner: the hand-written
|
||||
`unsupported_catalog` in `scripts/qa/cpu_inventory.py` lists "RCL/RCR/SHLD/
|
||||
SHRD", "string instructions" and "atomics/fences", which is stale against the
|
||||
code and tests at this revision — RCL/RCR/SHLD/SHRD are declared registry
|
||||
forms with implemented semantics (`x86_exec.rs`), 9 named `rcl*` cases and 8 named `shld*` or `shrd*` cases using the rule above,
|
||||
and 72 SHLD/SHRD assembly fixture lines; MOVS/STOS and the
|
||||
LOCK forms of XADD/CMPXCHG and the fences are supported within the documented
|
||||
scope. The catalog is advisory only and does not feed any gate.
|
||||
|
||||
### Map limitations
|
||||
|
||||
- Every count is pinned to the revision, host and single run named above.
|
||||
- The fixture evidence is mnemonic-level where it comes from the assembly
|
||||
corpora: it proves every declared form executes somewhere, not that every
|
||||
encoding variant of a form has its own expected-value case. The known-answer
|
||||
files carry the per-case expectations; their case lines are counted, not
|
||||
audited one by one here.
|
||||
- The native/shared partition is read from `is_native` at this revision and
|
||||
asserted by the fixtures; it is not a promise for other revisions.
|
||||
- Nothing here was compared with x86 hardware, no compatibility percentage is
|
||||
implied, and this is local documentation evidence, not independent
|
||||
acceptance.
|
||||
@@ -48,7 +48,7 @@ separate backend evidence. The [host evidence](../research/host-lab.md) records
|
||||
| Gate | Baseline disposition |
|
||||
| --- | --- |
|
||||
| P2-01 | Baseline captured. Phase 01 evidence and blockers are linked above. |
|
||||
| P2-02 | KyTx, Leonida and eight additional projects screened. Original fixtures and public specifications are the implementation source. No emulator code, tables or metadata are in scope for adoption. |
|
||||
| P2-02 | KyTx, PE-Vulkan project and eight additional projects screened. Original fixtures and public specifications are the implementation source. No emulator code, tables or metadata are in scope for adoption. |
|
||||
| P2-03 | VGPR-only OR verified on Apple M5. |
|
||||
| P2-04 | Workspace, LLVM and native GPU regression runs passed after OR integration. |
|
||||
| P2-05 | Independent OR expected values matched CPU execution and Metal readback. |
|
||||
|
||||
@@ -8,7 +8,7 @@ limit. A CPU rejection pass does not certify GPU execution.
|
||||
|
||||
| Upstream reference | Tested behavior | Xenora equivalent | Current result | Blocker |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| [Leonida compute](https://github.com/ItsNotRexed/Leonida/blob/3faac557b1584d39004357918e60325b4d4ff0fe/runtime/test/d3d12_compute_test.cpp) | Vulkan replay submits three distinct bindings and compares every readback word. Null, denied, malformed and out-of-bounds views decode to zero descriptors in separate controls. | Guest buffer view and original XOR readback. Persistent lifetime and snapshot tests extend this gate. | PASS for X8 view and readback | Xenora uses explicit faults for bad views. |
|
||||
| [PE-Vulkan project compute](https://github.com/ItsNotRexed/Leonida/blob/3faac557b1584d39004357918e60325b4d4ff0fe/runtime/test/d3d12_compute_test.cpp) | Vulkan replay submits three distinct bindings and compares every readback word. Null, denied, malformed and out-of-bounds views decode to zero descriptors in separate controls. | Guest buffer view and original XOR readback. Persistent lifetime and snapshot tests extend this gate. | PASS for X8 view and readback | Xenora uses explicit faults for bad views. |
|
||||
| [Xbox2Windows startup](https://github.com/R0Y00/Xbox2Windows/blob/cea1d927f891007262af75e0d907fddcc511b424/tests/cpu/startup_exe.cpp) | CPU startup exercises loading two DLLs, thread notifications and wait failures. | Original named-import PE32+ startup and missing import control. DLL and thread-local storage ordering are separate gates. | UNIMPLEMENTED for DLL and thread ordering | Bounded fixed-base guest profile. |
|
||||
| [Xbox2Windows wave shuffle](https://github.com/R0Y00/Xbox2Windows/blob/cea1d927f891007262af75e0d907fddcc511b424/tests/wave_shuffle.cpp) | D3D12 dispatch maps output by reported wave and lane, checks affine and rotation shuffles plus mirror and uniform controls, and rejects duplicate lanes or wrong widths. Forced variants require device capability. | ARM64 CPU compiler rejects an original gfx1030 cross-lane permute with a supported compile control. Native Wave64 shuffle needs a two-wave exact oracle. | PASS for rejection. UNIMPLEMENTED for Wave64 Metal dispatch. | No cross-lane lowering or Wave64 execution contract. |
|
||||
| [Xbox2Windows compute services](https://github.com/R0Y00/Xbox2Windows/blob/cea1d927f891007262af75e0d907fddcc511b424/tests/cpu/shim_compute_check.py) | Checks allocation, dispatch and free observations. Independently calculates four readback words. Provider rejection must produce zero output bytes. Native hardware is selected for the explicit hardware case. | Exact guest XOR readback, invalid import commands and observable destroy/reuse. | PASS for X8 XOR and malformed commands | Persistent resources have a separate X9 gate. |
|
||||
@@ -57,9 +57,9 @@ data sections, and no native host pointer crosses that boundary.
|
||||
|
||||
| Upstream reference | Tested behavior | Xenora equivalent | Current result | Blocker |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| Leonida compute and Xbox2Windows compute services | Repeat dispatch, update and release a resource with observable results | Original X9 PE repeats XOR with a nonzero view, updates words and destroys and reuses a slot. | PASS on Apple M5 | Device buffers are uploaded per completion. |
|
||||
| Leonida compute | Submission bindings and lifetime are independent of later changes | X9 queues a view, changes or destroys its owner and still gets the captured output. A second queued submission is rejected. | PASS on Apple M5 for queued snapshots | Actual GPU work already in flight during release is UNIMPLEMENTED. |
|
||||
| Leonida compute | Isolate guest runs and release resources at exit | X9 drops the table and any queued view at guest return. A queued-work exit returns guest status 73 and produces no GPU commands for that submission. | PASS for queued-work exit | Native Metal object residency across guest calls is UNIMPLEMENTED. |
|
||||
| Leonida compute | Reject malformed resource ranges | X9 rejects invalid or stale handles, out-of-range views, offset overflow, writeback into read-only memory and invalid resource types. | PASS for guest fault controls | The guest profile exposes one bounded submission at a time. |
|
||||
| PE-Vulkan project compute and Xbox2Windows compute services | Repeat dispatch, update and release a resource with observable results | Original X9 PE repeats XOR with a nonzero view, updates words and destroys and reuses a slot. | PASS on Apple M5 | Device buffers are uploaded per completion. |
|
||||
| PE-Vulkan project compute | Submission bindings and lifetime are independent of later changes | X9 queues a view, changes or destroys its owner and still gets the captured output. A second queued submission is rejected. | PASS on Apple M5 for queued snapshots | Actual GPU work already in flight during release is UNIMPLEMENTED. |
|
||||
| PE-Vulkan project compute | Isolate guest runs and release resources at exit | X9 drops the table and any queued view at guest return. A queued-work exit returns guest status 73 and produces no GPU commands for that submission. | PASS for queued-work exit | Native Metal object residency across guest calls is UNIMPLEMENTED. |
|
||||
| PE-Vulkan project compute | Reject malformed resource ranges | X9 rejects invalid or stale handles, out-of-range views, offset overflow, writeback into read-only memory and invalid resource types. | PASS for guest fault controls | The guest profile exposes one bounded submission at a time. |
|
||||
| Xbox2Windows pixel attributes | GPU pixels agree with a CPU expectation | X9 renders a constant or perspective-interpolated triangle through both translated stages. The PE checks every returned pixel. A separate host oracle checks exact values and the guest report. Changing the expected red byte of one interior pixel makes the PE return 93 after the same GPU readback. | PASS on Apple M5 | Shader selection uses original fixed fixture IDs. |
|
||||
| bcpack-rs round trips and Xbox2Windows texture LOD | Edge data and malformed input distinguish valid subresources | X9 validates a pitched descriptor, rejects wrong usage, layer, size and update requests, and reads selected BC1 mips and layers back through Metal. | PASS on Apple M5 for selected subresource readback | Translated texture sampling and GPU texture lifetime across guest calls are UNIMPLEMENTED. |
|
||||
@@ -6,7 +6,7 @@ identified the arithmetic shift as a candidate. Xenora uses the public
|
||||
and its existing pinned AMD XML generator for the VOP2 encoding. The lowering
|
||||
uses signed integer shift from the
|
||||
[Metal Shading Language Specification](https://developer.apple.com/metal/Metal-Shading-Language-Specification).
|
||||
The implementation and fixture were authored in Xenora. No Leonida code, tables,
|
||||
The implementation and fixture were authored in Xenora. No PE-Vulkan project code, tables,
|
||||
dependencies or game material were imported.
|
||||
|
||||
The decoder accepts the VOP2 VGPR/VGPR form. The shader lifter retains the synthetic
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Fast, deterministic documentation and repository hygiene checks.
|
||||
|
||||
Checks only tracked files:
|
||||
1. no merge-conflict markers in tracked text files;
|
||||
2. every relative Markdown link points at a tracked file or directory;
|
||||
3. every workflow file under .github/workflows parses as YAML.
|
||||
|
||||
External URLs and in-page anchors are not fetched or validated, so the result
|
||||
does not depend on the network. Exit status is 1 when a problem is found. Pass --require-yaml to fail, not skip,
|
||||
when PyYAML is missing.
|
||||
"""
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path, PurePosixPath
|
||||
from urllib.parse import unquote
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
MARKER = re.compile(r"^(<{7}( |$)|={7}$|>{7}( |$))")
|
||||
LINK = re.compile(r"(?<!\!)\[[^\]]*\]\(([^)\s]+)(?:\s+\"[^\"]*\")?\)")
|
||||
FENCE = re.compile(r"^\s*(```|~~~)")
|
||||
|
||||
|
||||
def tracked():
|
||||
out = subprocess.run(["git", "ls-files", "-z"], cwd=ROOT, check=True,
|
||||
capture_output=True).stdout.decode("utf-8", "replace")
|
||||
return [p for p in out.split("\0") if p and (ROOT / p).is_file()]
|
||||
|
||||
|
||||
def text(path):
|
||||
data = (ROOT / path).read_bytes()
|
||||
if b"\0" in data:
|
||||
return None
|
||||
return data.decode("utf-8", "replace")
|
||||
|
||||
|
||||
def check_markers(files, problems):
|
||||
for path in files:
|
||||
if path.endswith((".patch", ".diff")):
|
||||
continue
|
||||
body = text(path)
|
||||
if body is None:
|
||||
continue
|
||||
for number, line in enumerate(body.splitlines(), 1):
|
||||
if MARKER.match(line):
|
||||
problems.append(f"{path}:{number}: merge conflict marker")
|
||||
|
||||
|
||||
def check_links(files, problems):
|
||||
known = set(files)
|
||||
dirs = {str(d) for f in files for d in PurePosixPath(f).parents}
|
||||
for path in files:
|
||||
if not path.endswith(".md") or path.startswith(("artifacts/", "third_party/")):
|
||||
continue
|
||||
in_fence = False
|
||||
for number, line in enumerate((text(path) or "").splitlines(), 1):
|
||||
if FENCE.match(line):
|
||||
in_fence = not in_fence
|
||||
continue
|
||||
if in_fence:
|
||||
continue
|
||||
line = re.sub(r"`[^`]*`", "", line)
|
||||
for target in LINK.findall(line):
|
||||
if re.match(r"^([a-z][a-z0-9+.-]*:|#|//)", target, re.I):
|
||||
continue
|
||||
target = unquote(target.split("#", 1)[0].split("?", 1)[0])
|
||||
if not target:
|
||||
continue
|
||||
base = PurePosixPath(path).parent
|
||||
resolved = PurePosixPath(target.lstrip("/")) if target.startswith("/") else base / target
|
||||
parts = []
|
||||
for part in resolved.parts:
|
||||
if part == "..":
|
||||
if parts:
|
||||
parts.pop()
|
||||
elif part != ".":
|
||||
parts.append(part)
|
||||
norm = "/".join(parts)
|
||||
if norm and norm not in known and norm not in dirs:
|
||||
problems.append(f"{path}:{number}: broken relative link '{target}'")
|
||||
|
||||
|
||||
def check_workflows(files, problems, require_yaml):
|
||||
try:
|
||||
import yaml
|
||||
except ImportError:
|
||||
if require_yaml:
|
||||
problems.append("PyYAML is not installed but --require-yaml was given")
|
||||
else:
|
||||
print("note: PyYAML not installed; workflow YAML parse check skipped", file=sys.stderr)
|
||||
return
|
||||
for path in files:
|
||||
if path.startswith(".github/workflows/") and path.endswith((".yml", ".yaml")):
|
||||
try:
|
||||
yaml.safe_load((ROOT / path).read_text(encoding="utf-8"))
|
||||
except yaml.YAMLError as err:
|
||||
problems.append(f"{path}: invalid YAML: {str(err).splitlines()[0]}")
|
||||
|
||||
|
||||
def main():
|
||||
files = tracked()
|
||||
problems = []
|
||||
check_markers(files, problems)
|
||||
check_links(files, problems)
|
||||
check_workflows(files, problems, "--require-yaml" in sys.argv[1:])
|
||||
for problem in problems:
|
||||
print(problem)
|
||||
print(f"docs hygiene: {len(files)} tracked files checked, {len(problems)} problem(s)")
|
||||
return 1 if problems else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -54,5 +54,24 @@ codesign --force --sign - "$bundle"
|
||||
|
||||
binary="$bundle/Contents/MacOS/BetterXen"
|
||||
[ "$(lipo -archs "$binary")" = arm64 ] || fail "executable is not arm64-only: $(lipo -archs "$binary")"
|
||||
file "$binary"
|
||||
# Only system libraries may be linked: anything else would be a host dependency
|
||||
# shipped or expected outside macOS, which this bundle does not carry. List the
|
||||
# dependencies once, print that listing and check the same output.
|
||||
dependencies=$(otool -L "$binary") || fail "otool -L failed for $binary"
|
||||
printf '%s\n' "$dependencies"
|
||||
dependencies=$(printf '%s\n' "$dependencies" | tail -n +2 | awk '{print $1}')
|
||||
# Every Swift executable links at least libSystem, so an empty list is an error.
|
||||
[ -n "$dependencies" ] || fail "otool -L listed no dependencies for $binary"
|
||||
for dependency in $dependencies; do
|
||||
case "$dependency" in
|
||||
/System/Library/*|/usr/lib/*) ;;
|
||||
@rpath/*|@executable_path/*|@loader_path/*)
|
||||
fail "executable links a bundle-relative library, but this bundle ships none: $dependency" ;;
|
||||
*) fail "executable links a non-system library: $dependency" ;;
|
||||
esac
|
||||
done
|
||||
"$binary" --smoke
|
||||
"$binary" --smoke-inspection-order
|
||||
"$binary" --smoke-import-result
|
||||
echo "build-app: built $bundle"
|
||||
Loaded 100 of 113 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user