mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-27 20:20:28 +00:00
Compare commits
69
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
219a9756a3 | ||
|
|
c3279722e9 | ||
|
|
d21f38d631 | ||
|
|
ded1371b99 | ||
|
|
6cebcc559e | ||
|
|
790061e7c0 | ||
|
|
8e5856bbcf | ||
|
|
566272082a | ||
|
|
64ba56079f | ||
|
|
e266670e87 | ||
|
|
54b06fea3e | ||
|
|
8eb25fb9fe | ||
|
|
40ffea2789 | ||
|
|
80eacf9ac2 | ||
|
|
d9816e4cb5 | ||
|
|
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 | ||
|
|
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.
|
||||
@@ -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.
|
||||
+34
-1
@@ -9,8 +9,35 @@ exact revision and known limitations.
|
||||
Guest execution uses original, purpose-built test programs. Commercial Xbox game execution
|
||||
remains unsupported.
|
||||
|
||||
### Added
|
||||
- Investigated and resolved the two wave-operation failures of the vendored victory-shader tests under D3DMetal (`docs/research/shader-wave-semantics.md`). Measured device capabilities with a new original D3D12 host (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 caused by unsupported double-precision operations: shaders compiled from original HLSL by Microsoft's DXC that use a `double` (a plain add, or a wave sum) ran without writing anything, while wave operations on floats 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, 3 ignored; was 224 passed and 2 failed); 24 new GPU cases compare full 64-bit sums with a CPU model of the tree; both new tests fail against the original lowering. Cost not measured; tree-order fidelity relies on the recompiler's own recognizer.
|
||||
- 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 run them on the Apple GPU through D3D12 under CrossOver 26.3 (D3DMetal), plus `scripts/hybrid/run-shader-gpu-tests.sh`, which runs them through `betterxen-hybrid run`. Local results on the M4, not independently reproduced: 177 upstream CPU-side tests pass on macOS; all 6 fixtures with expected words (add, float-exact, bitwise-branch, or, shifts, ashr) 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 (wave-wide reductions), 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 `--stall-timeout` and a memory-settle wait to `betterxen-hybrid run`/`bench` (#385): a run that prints nothing for the given time is stopped and classified `stalled`, and after any stop the supervisor waits (up to `--settle-bound`, default 60 s) until free memory is back above the start threshold and records whether it recovered. Based on supervision lessons from skakwy's victory-mac (reimplemented, not copied). Also fixes a defect found by the first real stall run: stopping a bottle used `CX_BOTTLE`, which does not select the bottle, so a stopped Windows process kept running; it now sets `WINEPREFIX`. Verified with 4 new unit tests (stub launcher) and a real CrossOver 26.3 run on the M4: a silent workload was stopped as `stalled` after 4.7 s of a 120 s timeout, nothing was left running, and the next run passed. The low-memory recovery path is only tested with an injected memory reader. Not independently reviewed.
|
||||
- Added `betterxen-hybrid run` and `bench`: launch a Windows program through an installed CrossOver (`bin/wine --bottle`, an interface CodeWeavers does not document for macOS), with timeout, the memory guard, failure classification (passed, failed exit, timed out, stopped on low memory, cannot execute, no graphics device), sampled CrossOver process memory and CPU, thermal notes, recognised host-noise diagnostics and frame statistics, and write a JSON record; `bench` repeats a workload across graphics backends. Locally verified with 24 unit tests (stub launcher) and with real runs on CrossOver 26.3 on the Apple M4.
|
||||
- Executed the original Windows workloads under CrossOver 26.3 for the first time (`docs/research/crossover-baseline-2026-11-25.md`). x86-64 C, Rust, Direct3D 11 clear and triangle/frame-loop programs passed; all four ARM64 builds were rejected by CrossOver (`cannot execute`). Five-repeat, 2000-frame comparison of default, D3DMetal, DXMT, DXVK and wined3d on a trivial offscreen workload: D3DMetal's median submit-and-wait was about 1.8 times the others; this is not rendering performance. Observed on one machine, not independently reproduced, using an undocumented backend variable.
|
||||
- Added `workloads/d3d11-frameloop` (indexed triangle, shaders, event-query frame loop) and negative controls for both Direct3D programs; made workload builds byte-reproducible on one machine with `--no-insert-timestamp`.
|
||||
- Added `betterxen-hybrid guard`, a memory-pressure supervisor: it refuses to start a command when system-wide free memory is below a threshold and stops it (SIGTERM, then SIGKILL) when memory drops below a limit, reporting why. It is adapted from the memory guard in contributor skakwy's `victory-mac` `mac/run-victory.sh` (GPL-3.0, used with his permission) and reimplemented in Rust. Locally verified with 6 unit tests and three end-to-end runs (refuse, pass-through, stop) on macOS 27.0; the `memory_pressure -Q` output format is not a documented interface; not independently reviewed.
|
||||
- Added original Windows workloads and a build script (#364, #365): a C and a Rust self-checking console program and a Direct3D 11 clear-and-readback program (`workloads/`), built for x86-64 and ARM64 with a checksum-verified llvm-mingw 20261117 by `scripts/hybrid/build-windows-workloads.sh` (`docs/research/hybrid-toolchain.md`). All six outputs were confirmed as the right PE architecture with `file`. **The x86-64 outputs were later run under CrossOver (see below).**
|
||||
- Extended `docs/research/upstream-integration-audit.md` with a component-level review of skakwy's `victory-mac`: the reported ~1 FPS is, in his own notes, 1 to 1.9 s per frame of a leaked console-game dump measured by his runtime, so it is not reproducible or adoptable here. His Windows cross-link wrapper failed with Homebrew `llvm@17` and was not integrated; his Metal swizzle and D3DMetal-internals fixes are rejected; game-specific loader patches are rejected.
|
||||
- Added the `betterxen-hybrid` crate (`crates/hybrid`, no third-party dependencies, native arm64) with `host`, `crossover`, `toolchain`, `frames` and `receipt` commands that print JSON: a host receipt (macOS, chip, memory, core split, whether an x86_64 binary runs under Rosetta, GPU and Metal family), CrossOver discovery limited to `Info.plist` metadata, `lipo -archs` and the documented `BottleDir` and `ManagedBottleDirs` preferences, a Windows cross-compiler probe, and frame-time statistics (nearest-rank percentiles, 1 % and 0.1 % lows, stutter count). Locally verified: 13 unit tests, clippy with warnings denied, and a run on the Apple M4 reference machine, where CrossOver is **not installed** (the report says so) and only Homebrew mingw-w64 x86_64 and i686 compilers were found. CrossOver discovery has been tested on a synthetic bundle only and has never inspected a real CrossOver; nothing launches a program or measures a game. Not independently reviewed (#353, #350, #364, #145).
|
||||
- Added `docs/research/upstream-integration-audit.md` and registry and reuse-matrix rows for skakwy/victory-mac, MacBox, ScarlettMac, ossover, Whisky and rum (source read through the GitHub API, nothing executed, no code copied). Findings: MacBox and ScarlettMac are GPL-2.0 and game-specific, so they are rejected; the Game Porting Toolkit licence text (a third-party copy of version 4.0) limits use to developing, testing or evaluating games and distribution to non-commercial; contributor-reported frame results (about 1 FPS, then two rendered frames) are recorded as unverified.
|
||||
- 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 "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 active phase plan and README X1–X25 roadmap with one native macOS workload sequence and added a pinned PortWatch ecosystem review linked to eight contributor follow-ups. The plan distinguishes existing synthetic execution from future Xbox compatibility; no new runtime behavior, execution result or independent acceptance is claimed.
|
||||
- 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.
|
||||
@@ -21,6 +48,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`.
|
||||
@@ -34,6 +62,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.
|
||||
@@ -43,6 +73,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
+213
-8
@@ -2,6 +2,23 @@
|
||||
# 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 = "betterxen-hybrid"
|
||||
version = "0.1.0"
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.13.2"
|
||||
@@ -126,6 +143,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 +172,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 +233,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 +442,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,51 +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 phases
|
||||
|
||||
The active plan follows demonstrable native macOS workloads. Every phase has
|
||||
completion checks, dependencies and contributor issues in the
|
||||
[full development plan](docs/development-phases.md).
|
||||
|
||||
| Phase | Result to demonstrate |
|
||||
| --- | --- |
|
||||
| 1 — Compiled guest boot | Reproduce and independently accept the existing original C execution path on native ARM64. |
|
||||
| 2 — Modular guest runtime | Run an original executable with companion libraries, workers, checked waits and lifecycle cleanup. |
|
||||
| 3 — Guest-controlled Metal scene | Reach translated textured rendering through compiled guest calls, with checked resource lifetime and pixels. |
|
||||
| 4 — Interactive application | Combine guest execution, rendering, input, audio, saves and session controls in one original application. |
|
||||
| 5 — Compatibility corpus | Expand CPU/runtime/shader behavior using varied original workloads and independently derived regressions. |
|
||||
| 6 — Sustained native execution | Verify bounded long runs and measured performance on the Apple Silicon hosts actually tested. |
|
||||
| 7 — Xbox compatibility experiments | Resolve public console contracts and demonstrate each separately admitted execution stage before claiming support. |
|
||||
|
||||
These phases replace the previous roadmap. They are targets, not completed
|
||||
acceptance claims or a game-release timeline. Console-contract research and
|
||||
bounded subsystem work can proceed in parallel. Historical fixture identifiers
|
||||
such as X9 remain labels for their original test/evidence records.
|
||||
|
||||
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.
|
||||
@@ -166,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.
|
||||
|
||||
@@ -219,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.
|
||||
|
||||
@@ -243,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 |
|
||||
|
||||
@@ -340,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 [development phases](docs/development-phases.md) for the current work order, and the [changelog](CHANGELOG.md) for the current unreleased additions, such as the native blend pass, indexed draws and the depth pass. The remaining research steps are the outstanding items in [current limitations](#current-limitations).
|
||||
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).
|
||||
|
||||
---
|
||||
|
||||
@@ -356,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,9 @@ 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.
|
||||
|
||||
llvm-mingw release 20261117 is used as an external build tool for original Windows test programs under Apache-2.0 with LLVM exceptions plus its component licences; nothing from it is shipped or copied (see [hybrid-toolchain](docs/research/hybrid-toolchain.md)). `crates/hybrid/src/memory.rs` is a Rust reimplementation of the memory-guard logic in skakwy's [victory-mac](https://github.com/skakwy/victory-mac) `mac/run-victory.sh` (commit 22b3f8e45a59, GPL-3.0), used with the author's permission. The stall detection and memory-settle logic in `crates/hybrid/src/run.rs` follows supervision lessons from the same repository (`mac/PROGRESS.md`, `crates/victory-core/src/notes.rs`) and is reimplemented, not copied.
|
||||
|
||||
`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}");
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
[package]
|
||||
name = "betterxen-hybrid"
|
||||
description = "Host receipt, CrossOver discovery, frame-time statistics and Windows cross-toolchain probes for the hybrid direction"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "betterxen-hybrid"
|
||||
path = "src/main.rs"
|
||||
@@ -0,0 +1,13 @@
|
||||
//! Run a system tool and capture trimmed stdout. A missing tool or non-zero exit is `None`,
|
||||
//! never a guessed value.
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
pub fn run(program: &str, args: &[&str]) -> Option<String> {
|
||||
let out = Command::new(program).args(args).output().ok()?;
|
||||
if !out.status.success() {
|
||||
return None;
|
||||
}
|
||||
let s = String::from_utf8_lossy(&out.stdout).trim().to_string();
|
||||
Some(s)
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
//! Discover installed CrossOver bundles and read standard bundle metadata.
|
||||
//!
|
||||
//! Only documented or standard macOS interfaces are used: the app bundle's `Info.plist`
|
||||
//! (read through `plutil`), `lipo -archs` on the bundle's main executable, and the
|
||||
//! `defaults` keys CodeWeavers documents in "Advanced CrossOver Mac Configuration"
|
||||
//! (`BottleDir`, `ManagedBottleDirs` in `com.codeweavers.CrossOver`). Bundle internals such
|
||||
//! as `Contents/SharedSupport` are NOT interpreted: they are undocumented and not a stable
|
||||
//! interface (#350). The graphics backend of a bottle is deliberately not read.
|
||||
|
||||
use crate::cmdutil::run;
|
||||
use crate::json::Json;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub const BUNDLE_ID: &str = "com.codeweavers.CrossOver";
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Install {
|
||||
pub path: PathBuf,
|
||||
pub bundle_id: Option<String>,
|
||||
pub short_version: Option<String>,
|
||||
pub build_version: Option<String>,
|
||||
pub executable_archs: Option<Vec<String>>,
|
||||
pub minimum_macos: Option<String>,
|
||||
}
|
||||
|
||||
/// Candidate bundle locations: standard application directories. Spotlight is consulted too.
|
||||
pub fn candidate_paths(home: &Path) -> Vec<PathBuf> {
|
||||
let mut v = vec![
|
||||
PathBuf::from("/Applications/CrossOver.app"),
|
||||
home.join("Applications/CrossOver.app"),
|
||||
];
|
||||
if let Some(found) = run(
|
||||
"/usr/bin/mdfind",
|
||||
&[&format!("kMDItemCFBundleIdentifier == '{BUNDLE_ID}'")],
|
||||
) {
|
||||
for line in found.lines().filter(|l| !l.is_empty()) {
|
||||
let p = PathBuf::from(line);
|
||||
if !v.contains(&p) {
|
||||
v.push(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
pub fn discover(candidates: &[PathBuf]) -> Vec<Install> {
|
||||
candidates.iter().filter_map(|p| inspect(p)).collect()
|
||||
}
|
||||
|
||||
/// Inspect one bundle. Returns None if the path has no readable `Contents/Info.plist`.
|
||||
pub fn inspect(app: &Path) -> Option<Install> {
|
||||
let plist = app.join("Contents/Info.plist");
|
||||
if !plist.is_file() {
|
||||
return None;
|
||||
}
|
||||
let json = run(
|
||||
"/usr/bin/plutil",
|
||||
&["-convert", "json", "-o", "-", plist.to_str()?],
|
||||
)?;
|
||||
let exe = crate::host_string(&json, "CFBundleExecutable");
|
||||
let archs = exe.and_then(|e| {
|
||||
let p = app.join("Contents/MacOS").join(e);
|
||||
run("/usr/bin/lipo", &["-archs", p.to_str()?])
|
||||
.map(|s| s.split_whitespace().map(String::from).collect())
|
||||
});
|
||||
Some(Install {
|
||||
path: app.to_path_buf(),
|
||||
bundle_id: crate::host_string(&json, "CFBundleIdentifier"),
|
||||
short_version: crate::host_string(&json, "CFBundleShortVersionString"),
|
||||
build_version: crate::host_string(&json, "CFBundleVersion"),
|
||||
executable_archs: archs,
|
||||
minimum_macos: crate::host_string(&json, "LSMinimumSystemVersion"),
|
||||
})
|
||||
}
|
||||
|
||||
/// A documented CrossOver preference, or None when unset or unreadable.
|
||||
pub fn preference(key: &str) -> Option<String> {
|
||||
run("/usr/bin/defaults", &["read", BUNDLE_ID, key])
|
||||
}
|
||||
|
||||
impl Install {
|
||||
pub fn to_json(&self) -> Json {
|
||||
Json::obj(vec![
|
||||
("path", Json::str(self.path.display().to_string())),
|
||||
("bundle_id", Json::opt_str(self.bundle_id.clone())),
|
||||
("short_version", Json::opt_str(self.short_version.clone())),
|
||||
("build_version", Json::opt_str(self.build_version.clone())),
|
||||
(
|
||||
"executable_archs",
|
||||
self.executable_archs.as_ref().map_or(Json::Null, |a| {
|
||||
Json::Arr(a.iter().map(|s| Json::str(s.clone())).collect())
|
||||
}),
|
||||
),
|
||||
("minimum_macos", Json::opt_str(self.minimum_macos.clone())),
|
||||
(
|
||||
"bundle_id_is_codeweavers_crossover",
|
||||
Json::Bool(self.bundle_id.as_deref() == Some(BUNDLE_ID)),
|
||||
),
|
||||
])
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::fs;
|
||||
|
||||
// A synthetic bundle written by the test: it proves the metadata path, not that
|
||||
// any real CrossOver build has this layout.
|
||||
fn fake_bundle(dir: &Path) -> PathBuf {
|
||||
let app = dir.join("CrossOver.app");
|
||||
fs::create_dir_all(app.join("Contents/MacOS")).unwrap();
|
||||
fs::write(
|
||||
app.join("Contents/Info.plist"),
|
||||
r#"<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0"><dict>
|
||||
<key>CFBundleExecutable</key><string>CrossOver</string>
|
||||
<key>CFBundleIdentifier</key><string>com.codeweavers.CrossOver</string>
|
||||
<key>CFBundleShortVersionString</key><string>99.1.2</string>
|
||||
<key>CFBundleVersion</key><string>12345</string>
|
||||
<key>LSMinimumSystemVersion</key><string>14.0</string>
|
||||
</dict></plist>"#,
|
||||
)
|
||||
.unwrap();
|
||||
// Copy a real system executable so `lipo -archs` has a Mach-O to read.
|
||||
fs::copy("/usr/bin/true", app.join("Contents/MacOS/CrossOver")).unwrap();
|
||||
app
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_bundle_metadata() {
|
||||
if !cfg!(target_os = "macos") {
|
||||
return;
|
||||
}
|
||||
let tmp = std::env::temp_dir().join(format!("bxhybrid-co-{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&tmp);
|
||||
fs::create_dir_all(&tmp).unwrap();
|
||||
let app = fake_bundle(&tmp);
|
||||
let i = inspect(&app).expect("inspect");
|
||||
assert_eq!(i.short_version.as_deref(), Some("99.1.2"));
|
||||
assert_eq!(i.build_version.as_deref(), Some("12345"));
|
||||
assert_eq!(i.minimum_macos.as_deref(), Some("14.0"));
|
||||
assert_eq!(i.bundle_id.as_deref(), Some(BUNDLE_ID));
|
||||
assert!(
|
||||
i.executable_archs.as_ref().is_some_and(|a| !a.is_empty()),
|
||||
"{:?}",
|
||||
i.executable_archs
|
||||
);
|
||||
assert_eq!(discover(&[app.clone(), tmp.join("Missing.app")]).len(), 1);
|
||||
fs::remove_dir_all(&tmp).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_or_plistless_bundle_is_none() {
|
||||
let tmp = std::env::temp_dir().join(format!("bxhybrid-co2-{}", std::process::id()));
|
||||
fs::create_dir_all(tmp.join("X.app/Contents")).unwrap();
|
||||
assert!(inspect(&tmp.join("X.app")).is_none());
|
||||
assert!(inspect(&tmp.join("Nope.app")).is_none());
|
||||
fs::remove_dir_all(&tmp).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
//! Frame-time statistics from a list of frame intervals in milliseconds (issue #145).
|
||||
//!
|
||||
//! Percentiles use the nearest-rank method on the sorted intervals: the p-th percentile is
|
||||
//! the value at rank ceil(p/100 * n) (1-based). "1 % low FPS" is 1000 divided by the 99th
|
||||
//! percentile interval. These definitions are fixed here so reports are comparable; other
|
||||
//! tools define lows differently (for example as the mean of the worst 1 %).
|
||||
|
||||
use crate::json::Json;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct FrameStats {
|
||||
pub frames: usize,
|
||||
pub total_ms: f64,
|
||||
pub mean_ms: f64,
|
||||
pub avg_fps: f64,
|
||||
pub min_ms: f64,
|
||||
pub max_ms: f64,
|
||||
pub p50_ms: f64,
|
||||
pub p95_ms: f64,
|
||||
pub p99_ms: f64,
|
||||
pub p999_ms: f64,
|
||||
pub low_1pct_fps: f64,
|
||||
pub low_01pct_fps: f64,
|
||||
/// Frames longer than twice the median interval.
|
||||
pub stutters: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum FrameError {
|
||||
Empty,
|
||||
Invalid { index: usize, value: f64 },
|
||||
Parse { line: usize, text: String },
|
||||
}
|
||||
|
||||
impl std::fmt::Display for FrameError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
FrameError::Empty => write!(f, "no frame intervals"),
|
||||
FrameError::Invalid { index, value } => {
|
||||
write!(
|
||||
f,
|
||||
"frame {index}: interval {value} is not a positive finite number of milliseconds"
|
||||
)
|
||||
}
|
||||
FrameError::Parse { line, text } => {
|
||||
write!(f, "line {line}: cannot parse {text:?} as milliseconds")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for FrameError {}
|
||||
|
||||
fn nearest_rank(sorted: &[f64], pct: f64) -> f64 {
|
||||
let n = sorted.len();
|
||||
let rank = ((pct / 100.0) * n as f64).ceil().max(1.0) as usize;
|
||||
sorted[rank.min(n) - 1]
|
||||
}
|
||||
|
||||
pub fn analyze(intervals_ms: &[f64]) -> Result<FrameStats, FrameError> {
|
||||
if intervals_ms.is_empty() {
|
||||
return Err(FrameError::Empty);
|
||||
}
|
||||
for (index, &value) in intervals_ms.iter().enumerate() {
|
||||
if !value.is_finite() || value <= 0.0 {
|
||||
return Err(FrameError::Invalid { index, value });
|
||||
}
|
||||
}
|
||||
let mut sorted = intervals_ms.to_vec();
|
||||
sorted.sort_by(|a, b| a.total_cmp(b));
|
||||
let total: f64 = intervals_ms.iter().sum();
|
||||
let n = sorted.len();
|
||||
let p50 = nearest_rank(&sorted, 50.0);
|
||||
let p99 = nearest_rank(&sorted, 99.0);
|
||||
let p999 = nearest_rank(&sorted, 99.9);
|
||||
Ok(FrameStats {
|
||||
frames: n,
|
||||
total_ms: total,
|
||||
mean_ms: total / n as f64,
|
||||
avg_fps: n as f64 / (total / 1000.0),
|
||||
min_ms: sorted[0],
|
||||
max_ms: sorted[n - 1],
|
||||
p50_ms: p50,
|
||||
p95_ms: nearest_rank(&sorted, 95.0),
|
||||
p99_ms: p99,
|
||||
p999_ms: p999,
|
||||
low_1pct_fps: 1000.0 / p99,
|
||||
low_01pct_fps: 1000.0 / p999,
|
||||
stutters: intervals_ms.iter().filter(|&&v| v > 2.0 * p50).count(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Parse one interval per line; blank lines and lines starting with `#` are skipped.
|
||||
pub fn parse_intervals(text: &str) -> Result<Vec<f64>, FrameError> {
|
||||
let mut out = Vec::new();
|
||||
for (i, line) in text.lines().enumerate() {
|
||||
let t = line.trim();
|
||||
if t.is_empty() || t.starts_with('#') {
|
||||
continue;
|
||||
}
|
||||
let v: f64 = t.parse().map_err(|_| FrameError::Parse {
|
||||
line: i + 1,
|
||||
text: t.to_string(),
|
||||
})?;
|
||||
out.push(v);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
impl FrameStats {
|
||||
pub fn to_json(&self) -> Json {
|
||||
Json::obj(vec![
|
||||
("frames", Json::Num(self.frames as f64)),
|
||||
("total_ms", Json::Num(self.total_ms)),
|
||||
("mean_ms", Json::Num(self.mean_ms)),
|
||||
("avg_fps", Json::Num(self.avg_fps)),
|
||||
("min_ms", Json::Num(self.min_ms)),
|
||||
("max_ms", Json::Num(self.max_ms)),
|
||||
("p50_ms", Json::Num(self.p50_ms)),
|
||||
("p95_ms", Json::Num(self.p95_ms)),
|
||||
("p99_ms", Json::Num(self.p99_ms)),
|
||||
("p999_ms", Json::Num(self.p999_ms)),
|
||||
("low_1pct_fps", Json::Num(self.low_1pct_fps)),
|
||||
("low_0_1pct_fps", Json::Num(self.low_01pct_fps)),
|
||||
("stutters_over_2x_median", Json::Num(self.stutters as f64)),
|
||||
("percentile_method", Json::str("nearest-rank")),
|
||||
])
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
// Expected values below are worked out by hand, not produced by analyze().
|
||||
#[test]
|
||||
fn known_answer_ten_frames() {
|
||||
// Sorted: 10,10,10,10,10,10,10,10,20,100. Total 200 ms, n = 10.
|
||||
let v = [10.0, 10.0, 10.0, 10.0, 20.0, 10.0, 10.0, 10.0, 100.0, 10.0];
|
||||
let s = analyze(&v).unwrap();
|
||||
assert_eq!(s.frames, 10);
|
||||
assert_eq!(s.total_ms, 200.0);
|
||||
assert_eq!(s.mean_ms, 20.0);
|
||||
assert_eq!(s.avg_fps, 50.0);
|
||||
assert_eq!(s.p50_ms, 10.0); // rank 5
|
||||
assert_eq!(s.p95_ms, 100.0); // rank ceil(9.5) = 10
|
||||
assert_eq!(s.p99_ms, 100.0);
|
||||
assert_eq!(s.low_1pct_fps, 10.0);
|
||||
assert_eq!(s.stutters, 1); // threshold is 2 * 10 = 20; 20 is not > 20, only 100 is.
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stutter_threshold_is_strict() {
|
||||
let s = analyze(&[10.0, 10.0, 10.0, 20.0, 21.0]).unwrap();
|
||||
assert_eq!(s.stutters, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_frame_per_second() {
|
||||
let s = analyze(&[1000.0, 1000.0]).unwrap();
|
||||
assert_eq!(s.avg_fps, 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_bad_input() {
|
||||
assert_eq!(analyze(&[]), Err(FrameError::Empty));
|
||||
assert!(matches!(
|
||||
analyze(&[1.0, 0.0]),
|
||||
Err(FrameError::Invalid { index: 1, .. })
|
||||
));
|
||||
assert!(matches!(
|
||||
analyze(&[f64::NAN]),
|
||||
Err(FrameError::Invalid { .. })
|
||||
));
|
||||
assert!(matches!(analyze(&[-3.0]), Err(FrameError::Invalid { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_text() {
|
||||
assert_eq!(
|
||||
parse_intervals("# c\n16.5\n\n 8 \n").unwrap(),
|
||||
vec![16.5, 8.0]
|
||||
);
|
||||
assert_eq!(
|
||||
parse_intervals("1\nabc\n"),
|
||||
Err(FrameError::Parse {
|
||||
line: 2,
|
||||
text: "abc".into()
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
//! Host receipt: what this Mac is, from documented system interfaces (issue #353).
|
||||
//!
|
||||
//! Every field is `Option` where the probe can fail; absence is reported as null, not guessed.
|
||||
|
||||
use crate::cmdutil::run;
|
||||
use crate::json::Json;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct HostReceipt {
|
||||
pub macos_version: Option<String>,
|
||||
pub macos_build: Option<String>,
|
||||
pub chip: Option<String>,
|
||||
pub apple_silicon: Option<bool>,
|
||||
pub memory_bytes: Option<u64>,
|
||||
pub logical_cpus: Option<u32>,
|
||||
pub performance_cores: Option<u32>,
|
||||
pub efficiency_cores: Option<u32>,
|
||||
/// True only if an x86_64 slice of a system binary actually executed.
|
||||
pub rosetta_executes_x86_64: Option<bool>,
|
||||
pub gpu_name: Option<String>,
|
||||
pub gpu_cores: Option<String>,
|
||||
pub metal_support: Option<String>,
|
||||
pub host_arch_of_this_binary: &'static str,
|
||||
}
|
||||
|
||||
fn sysctl(name: &str) -> Option<String> {
|
||||
run("/usr/sbin/sysctl", &["-n", name])
|
||||
}
|
||||
|
||||
pub fn collect() -> HostReceipt {
|
||||
let gpu = run(
|
||||
"/usr/sbin/system_profiler",
|
||||
&["SPDisplaysDataType", "-json"],
|
||||
)
|
||||
.and_then(|j| parse_gpu(&j));
|
||||
HostReceipt {
|
||||
macos_version: run("/usr/bin/sw_vers", &["-productVersion"]),
|
||||
macos_build: sysctl("kern.osversion"),
|
||||
chip: sysctl("machdep.cpu.brand_string"),
|
||||
apple_silicon: sysctl("hw.optional.arm64").map(|v| v == "1"),
|
||||
memory_bytes: sysctl("hw.memsize").and_then(|v| v.parse().ok()),
|
||||
logical_cpus: sysctl("hw.logicalcpu").and_then(|v| v.parse().ok()),
|
||||
performance_cores: sysctl("hw.perflevel0.physicalcpu").and_then(|v| v.parse().ok()),
|
||||
efficiency_cores: sysctl("hw.perflevel1.physicalcpu").and_then(|v| v.parse().ok()),
|
||||
// Executes the x86_64 slice of /usr/bin/true. Failure means Rosetta cannot run it
|
||||
// now; it does not distinguish "not installed" from "disabled".
|
||||
rosetta_executes_x86_64: Some(
|
||||
run("/usr/bin/arch", &["-x86_64", "/usr/bin/true"]).is_some(),
|
||||
),
|
||||
gpu_name: gpu.as_ref().map(|g| g.0.clone()),
|
||||
gpu_cores: gpu.as_ref().and_then(|g| g.1.clone()),
|
||||
metal_support: gpu.as_ref().and_then(|g| g.2.clone()),
|
||||
host_arch_of_this_binary: std::env::consts::ARCH,
|
||||
}
|
||||
}
|
||||
|
||||
/// Pull `sppci_model`, `sppci_cores` and `spdisplays_mtlgpufamilysupport` of the first display
|
||||
/// entry from `system_profiler SPDisplaysDataType -json` output. Returns None if the model
|
||||
/// key is absent. Uses a small string scan because this crate has no JSON parser dependency.
|
||||
pub fn parse_gpu(json: &str) -> Option<(String, Option<String>, Option<String>)> {
|
||||
let model = string_value(json, "sppci_model")?;
|
||||
Some((
|
||||
model,
|
||||
string_value(json, "sppci_cores"),
|
||||
string_value(json, "spdisplays_mtlgpufamilysupport"),
|
||||
))
|
||||
}
|
||||
|
||||
fn string_value(json: &str, key: &str) -> Option<String> {
|
||||
let needle = format!("\"{key}\"");
|
||||
let at = json.find(&needle)? + needle.len();
|
||||
let rest = json[at..].trim_start().strip_prefix(':')?.trim_start();
|
||||
let rest = rest.strip_prefix('"')?;
|
||||
let end = rest.find('"')?;
|
||||
Some(rest[..end].to_string())
|
||||
}
|
||||
|
||||
impl HostReceipt {
|
||||
pub fn to_json(&self) -> Json {
|
||||
let n = |v: Option<u32>| v.map_or(Json::Null, |x| Json::Num(x as f64));
|
||||
Json::obj(vec![
|
||||
("macos_version", Json::opt_str(self.macos_version.clone())),
|
||||
("macos_build", Json::opt_str(self.macos_build.clone())),
|
||||
("chip", Json::opt_str(self.chip.clone())),
|
||||
(
|
||||
"apple_silicon",
|
||||
self.apple_silicon.map_or(Json::Null, Json::Bool),
|
||||
),
|
||||
(
|
||||
"memory_bytes",
|
||||
self.memory_bytes
|
||||
.map_or(Json::Null, |x| Json::Num(x as f64)),
|
||||
),
|
||||
("logical_cpus", n(self.logical_cpus)),
|
||||
("performance_cores", n(self.performance_cores)),
|
||||
("efficiency_cores", n(self.efficiency_cores)),
|
||||
(
|
||||
"rosetta_executes_x86_64",
|
||||
self.rosetta_executes_x86_64.map_or(Json::Null, Json::Bool),
|
||||
),
|
||||
("gpu_name", Json::opt_str(self.gpu_name.clone())),
|
||||
("gpu_cores", Json::opt_str(self.gpu_cores.clone())),
|
||||
("metal_support", Json::opt_str(self.metal_support.clone())),
|
||||
(
|
||||
"receipt_binary_arch",
|
||||
Json::str(self.host_arch_of_this_binary),
|
||||
),
|
||||
])
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_gpu_fixture() {
|
||||
let j = r#"{"SPDisplaysDataType":[{"sppci_cores":"10","sppci_model":"Apple M4",
|
||||
"spdisplays_mtlgpufamilysupport":"spdisplays_metal4"}]}"#;
|
||||
let g = parse_gpu(j).unwrap();
|
||||
assert_eq!(g.0, "Apple M4");
|
||||
assert_eq!(g.1.as_deref(), Some("10"));
|
||||
assert_eq!(g.2.as_deref(), Some("spdisplays_metal4"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_gpu_is_none() {
|
||||
assert!(parse_gpu("{}").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collect_runs_on_this_host() {
|
||||
let r = collect();
|
||||
if cfg!(target_os = "macos") {
|
||||
assert!(r.macos_version.is_some());
|
||||
assert!(r.memory_bytes.unwrap() > 0);
|
||||
}
|
||||
assert!(r.to_json().render().contains("receipt_binary_arch"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
//! Minimal JSON value and writer. Output only; no parsing is needed by this crate.
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum Json {
|
||||
Null,
|
||||
Bool(bool),
|
||||
Num(f64),
|
||||
Str(String),
|
||||
Arr(Vec<Json>),
|
||||
Obj(Vec<(String, Json)>),
|
||||
}
|
||||
|
||||
impl Json {
|
||||
pub fn str(s: impl Into<String>) -> Json {
|
||||
Json::Str(s.into())
|
||||
}
|
||||
pub fn opt_str(s: Option<String>) -> Json {
|
||||
s.map_or(Json::Null, Json::Str)
|
||||
}
|
||||
pub fn obj(fields: Vec<(&str, Json)>) -> Json {
|
||||
Json::Obj(
|
||||
fields
|
||||
.into_iter()
|
||||
.map(|(k, v)| (k.to_string(), v))
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn render(&self) -> String {
|
||||
let mut out = String::new();
|
||||
self.write(&mut out, 0);
|
||||
out.push('\n');
|
||||
out
|
||||
}
|
||||
|
||||
fn write(&self, out: &mut String, depth: usize) {
|
||||
let pad = |out: &mut String, d: usize| out.push_str(&" ".repeat(d));
|
||||
match self {
|
||||
Json::Null => out.push_str("null"),
|
||||
Json::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
|
||||
Json::Num(n) if n.is_finite() => {
|
||||
if n.fract() == 0.0 && n.abs() < 1e15 {
|
||||
out.push_str(&format!("{}", *n as i64));
|
||||
} else {
|
||||
out.push_str(&format!("{n}"));
|
||||
}
|
||||
}
|
||||
// JSON has no NaN or infinity; refuse to invent a number.
|
||||
Json::Num(_) => out.push_str("null"),
|
||||
Json::Str(s) => escape(s, out),
|
||||
Json::Arr(items) if items.is_empty() => out.push_str("[]"),
|
||||
Json::Arr(items) => {
|
||||
out.push_str("[\n");
|
||||
for (i, item) in items.iter().enumerate() {
|
||||
pad(out, depth + 1);
|
||||
item.write(out, depth + 1);
|
||||
out.push_str(if i + 1 < items.len() { ",\n" } else { "\n" });
|
||||
}
|
||||
pad(out, depth);
|
||||
out.push(']');
|
||||
}
|
||||
Json::Obj(fields) if fields.is_empty() => out.push_str("{}"),
|
||||
Json::Obj(fields) => {
|
||||
out.push_str("{\n");
|
||||
for (i, (k, v)) in fields.iter().enumerate() {
|
||||
pad(out, depth + 1);
|
||||
escape(k, out);
|
||||
out.push_str(": ");
|
||||
v.write(out, depth + 1);
|
||||
out.push_str(if i + 1 < fields.len() { ",\n" } else { "\n" });
|
||||
}
|
||||
pad(out, depth);
|
||||
out.push('}');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn escape(s: &str, out: &mut String) {
|
||||
out.push('"');
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
'"' => out.push_str("\\\""),
|
||||
'\\' => out.push_str("\\\\"),
|
||||
'\n' => out.push_str("\\n"),
|
||||
'\r' => out.push_str("\\r"),
|
||||
'\t' => out.push_str("\\t"),
|
||||
c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
out.push('"');
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn escapes_and_nests() {
|
||||
let j = Json::obj(vec![
|
||||
("a", Json::str("q\"\\\n\u{1}")),
|
||||
(
|
||||
"b",
|
||||
Json::Arr(vec![Json::Num(1.0), Json::Num(0.5), Json::Null]),
|
||||
),
|
||||
("c", Json::Num(f64::NAN)),
|
||||
]);
|
||||
let r = j.render();
|
||||
assert!(r.contains(r#""a": "q\"\\\n\u0001""#), "{r}");
|
||||
assert!(r.contains("0.5"));
|
||||
assert!(r.contains(r#""c": null"#));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
//! BetterXen hybrid tooling: read-only inspection and measurement helpers around an
|
||||
//! externally installed CrossOver. Nothing here launches a game or claims compatibility.
|
||||
|
||||
pub mod cmdutil;
|
||||
pub mod crossover;
|
||||
pub mod frames;
|
||||
pub mod host;
|
||||
pub mod json;
|
||||
pub mod memory;
|
||||
pub mod run;
|
||||
pub mod toolchain;
|
||||
|
||||
/// Value of a top-level string key in flat JSON produced by `plutil -convert json`.
|
||||
pub fn host_string(json: &str, key: &str) -> Option<String> {
|
||||
let needle = format!("\"{key}\"");
|
||||
let at = json.find(&needle)? + needle.len();
|
||||
let rest = json[at..]
|
||||
.trim_start()
|
||||
.strip_prefix(':')?
|
||||
.trim_start()
|
||||
.strip_prefix('"')?;
|
||||
let mut out = String::new();
|
||||
let mut chars = rest.chars();
|
||||
while let Some(c) = chars.next() {
|
||||
match c {
|
||||
'"' => return Some(out),
|
||||
'\\' => out.push(chars.next()?),
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
@@ -0,0 +1,325 @@
|
||||
use betterxen_hybrid::{crossover, frames, host, json::Json, memory, run, toolchain};
|
||||
use std::path::PathBuf;
|
||||
use std::process::ExitCode;
|
||||
|
||||
const USAGE: &str = "usage: betterxen-hybrid <command>
|
||||
host host receipt (JSON)
|
||||
crossover [--app P] CrossOver installs and documented preferences (JSON)
|
||||
toolchain Windows cross-compilers found on PATH (JSON)
|
||||
frames <file> frame-time statistics; file has one interval in ms per line (JSON)
|
||||
guard [--min-start-free N] [--min-free N] -- CMD ARGS...
|
||||
run CMD; refuse to start / stop it when free memory is low
|
||||
run --bottle B [--backend X] [--timeout S] [--stall-timeout S] [--settle-bound S] [--expect TEXT] [--out DIR]
|
||||
[--min-start-free N] [--min-free N] -- EXE [ARGS...]
|
||||
run a Windows program through CrossOver; write a JSON record
|
||||
bench --bottle B --backends a,b,c [--repeat N] [same options] -- EXE [ARGS...]
|
||||
run the program per backend N times; summarise frame times
|
||||
receipt host + crossover + toolchain in one JSON document";
|
||||
|
||||
fn crossover_json(app: Option<PathBuf>) -> Json {
|
||||
let home = PathBuf::from(std::env::var("HOME").unwrap_or_default());
|
||||
let cands = match app {
|
||||
Some(p) => vec![p],
|
||||
None => crossover::candidate_paths(&home),
|
||||
};
|
||||
let installs = crossover::discover(&cands);
|
||||
Json::obj(vec![
|
||||
("installed", Json::Bool(!installs.is_empty())),
|
||||
(
|
||||
"installs",
|
||||
Json::Arr(installs.iter().map(|i| i.to_json()).collect()),
|
||||
),
|
||||
(
|
||||
"bottle_dir_preference",
|
||||
Json::opt_str(crossover::preference("BottleDir")),
|
||||
),
|
||||
(
|
||||
"managed_bottle_dirs_preference",
|
||||
Json::opt_str(crossover::preference("ManagedBottleDirs")),
|
||||
),
|
||||
(
|
||||
"searched",
|
||||
Json::Arr(
|
||||
cands
|
||||
.iter()
|
||||
.map(|p| Json::str(p.display().to_string()))
|
||||
.collect(),
|
||||
),
|
||||
),
|
||||
(
|
||||
"note",
|
||||
Json::str(
|
||||
"Only Info.plist metadata, lipo -archs and documented defaults keys are read. Bottle graphics backend and bundle internals are not interpreted (undocumented, #350).",
|
||||
),
|
||||
),
|
||||
])
|
||||
}
|
||||
|
||||
fn toolchain_json() -> Json {
|
||||
let path = std::env::var("PATH").unwrap_or_default();
|
||||
Json::Arr(
|
||||
toolchain::probe(&path)
|
||||
.iter()
|
||||
.map(|c| c.to_json())
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
fn guard(args: &[String]) -> ExitCode {
|
||||
let mut limits = memory::Limits {
|
||||
min_start_free: 70,
|
||||
min_free: 20,
|
||||
poll: std::time::Duration::from_secs(1),
|
||||
grace: std::time::Duration::from_secs(10),
|
||||
};
|
||||
let mut i = 0;
|
||||
while i < args.len() && args[i] != "--" {
|
||||
let v = args.get(i + 1).and_then(|v| v.parse::<u8>().ok());
|
||||
match (args[i].as_str(), v) {
|
||||
("--min-start-free", Some(v)) => limits.min_start_free = v,
|
||||
("--min-free", Some(v)) => limits.min_free = v,
|
||||
_ => {
|
||||
eprintln!("{USAGE}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
}
|
||||
i += 2;
|
||||
}
|
||||
let Some(cmd) = args.get(i + 1) else {
|
||||
eprintln!("{USAGE}");
|
||||
return ExitCode::from(2);
|
||||
};
|
||||
match memory::supervise(cmd, &args[i + 2..], limits, &mut memory::free_percentage) {
|
||||
memory::Outcome::Exited(Some(0)) => ExitCode::SUCCESS,
|
||||
memory::Outcome::Exited(c) => ExitCode::from(c.map_or(1, |c| c.clamp(1, 255)) as u8),
|
||||
other => {
|
||||
eprintln!("guard: {other:?}");
|
||||
ExitCode::from(3)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct RunArgs {
|
||||
cfg: run::RunConfig,
|
||||
backends: Vec<String>,
|
||||
repeat: u32,
|
||||
out: Option<PathBuf>,
|
||||
}
|
||||
|
||||
fn parse_run_args(args: &[String]) -> Result<RunArgs, String> {
|
||||
let mut bottle = None;
|
||||
let mut backend = None;
|
||||
let mut backends = Vec::new();
|
||||
let mut repeat = 1u32;
|
||||
let mut timeout = 300u64;
|
||||
let mut stall = None;
|
||||
let mut settle = 60u64;
|
||||
let mut expect = None;
|
||||
let mut out = None;
|
||||
let (mut min_start, mut min_free) = (50u8, 15u8);
|
||||
let mut i = 0;
|
||||
while i < args.len() && args[i] != "--" {
|
||||
let v = args
|
||||
.get(i + 1)
|
||||
.ok_or_else(|| format!("{} needs a value", args[i]))?
|
||||
.clone();
|
||||
match args[i].as_str() {
|
||||
"--bottle" => bottle = Some(v),
|
||||
"--backend" => backend = Some(v),
|
||||
"--backends" => backends = v.split(',').map(String::from).collect(),
|
||||
"--repeat" => repeat = v.parse().map_err(|_| "bad --repeat")?,
|
||||
"--timeout" => timeout = v.parse().map_err(|_| "bad --timeout")?,
|
||||
"--stall-timeout" => stall = Some(v.parse().map_err(|_| "bad --stall-timeout")?),
|
||||
"--settle-bound" => settle = v.parse().map_err(|_| "bad --settle-bound")?,
|
||||
"--expect" => expect = Some(v),
|
||||
"--out" => out = Some(PathBuf::from(v)),
|
||||
"--min-start-free" => min_start = v.parse().map_err(|_| "bad --min-start-free")?,
|
||||
"--min-free" => min_free = v.parse().map_err(|_| "bad --min-free")?,
|
||||
o => return Err(format!("unknown option {o}")),
|
||||
}
|
||||
i += 2;
|
||||
}
|
||||
let program = args.get(i + 1).ok_or("missing program after --")?.clone();
|
||||
let home = PathBuf::from(std::env::var("HOME").unwrap_or_default());
|
||||
let installs = crossover::discover(&crossover::candidate_paths(&home));
|
||||
let install = installs.first().ok_or("no CrossOver installation found")?;
|
||||
let wine = run::wine_path(&install.path);
|
||||
if !wine.is_file() {
|
||||
return Err(format!(
|
||||
"{} not found in this CrossOver build",
|
||||
wine.display()
|
||||
));
|
||||
}
|
||||
let work = out
|
||||
.clone()
|
||||
.unwrap_or_else(|| PathBuf::from("artifacts/hybrid-runs"));
|
||||
Ok(RunArgs {
|
||||
cfg: run::RunConfig {
|
||||
wine,
|
||||
bottle: bottle.ok_or("--bottle is required")?,
|
||||
backend,
|
||||
program,
|
||||
args: args[i + 2..].to_vec(),
|
||||
timeout: std::time::Duration::from_secs(timeout),
|
||||
limits: memory::Limits {
|
||||
min_start_free: min_start,
|
||||
min_free,
|
||||
poll: std::time::Duration::from_millis(250),
|
||||
grace: std::time::Duration::from_secs(10),
|
||||
},
|
||||
expect,
|
||||
work_dir: work,
|
||||
stall_timeout: stall.map(std::time::Duration::from_secs),
|
||||
settle_bound: std::time::Duration::from_secs(settle),
|
||||
read_free: memory::free_percentage,
|
||||
},
|
||||
backends,
|
||||
repeat,
|
||||
out,
|
||||
})
|
||||
}
|
||||
|
||||
fn crossover_build() -> Option<String> {
|
||||
let home = PathBuf::from(std::env::var("HOME").unwrap_or_default());
|
||||
crossover::discover(&crossover::candidate_paths(&home))
|
||||
.first()
|
||||
.and_then(|i| {
|
||||
Some(format!(
|
||||
"{} ({})",
|
||||
i.short_version.clone()?,
|
||||
i.build_version.clone()?
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
fn save(dir: &std::path::Path, name: &str, j: &Json) {
|
||||
let _ = std::fs::create_dir_all(dir);
|
||||
let _ = std::fs::write(dir.join(name), j.render());
|
||||
}
|
||||
|
||||
fn run_cmd(args: &[String]) -> ExitCode {
|
||||
let a = match parse_run_args(args) {
|
||||
Ok(a) => a,
|
||||
Err(e) => {
|
||||
eprintln!("{e}\n{USAGE}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
};
|
||||
let r = run::execute(&a.cfg, crossover_build());
|
||||
print!("{}", r.json.render());
|
||||
if let Some(dir) = &a.out {
|
||||
save(
|
||||
dir,
|
||||
&format!(
|
||||
"run-{}.json",
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map_or(0, |d| d.as_secs())
|
||||
),
|
||||
&r.json,
|
||||
);
|
||||
}
|
||||
if r.class == run::Class::Passed {
|
||||
ExitCode::SUCCESS
|
||||
} else {
|
||||
ExitCode::from(1)
|
||||
}
|
||||
}
|
||||
|
||||
fn bench_cmd(args: &[String]) -> ExitCode {
|
||||
let a = match parse_run_args(args) {
|
||||
Ok(a) if !a.backends.is_empty() => a,
|
||||
Ok(_) => {
|
||||
eprintln!("bench needs --backends\n{USAGE}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("{e}\n{USAGE}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
};
|
||||
let build = crossover_build();
|
||||
let mut per_backend = Vec::new();
|
||||
let mut all_ok = true;
|
||||
for b in &a.backends {
|
||||
let mut runs = Vec::new();
|
||||
for _ in 0..a.repeat {
|
||||
let mut cfg = a.cfg.clone();
|
||||
cfg.backend = if b == "default" {
|
||||
None
|
||||
} else {
|
||||
Some(b.clone())
|
||||
};
|
||||
let r = run::execute(&cfg, build.clone());
|
||||
all_ok &= r.class == run::Class::Passed;
|
||||
runs.push(r.json);
|
||||
}
|
||||
per_backend.push(Json::obj(vec![
|
||||
("backend", Json::str(b.clone())),
|
||||
("runs", Json::Arr(runs)),
|
||||
]));
|
||||
}
|
||||
let doc = Json::obj(vec![
|
||||
("schema", Json::str("betterxen-hybrid-bench/0")),
|
||||
("repeat", Json::Num(a.repeat as f64)),
|
||||
("host", host::collect().to_json()),
|
||||
("results", Json::Arr(per_backend)),
|
||||
]);
|
||||
print!("{}", doc.render());
|
||||
if let Some(dir) = &a.out {
|
||||
save(dir, "bench.json", &doc);
|
||||
}
|
||||
if all_ok {
|
||||
ExitCode::SUCCESS
|
||||
} else {
|
||||
ExitCode::from(1)
|
||||
}
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
match std::env::args().nth(1).as_deref() {
|
||||
Some("run") => return run_cmd(&std::env::args().skip(2).collect::<Vec<_>>()),
|
||||
Some("bench") => return bench_cmd(&std::env::args().skip(2).collect::<Vec<_>>()),
|
||||
_ => {}
|
||||
}
|
||||
if std::env::args().nth(1).as_deref() == Some("guard") {
|
||||
return guard(&std::env::args().skip(2).collect::<Vec<_>>());
|
||||
}
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
let result: Result<Json, String> = match args.first().map(String::as_str) {
|
||||
Some("host") => Ok(host::collect().to_json()),
|
||||
Some("crossover") => {
|
||||
let app = match args.get(1).map(String::as_str) {
|
||||
Some("--app") => args.get(2).map(PathBuf::from),
|
||||
_ => None,
|
||||
};
|
||||
Ok(crossover_json(app))
|
||||
}
|
||||
Some("toolchain") => Ok(toolchain_json()),
|
||||
Some("frames") => match args.get(1) {
|
||||
None => Err("frames needs a file".into()),
|
||||
Some(f) => std::fs::read_to_string(f)
|
||||
.map_err(|e| format!("{f}: {e}"))
|
||||
.and_then(|t| frames::parse_intervals(&t).map_err(|e| e.to_string()))
|
||||
.and_then(|v| frames::analyze(&v).map_err(|e| e.to_string()))
|
||||
.map(|s| s.to_json()),
|
||||
},
|
||||
Some("receipt") => Ok(Json::obj(vec![
|
||||
("schema", Json::str("betterxen-hybrid-receipt/0")),
|
||||
("host", host::collect().to_json()),
|
||||
("crossover", crossover_json(None)),
|
||||
("windows_cross_compilers", toolchain_json()),
|
||||
])),
|
||||
_ => Err(USAGE.into()),
|
||||
};
|
||||
match result {
|
||||
Ok(j) => {
|
||||
print!("{}", j.render());
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("{e}");
|
||||
ExitCode::from(2)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
//! Memory-pressure supervision of a child process.
|
||||
//!
|
||||
//! Adapted in concept from the memory guard in `mac/run-victory.sh` of
|
||||
//! <https://github.com/skakwy/victory-mac> (author skakwy, GPL-3.0; commit 22b3f8e, used with
|
||||
//! the author's permission): do not start a workload when little memory is free, and stop it
|
||||
//! when system-wide free memory falls below a limit, because GPU memory is wired under
|
||||
//! unified memory and a runaway workload can take the whole Mac down. This version is
|
||||
//! reimplemented in Rust, stops the child with SIGTERM before SIGKILL, and reports why it
|
||||
//! stopped. It supervises any command; it contains nothing game-specific.
|
||||
//!
|
||||
//! The reading is the "System-wide memory free percentage" line of `memory_pressure -Q`.
|
||||
//! That line was observed on macOS 27.0 (build 26A428); its format is not a documented
|
||||
//! stable interface, so an unreadable value is an error, never "assume enough memory".
|
||||
|
||||
use crate::cmdutil::run;
|
||||
use std::process::{Child, Command};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
pub fn parse_free_percentage(output: &str) -> Option<u8> {
|
||||
let line = output
|
||||
.lines()
|
||||
.find(|l| l.contains("System-wide memory free percentage"))?;
|
||||
let digits: String = line
|
||||
.split(':')
|
||||
.nth(1)?
|
||||
.trim()
|
||||
.chars()
|
||||
.take_while(|c| c.is_ascii_digit())
|
||||
.collect();
|
||||
let v: u8 = digits.parse().ok()?;
|
||||
(v <= 100).then_some(v)
|
||||
}
|
||||
|
||||
pub fn free_percentage() -> Option<u8> {
|
||||
run("/usr/bin/memory_pressure", &["-Q"]).and_then(|o| parse_free_percentage(&o))
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct Limits {
|
||||
/// Refuse to start below this percent free.
|
||||
pub min_start_free: u8,
|
||||
/// Stop the child when free memory drops below this percent.
|
||||
pub min_free: u8,
|
||||
pub poll: Duration,
|
||||
/// Time between SIGTERM and SIGKILL.
|
||||
pub grace: Duration,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum Outcome {
|
||||
/// The child ran to completion; `None` means it ended by a signal.
|
||||
Exited(Option<i32>),
|
||||
RefusedToStart {
|
||||
free: u8,
|
||||
need: u8,
|
||||
},
|
||||
StoppedLowMemory {
|
||||
free: u8,
|
||||
limit: u8,
|
||||
},
|
||||
/// Memory could not be read, so no guarantee can be given.
|
||||
MemoryUnreadable,
|
||||
SpawnFailed(String),
|
||||
}
|
||||
|
||||
pub(crate) fn terminate(child: &mut Child, grace: Duration) {
|
||||
let _ = Command::new("/bin/kill")
|
||||
.args(["-TERM", &child.id().to_string()])
|
||||
.status();
|
||||
let t0 = Instant::now();
|
||||
while t0.elapsed() < grace {
|
||||
if matches!(child.try_wait(), Ok(Some(_))) {
|
||||
return;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
}
|
||||
|
||||
/// Run `program` under `limits`, reading memory through `read_free`.
|
||||
pub fn supervise(
|
||||
program: &str,
|
||||
args: &[String],
|
||||
limits: Limits,
|
||||
read_free: &mut dyn FnMut() -> Option<u8>,
|
||||
) -> Outcome {
|
||||
match read_free() {
|
||||
None => return Outcome::MemoryUnreadable,
|
||||
Some(free) if free < limits.min_start_free => {
|
||||
return Outcome::RefusedToStart {
|
||||
free,
|
||||
need: limits.min_start_free,
|
||||
};
|
||||
}
|
||||
Some(_) => {}
|
||||
}
|
||||
let mut child = match Command::new(program).args(args).spawn() {
|
||||
Ok(c) => c,
|
||||
Err(e) => return Outcome::SpawnFailed(format!("{program}: {e}")),
|
||||
};
|
||||
loop {
|
||||
match child.try_wait() {
|
||||
Ok(Some(status)) => return Outcome::Exited(status.code()),
|
||||
Ok(None) => {}
|
||||
Err(e) => return Outcome::SpawnFailed(e.to_string()),
|
||||
}
|
||||
match read_free() {
|
||||
None => {
|
||||
terminate(&mut child, limits.grace);
|
||||
return Outcome::MemoryUnreadable;
|
||||
}
|
||||
Some(free) if free < limits.min_free => {
|
||||
terminate(&mut child, limits.grace);
|
||||
return Outcome::StoppedLowMemory {
|
||||
free,
|
||||
limit: limits.min_free,
|
||||
};
|
||||
}
|
||||
Some(_) => {}
|
||||
}
|
||||
std::thread::sleep(limits.poll);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn limits() -> Limits {
|
||||
Limits {
|
||||
min_start_free: 50,
|
||||
min_free: 20,
|
||||
poll: Duration::from_millis(20),
|
||||
grace: Duration::from_millis(500),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_memory_pressure_output() {
|
||||
let real = "The system has 25769803776 (1572864 pages with a page size of 16384).\nSystem-wide memory free percentage: 71%\n";
|
||||
assert_eq!(parse_free_percentage(real), Some(71));
|
||||
assert_eq!(
|
||||
parse_free_percentage("System-wide memory free percentage: 100%"),
|
||||
Some(100)
|
||||
);
|
||||
assert_eq!(
|
||||
parse_free_percentage("System-wide memory free percentage: 101%"),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
parse_free_percentage("System-wide memory free percentage: x"),
|
||||
None
|
||||
);
|
||||
assert_eq!(parse_free_percentage("nothing"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_to_start_when_low() {
|
||||
let out = supervise("/usr/bin/true", &[], limits(), &mut || Some(30));
|
||||
assert_eq!(out, Outcome::RefusedToStart { free: 30, need: 50 });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unreadable_memory_is_an_error() {
|
||||
assert_eq!(
|
||||
supervise("/usr/bin/true", &[], limits(), &mut || None),
|
||||
Outcome::MemoryUnreadable
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn child_exit_code_is_reported() {
|
||||
let out = supervise(
|
||||
"/bin/sh",
|
||||
&["-c".into(), "exit 7".into()],
|
||||
limits(),
|
||||
&mut || Some(90),
|
||||
);
|
||||
assert_eq!(out, Outcome::Exited(Some(7)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stops_child_when_memory_drops() {
|
||||
let mut calls = 0;
|
||||
let t0 = Instant::now();
|
||||
let out = supervise("/bin/sleep", &["30".into()], limits(), &mut || {
|
||||
calls += 1;
|
||||
Some(if calls < 4 { 90 } else { 10 })
|
||||
});
|
||||
assert_eq!(
|
||||
out,
|
||||
Outcome::StoppedLowMemory {
|
||||
free: 10,
|
||||
limit: 20
|
||||
}
|
||||
);
|
||||
assert!(
|
||||
t0.elapsed() < Duration::from_secs(10),
|
||||
"child was not stopped promptly"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn real_reading_is_available_on_macos() {
|
||||
if cfg!(target_os = "macos") {
|
||||
assert!(free_percentage().is_some());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,685 @@
|
||||
//! Launch a Windows program through an installed CrossOver, supervise it, and write a
|
||||
//! structured record of what happened.
|
||||
//!
|
||||
//! Interface used: `<CrossOver.app>/Contents/SharedSupport/CrossOver/bin/wine --bottle B EXE`
|
||||
//! and `.../bin/wineserver -k`. These are **not documented by CodeWeavers** for macOS; they
|
||||
//! exist in the installed build and answer `--help` (cxbottle, cxstart) as observed on build
|
||||
//! 26.3.0.39832. Every record therefore carries the CrossOver build and a flag saying the
|
||||
//! launcher interface is vendor-help-only. The graphics backend is selected through the
|
||||
//! `CX_GRAPHICS_BACKEND` environment variable, which appears in third-party launch scripts and
|
||||
//! is likewise undocumented; an unrecognised value was observed to be ignored silently, so a
|
||||
//!
|
||||
//! Stall detection and the wait for memory to settle after a stop follow the supervision
|
||||
//! lessons in skakwy's <https://github.com/skakwy/victory-mac> (`mac/PROGRESS.md`,
|
||||
//! `mac/run-victory.sh`, `crates/victory-core/src/notes.rs` at commit 22b3f8e45a59; his own
|
||||
//! work, GPL-3.0, used with his permission): detect a hung run by absence of progress, stop a
|
||||
//! bottle with `wineserver -k` and its prefix, and do not start the next run until memory has
|
||||
//! been returned. Reimplemented here; none of his code is copied.
|
||||
//!
|
||||
//! A record names the backend *requested* and relies on the workload's own diagnostics
|
||||
//! (adapter name, backend log lines) to show what actually ran.
|
||||
|
||||
use crate::frames;
|
||||
use crate::json::Json;
|
||||
use crate::memory;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RunConfig {
|
||||
pub wine: PathBuf,
|
||||
pub bottle: String,
|
||||
pub backend: Option<String>,
|
||||
pub program: String,
|
||||
pub args: Vec<String>,
|
||||
pub timeout: Duration,
|
||||
pub limits: memory::Limits,
|
||||
/// Text that must appear in stdout for a zero exit to count as a pass.
|
||||
pub expect: Option<String>,
|
||||
pub work_dir: PathBuf,
|
||||
/// Stop the run when neither stdout nor stderr has grown for this long.
|
||||
pub stall_timeout: Option<Duration>,
|
||||
/// After a stop, wait at most this long for free memory to return to `min_start_free`.
|
||||
pub settle_bound: Duration,
|
||||
/// Free-memory reader; `memory::free_percentage` outside tests.
|
||||
pub read_free: fn() -> Option<u8>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum Class {
|
||||
Passed,
|
||||
FailedExit(i32),
|
||||
MissingExpectedMarker,
|
||||
TimedOut,
|
||||
/// No output on stdout or stderr for the stall timeout.
|
||||
Stalled,
|
||||
StoppedLowMemory,
|
||||
RefusedToStart,
|
||||
/// The Windows loader did not accept the file (for example an ARM64 PE this build cannot run).
|
||||
CannotExecute,
|
||||
/// The workload reported that no graphics device could be created.
|
||||
NoDevice,
|
||||
MemoryUnreadable,
|
||||
LaunchFailed,
|
||||
}
|
||||
|
||||
impl Class {
|
||||
pub fn name(&self) -> String {
|
||||
match self {
|
||||
Class::Passed => "passed".into(),
|
||||
Class::FailedExit(c) => format!("failed_exit_{c}"),
|
||||
Class::MissingExpectedMarker => "missing_expected_marker".into(),
|
||||
Class::TimedOut => "timed_out".into(),
|
||||
Class::Stalled => "stalled".into(),
|
||||
Class::StoppedLowMemory => "stopped_low_memory".into(),
|
||||
Class::RefusedToStart => "refused_to_start_low_memory".into(),
|
||||
Class::CannotExecute => "cannot_execute".into(),
|
||||
Class::NoDevice => "no_graphics_device".into(),
|
||||
Class::MemoryUnreadable => "memory_unreadable".into(),
|
||||
Class::LaunchFailed => "launch_failed".into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Classify a finished (or stopped) run from observable facts only.
|
||||
pub fn classify(exit: Option<i32>, stdout: &str, stderr: &str, expect: Option<&str>) -> Class {
|
||||
if stderr.contains("cannot execute") {
|
||||
return Class::CannotExecute;
|
||||
}
|
||||
if stdout.contains("NO DEVICE") && exit == Some(2) {
|
||||
return Class::NoDevice;
|
||||
}
|
||||
match exit {
|
||||
Some(0) => match expect {
|
||||
Some(m) if !stdout.contains(m) => Class::MissingExpectedMarker,
|
||||
_ => Class::Passed,
|
||||
},
|
||||
Some(c) => Class::FailedExit(c),
|
||||
None => Class::FailedExit(-1),
|
||||
}
|
||||
}
|
||||
|
||||
/// Known host-environment noise in CrossOver output, reported as diagnostics instead of
|
||||
/// silently dropped. Returns (kind, line) for each recognised line.
|
||||
pub fn diagnostics(text: &str) -> Vec<(&'static str, String)> {
|
||||
let mut out = Vec::new();
|
||||
for line in text.lines() {
|
||||
if line.contains("LibClamAV Error") || line.contains("Can't open file or directory") {
|
||||
out.push(("clamav-database-missing", line.to_string()));
|
||||
} else if line.starts_with("warn:") && line.contains("DXVK") {
|
||||
out.push(("dxvk-warning", line.to_string()));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Which graphics layer announced itself, judged from the workload's stdout and stderr.
|
||||
pub fn detected_backend(output: &str) -> &'static str {
|
||||
if output.contains("DXVK:") {
|
||||
"dxvk"
|
||||
} else if output.contains("DXMT") || output.contains("D3D_FEATURE_LEVEL_11_1\ninfo: Using") {
|
||||
"dxmt"
|
||||
} else if output.contains("adapter=AMD Compatibility Mode") {
|
||||
"d3dmetal (inferred: Apple-reported adapter identity)"
|
||||
} else if output.contains("adapter=Apple M") {
|
||||
"wined3d (inferred: native adapter name, no layer banner)"
|
||||
} else {
|
||||
"unknown"
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct Samples {
|
||||
pub peak_rss_kb: u64,
|
||||
pub mean_cpu_percent_of_core: f64,
|
||||
pub min_free_percent: Option<u8>,
|
||||
pub samples: u32,
|
||||
}
|
||||
|
||||
/// Sum RSS (KB) and CPU % of processes whose command line mentions the CrossOver bundle or the
|
||||
/// bottle directory. Heuristic: processes not started from those paths are not counted.
|
||||
fn sample_processes(needles: &[String]) -> (u64, f64) {
|
||||
let Some(out) = crate::cmdutil::run("/bin/ps", &["-axo", "rss=,pcpu=,command="]) else {
|
||||
return (0, 0.0);
|
||||
};
|
||||
let (mut rss, mut cpu) = (0u64, 0f64);
|
||||
for l in out.lines() {
|
||||
if !needles.iter().any(|n| l.contains(n.as_str())) {
|
||||
continue;
|
||||
}
|
||||
let mut it = l.split_whitespace();
|
||||
rss += it.next().and_then(|v| v.parse::<u64>().ok()).unwrap_or(0);
|
||||
cpu += it.next().and_then(|v| v.parse::<f64>().ok()).unwrap_or(0.0);
|
||||
}
|
||||
(rss, cpu)
|
||||
}
|
||||
|
||||
fn thermal() -> Json {
|
||||
match crate::cmdutil::run("/usr/bin/pmset", &["-g", "therm"]) {
|
||||
Some(t) => Json::Arr(
|
||||
t.lines()
|
||||
.map(|l| Json::str(l.trim()))
|
||||
.filter(|j| *j != Json::str(""))
|
||||
.collect(),
|
||||
),
|
||||
None => Json::Null,
|
||||
}
|
||||
}
|
||||
|
||||
pub struct RunRecord {
|
||||
pub class: Class,
|
||||
pub duration: Duration,
|
||||
pub exit: Option<i32>,
|
||||
pub stdout: String,
|
||||
pub stderr: String,
|
||||
pub samples: Samples,
|
||||
pub json: Json,
|
||||
}
|
||||
|
||||
pub fn execute(cfg: &RunConfig, crossover_build: Option<String>) -> RunRecord {
|
||||
let t_wall = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map_or(0, |d| d.as_secs());
|
||||
let _ = std::fs::create_dir_all(&cfg.work_dir);
|
||||
let out_path = cfg
|
||||
.work_dir
|
||||
.join(format!("stdout-{t_wall}-{}.txt", std::process::id()));
|
||||
let err_path = cfg
|
||||
.work_dir
|
||||
.join(format!("stderr-{t_wall}-{}.txt", std::process::id()));
|
||||
let mut settle: Option<(Duration, bool)> = None;
|
||||
let thermal_before = thermal();
|
||||
let free_start = (cfg.read_free)();
|
||||
|
||||
let mut result = RunRecord {
|
||||
class: Class::LaunchFailed,
|
||||
duration: Duration::ZERO,
|
||||
exit: None,
|
||||
stdout: String::new(),
|
||||
stderr: String::new(),
|
||||
samples: Samples::default(),
|
||||
json: Json::Null,
|
||||
};
|
||||
|
||||
match free_start {
|
||||
None => result.class = Class::MemoryUnreadable,
|
||||
Some(f) if f < cfg.limits.min_start_free => result.class = Class::RefusedToStart,
|
||||
Some(_) => {
|
||||
let files = std::fs::File::create(&out_path)
|
||||
.and_then(|o| std::fs::File::create(&err_path).map(|e| (o, e)));
|
||||
if let Ok((o, e)) = files {
|
||||
let mut cmd = Command::new(&cfg.wine);
|
||||
cmd.arg("--bottle")
|
||||
.arg(&cfg.bottle)
|
||||
.arg(&cfg.program)
|
||||
.args(&cfg.args);
|
||||
cmd.stdout(Stdio::from(o)).stderr(Stdio::from(e));
|
||||
if let Some(b) = &cfg.backend {
|
||||
cmd.env("CX_GRAPHICS_BACKEND", b);
|
||||
}
|
||||
let started = Instant::now();
|
||||
if let Ok(mut child) = cmd.spawn() {
|
||||
let bundle = cfg
|
||||
.wine
|
||||
.to_string_lossy()
|
||||
.split("/Contents/")
|
||||
.next()
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
let needles = vec![bundle, format!("Bottles/{}", cfg.bottle)];
|
||||
let (mut cpu_sum, mut n) = (0f64, 0u32);
|
||||
let mut stop: Option<Class> = None;
|
||||
let mut last_len = 0u64;
|
||||
let mut last_growth = Instant::now();
|
||||
loop {
|
||||
match child.try_wait() {
|
||||
Ok(Some(st)) => {
|
||||
result.exit = st.code();
|
||||
break;
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(_) => break,
|
||||
}
|
||||
let (rss, cpu) = sample_processes(&needles);
|
||||
result.samples.peak_rss_kb = result.samples.peak_rss_kb.max(rss);
|
||||
cpu_sum += cpu;
|
||||
n += 1;
|
||||
match (cfg.read_free)() {
|
||||
Some(f) => {
|
||||
let m = result.samples.min_free_percent.map_or(f, |x| x.min(f));
|
||||
result.samples.min_free_percent = Some(m);
|
||||
if f < cfg.limits.min_free {
|
||||
stop = Some(Class::StoppedLowMemory);
|
||||
}
|
||||
}
|
||||
None => stop = Some(Class::MemoryUnreadable),
|
||||
}
|
||||
let len = [&out_path, &err_path]
|
||||
.iter()
|
||||
.map(|p| std::fs::metadata(p).map_or(0, |m| m.len()))
|
||||
.sum::<u64>();
|
||||
if len != last_len {
|
||||
last_len = len;
|
||||
last_growth = Instant::now();
|
||||
}
|
||||
if stop.is_none() && started.elapsed() > cfg.timeout {
|
||||
stop = Some(Class::TimedOut);
|
||||
}
|
||||
if stop.is_none()
|
||||
&& cfg.stall_timeout.is_some_and(|d| last_growth.elapsed() > d)
|
||||
{
|
||||
stop = Some(Class::Stalled);
|
||||
}
|
||||
if stop.is_some() {
|
||||
memory::terminate(&mut child, cfg.limits.grace);
|
||||
stop_bottle(&cfg.wine, &cfg.bottle);
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(cfg.limits.poll);
|
||||
}
|
||||
result.duration = started.elapsed();
|
||||
if stop.is_some() {
|
||||
let t = Instant::now();
|
||||
let need = cfg.limits.min_start_free;
|
||||
let mut recovered = false;
|
||||
loop {
|
||||
if (cfg.read_free)().is_some_and(|f| f >= need) {
|
||||
recovered = true;
|
||||
break;
|
||||
}
|
||||
if t.elapsed() >= cfg.settle_bound {
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(cfg.limits.poll);
|
||||
}
|
||||
settle = Some((t.elapsed(), recovered));
|
||||
}
|
||||
result.samples.samples = n;
|
||||
result.samples.mean_cpu_percent_of_core =
|
||||
if n > 0 { cpu_sum / n as f64 } else { 0.0 };
|
||||
result.stdout = std::fs::read_to_string(&out_path).unwrap_or_default();
|
||||
result.stderr = std::fs::read_to_string(&err_path).unwrap_or_default();
|
||||
result.class = stop.unwrap_or_else(|| {
|
||||
classify(
|
||||
result.exit,
|
||||
&result.stdout,
|
||||
&result.stderr,
|
||||
cfg.expect.as_deref(),
|
||||
)
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let intervals: Vec<f64> = result
|
||||
.stdout
|
||||
.lines()
|
||||
.filter_map(|l| l.strip_prefix("frame_ms "))
|
||||
.filter_map(|v| v.trim().parse().ok())
|
||||
.collect();
|
||||
let frame_stats = frames::analyze(&intervals).ok().map(|s| s.to_json());
|
||||
let combined = format!("{}\n{}", result.stdout, result.stderr);
|
||||
let diags: Vec<Json> = diagnostics(&combined)
|
||||
.into_iter()
|
||||
.map(|(k, l)| Json::obj(vec![("kind", Json::str(k)), ("line", Json::str(l))]))
|
||||
.collect();
|
||||
let tail = |s: &str| -> Json {
|
||||
let lines: Vec<&str> = s.lines().filter(|l| !l.starts_with("frame_ms ")).collect();
|
||||
let keep = if lines.len() > 40 {
|
||||
&lines[lines.len() - 40..]
|
||||
} else {
|
||||
&lines[..]
|
||||
};
|
||||
Json::Arr(keep.iter().map(|l| Json::str(*l)).collect())
|
||||
};
|
||||
result.json = Json::obj(vec![
|
||||
("schema", Json::str("betterxen-hybrid-run/0")),
|
||||
("unix_time", Json::Num(t_wall as f64)),
|
||||
("crossover_build", Json::opt_str(crossover_build)),
|
||||
(
|
||||
"launcher_interface",
|
||||
Json::str(
|
||||
"CrossOver bin/wine --bottle (vendor --help only; not documented by CodeWeavers for macOS)",
|
||||
),
|
||||
),
|
||||
("bottle", Json::str(cfg.bottle.clone())),
|
||||
("backend_requested", Json::opt_str(cfg.backend.clone())),
|
||||
("backend_variable_documented", Json::Bool(false)),
|
||||
("backend_detected", Json::str(detected_backend(&combined))),
|
||||
("program", Json::str(cfg.program.clone())),
|
||||
(
|
||||
"args",
|
||||
Json::Arr(cfg.args.iter().map(|a| Json::str(a.clone())).collect()),
|
||||
),
|
||||
("classification", Json::str(result.class.name())),
|
||||
(
|
||||
"exit_code",
|
||||
result.exit.map_or(Json::Null, |c| Json::Num(c as f64)),
|
||||
),
|
||||
(
|
||||
"duration_ms",
|
||||
Json::Num(result.duration.as_secs_f64() * 1000.0),
|
||||
),
|
||||
("timeout_s", Json::Num(cfg.timeout.as_secs_f64())),
|
||||
(
|
||||
"stall_timeout_s",
|
||||
cfg.stall_timeout
|
||||
.map_or(Json::Null, |d| Json::Num(d.as_secs_f64())),
|
||||
),
|
||||
(
|
||||
"memory_settle_after_stop",
|
||||
settle.map_or(Json::Null, |(d, ok)| {
|
||||
Json::obj(vec![
|
||||
("waited_ms", Json::Num(d.as_secs_f64() * 1000.0)),
|
||||
("recovered_to_start_threshold", Json::Bool(ok)),
|
||||
("bound_s", Json::Num(cfg.settle_bound.as_secs_f64())),
|
||||
])
|
||||
}),
|
||||
),
|
||||
(
|
||||
"free_memory_percent_at_start",
|
||||
free_start.map_or(Json::Null, |f| Json::Num(f as f64)),
|
||||
),
|
||||
(
|
||||
"min_free_memory_percent_during_run",
|
||||
result
|
||||
.samples
|
||||
.min_free_percent
|
||||
.map_or(Json::Null, |f| Json::Num(f as f64)),
|
||||
),
|
||||
(
|
||||
"peak_crossover_rss_kb_sampled",
|
||||
Json::Num(result.samples.peak_rss_kb as f64),
|
||||
),
|
||||
(
|
||||
"mean_crossover_cpu_percent_of_one_core_sampled",
|
||||
Json::Num(result.samples.mean_cpu_percent_of_core),
|
||||
),
|
||||
("process_samples", Json::Num(result.samples.samples as f64)),
|
||||
(
|
||||
"gpu_utilization",
|
||||
Json::str("not collected: no unprivileged documented source on this host"),
|
||||
),
|
||||
("thermal_before", thermal_before),
|
||||
("thermal_after", thermal()),
|
||||
("diagnostics", Json::Arr(diags)),
|
||||
("frame_stats", frame_stats.unwrap_or(Json::Null)),
|
||||
("stdout_tail", tail(&result.stdout)),
|
||||
("stderr_tail", tail(&result.stderr)),
|
||||
]);
|
||||
let _ = std::fs::remove_file(&out_path);
|
||||
let _ = std::fs::remove_file(&err_path);
|
||||
result
|
||||
}
|
||||
|
||||
/// Prefix directory of a bottle. CrossOver documents `BottleDir` in its preferences; otherwise
|
||||
/// the default location under Application Support is used.
|
||||
pub fn bottle_prefix(bottle: &str) -> PathBuf {
|
||||
let base = crate::crossover::preference("BottleDir")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| {
|
||||
PathBuf::from(std::env::var("HOME").unwrap_or_default())
|
||||
.join("Library/Application Support/CrossOver/Bottles")
|
||||
});
|
||||
base.join(bottle)
|
||||
}
|
||||
|
||||
/// Stop every process of one bottle with `wineserver -k`, selecting the bottle through
|
||||
/// `WINEPREFIX`. Setting `CX_BOTTLE` instead was tried first and observed NOT to select the
|
||||
/// bottle: the Windows process kept running after the supervisor reported it stopped.
|
||||
pub fn stop_bottle(wine: &Path, bottle: &str) {
|
||||
if let Some(dir) = wine.parent() {
|
||||
let _ = Command::new(dir.join("wineserver"))
|
||||
.arg("-k")
|
||||
.env("WINEPREFIX", bottle_prefix(bottle))
|
||||
.status();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn wine_path(app: &Path) -> PathBuf {
|
||||
app.join("Contents/SharedSupport/CrossOver/bin/wine")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn classifies_from_observed_facts() {
|
||||
assert_eq!(classify(Some(0), "PASS", "", Some("PASS")), Class::Passed);
|
||||
assert_eq!(
|
||||
classify(Some(0), "ok", "", Some("PASS")),
|
||||
Class::MissingExpectedMarker
|
||||
);
|
||||
assert_eq!(classify(Some(0), "", "", None), Class::Passed);
|
||||
assert_eq!(classify(Some(1), "FAIL", "", None), Class::FailedExit(1));
|
||||
assert_eq!(
|
||||
classify(Some(2), "NO DEVICE hr=0x1", "", None),
|
||||
Class::NoDevice
|
||||
);
|
||||
assert_eq!(classify(Some(2), "other", "", None), Class::FailedExit(2));
|
||||
assert_eq!(
|
||||
classify(
|
||||
Some(1),
|
||||
"",
|
||||
"winewrapper.exe:error: cannot execute L\"a.exe\"",
|
||||
None
|
||||
),
|
||||
Class::CannotExecute
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recognises_noise_and_backends() {
|
||||
let d = diagnostics(
|
||||
"LibClamAV Error: x\nERROR: Can't open file or directory\nwarn: DXVK: No state cache\nfine",
|
||||
);
|
||||
assert_eq!(d.len(), 3);
|
||||
assert_eq!(d[0].0, "clamav-database-missing");
|
||||
assert!(detected_backend("info: DXVK: cxaddon\nadapter=Apple M4").starts_with("dxvk"));
|
||||
assert!(detected_backend("adapter=AMD Compatibility Mode").starts_with("d3dmetal"));
|
||||
assert_eq!(detected_backend("nothing"), "unknown");
|
||||
}
|
||||
|
||||
fn stub(dir: &Path, body: &str) -> PathBuf {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::create_dir_all(dir).unwrap();
|
||||
let p = dir.join("wine");
|
||||
std::fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
|
||||
std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
p
|
||||
}
|
||||
|
||||
fn cfg(wine: PathBuf, timeout_ms: u64, tag: &str) -> RunConfig {
|
||||
RunConfig {
|
||||
wine,
|
||||
bottle: "t".into(),
|
||||
backend: None,
|
||||
program: "x.exe".into(),
|
||||
args: vec![],
|
||||
timeout: Duration::from_millis(timeout_ms),
|
||||
limits: memory::Limits {
|
||||
min_start_free: 0,
|
||||
min_free: 0,
|
||||
poll: Duration::from_millis(30),
|
||||
grace: Duration::from_millis(500),
|
||||
},
|
||||
expect: Some("PASS".into()),
|
||||
work_dir: std::env::temp_dir().join(format!("bxrun-{tag}-{}", std::process::id())),
|
||||
stall_timeout: None,
|
||||
settle_bound: Duration::from_millis(200),
|
||||
read_free: memory::free_percentage,
|
||||
}
|
||||
}
|
||||
|
||||
// These use a stub standing in for the launcher: they prove the supervision and record
|
||||
// logic, not anything about CrossOver.
|
||||
#[test]
|
||||
fn stub_run_records_pass_frames_and_env() {
|
||||
if !cfg!(target_os = "macos") {
|
||||
return;
|
||||
}
|
||||
let dir = std::env::temp_dir().join(format!("bxrun-stub1-{}", std::process::id()));
|
||||
let w = stub(
|
||||
&dir,
|
||||
"echo \"backend=$CX_GRAPHICS_BACKEND\"; echo 'frame_ms 10'; echo 'frame_ms 20'; echo PASS",
|
||||
);
|
||||
let mut c = cfg(w, 10_000, "a");
|
||||
c.backend = Some("dxmt".into());
|
||||
let r = execute(&c, Some("test".into()));
|
||||
assert_eq!(r.class, Class::Passed);
|
||||
let j = r.json.render();
|
||||
assert!(j.contains("\"frames\": 2"), "{j}");
|
||||
assert!(j.contains("backend=dxmt"), "{j}");
|
||||
assert!(j.contains("\"backend_requested\": \"dxmt\""));
|
||||
assert!(
|
||||
!j.contains("frame_ms 10"),
|
||||
"frame lines belong in frame_stats, not the tail"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stub_run_times_out_and_is_stopped() {
|
||||
if !cfg!(target_os = "macos") {
|
||||
return;
|
||||
}
|
||||
let dir = std::env::temp_dir().join(format!("bxrun-stub2-{}", std::process::id()));
|
||||
let w = stub(&dir, "exec /bin/sleep 30");
|
||||
let t0 = Instant::now();
|
||||
let r = execute(&cfg(w, 300, "b"), None);
|
||||
assert_eq!(r.class, Class::TimedOut);
|
||||
assert!(t0.elapsed() < Duration::from_secs(10));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stub_failure_is_classified_with_exit_code() {
|
||||
if !cfg!(target_os = "macos") {
|
||||
return;
|
||||
}
|
||||
let dir = std::env::temp_dir().join(format!("bxrun-stub3-{}", std::process::id()));
|
||||
let w = stub(&dir, "echo FAIL; exit 3");
|
||||
assert_eq!(
|
||||
execute(&cfg(w, 10_000, "c"), None).class,
|
||||
Class::FailedExit(3)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn silent_workload_is_stopped_as_stalled_before_the_timeout() {
|
||||
if !cfg!(target_os = "macos") {
|
||||
return;
|
||||
}
|
||||
let dir = std::env::temp_dir().join(format!("bxrun-stall1-{}", std::process::id()));
|
||||
let w = stub(&dir, "exec /bin/sleep 30");
|
||||
let mut c = cfg(w, 20_000, "d");
|
||||
c.stall_timeout = Some(Duration::from_millis(300));
|
||||
let t0 = Instant::now();
|
||||
let r = execute(&c, None);
|
||||
assert_eq!(r.class, Class::Stalled);
|
||||
assert!(
|
||||
t0.elapsed() < Duration::from_secs(5),
|
||||
"stall must fire long before the 20 s timeout"
|
||||
);
|
||||
assert!(r.json.render().contains("\"classification\": \"stalled\""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn workload_that_keeps_printing_is_not_stalled() {
|
||||
if !cfg!(target_os = "macos") {
|
||||
return;
|
||||
}
|
||||
let dir = std::env::temp_dir().join(format!("bxrun-stall2-{}", std::process::id()));
|
||||
// Prints every 0.1 s for about 1.2 s: longer than the 0.5 s stall timeout in total.
|
||||
let w = stub(
|
||||
&dir,
|
||||
"i=0; while [ $i -lt 12 ]; do echo tick; i=$((i+1)); sleep 0.1; done; echo PASS",
|
||||
);
|
||||
let mut c = cfg(w, 20_000, "e");
|
||||
c.stall_timeout = Some(Duration::from_millis(500));
|
||||
assert_eq!(execute(&c, None).class, Class::Passed);
|
||||
}
|
||||
|
||||
static FREE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(90);
|
||||
fn fake_free() -> Option<u8> {
|
||||
Some(FREE.load(std::sync::atomic::Ordering::SeqCst))
|
||||
}
|
||||
|
||||
// One test owns the shared `FREE` value, so it does not race with the others.
|
||||
#[test]
|
||||
fn after_a_stop_the_run_waits_for_memory_to_return() {
|
||||
use std::sync::atomic::Ordering::SeqCst;
|
||||
if !cfg!(target_os = "macos") {
|
||||
return;
|
||||
}
|
||||
let dir = std::env::temp_dir().join(format!("bxrun-settle-{}", std::process::id()));
|
||||
let w = stub(&dir, "exec /bin/sleep 30");
|
||||
let mut c = cfg(w, 300, "f");
|
||||
c.read_free = fake_free;
|
||||
c.limits.min_start_free = 50;
|
||||
c.limits.min_free = 0; // only the timeout stops the run
|
||||
c.settle_bound = Duration::from_secs(5);
|
||||
|
||||
// Memory drops 100 ms in and returns 900 ms in; the timeout stop happens at about 300 ms.
|
||||
FREE.store(90, SeqCst);
|
||||
let h = std::thread::spawn(|| {
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
FREE.store(10, SeqCst);
|
||||
std::thread::sleep(Duration::from_millis(800));
|
||||
FREE.store(90, SeqCst);
|
||||
});
|
||||
let r = execute(&c, None);
|
||||
h.join().unwrap();
|
||||
assert_eq!(r.class, Class::TimedOut);
|
||||
let j = r.json.render();
|
||||
assert!(j.contains("\"recovered_to_start_threshold\": true"), "{j}");
|
||||
assert!(r.duration >= Duration::from_millis(300));
|
||||
|
||||
// Memory never returns: the wait gives up at the bound and says so.
|
||||
FREE.store(90, SeqCst);
|
||||
let h = std::thread::spawn(|| {
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
FREE.store(10, SeqCst);
|
||||
});
|
||||
c.settle_bound = Duration::from_millis(400);
|
||||
let t0 = Instant::now();
|
||||
let r = execute(&c, None);
|
||||
h.join().unwrap();
|
||||
assert!(t0.elapsed() < Duration::from_secs(5));
|
||||
assert!(
|
||||
r.json
|
||||
.render()
|
||||
.contains("\"recovered_to_start_threshold\": false")
|
||||
);
|
||||
FREE.store(90, SeqCst);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stopping_a_bottle_selects_it_through_wineprefix() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
if !cfg!(target_os = "macos") {
|
||||
return;
|
||||
}
|
||||
let dir = std::env::temp_dir().join(format!("bxrun-stop-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let log = dir.join("wineserver.log");
|
||||
let ws = dir.join("wineserver");
|
||||
std::fs::write(
|
||||
&ws,
|
||||
format!(
|
||||
"#!/bin/sh\necho \"args=$* WINEPREFIX=$WINEPREFIX\" > '{}'\n",
|
||||
log.display()
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::set_permissions(&ws, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
stop_bottle(&dir.join("wine"), "my-bottle");
|
||||
let got = std::fs::read_to_string(&log).unwrap();
|
||||
assert!(got.contains("args=-k"), "{got}");
|
||||
assert!(
|
||||
got.contains("Bottles/my-bottle") || got.contains("/my-bottle"),
|
||||
"{got}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
//! Probe Windows cross-compilers for original test programs (issue #364).
|
||||
//!
|
||||
//! Reports what is installed and what each compiler targets; it does not install anything.
|
||||
|
||||
use crate::cmdutil::run;
|
||||
use crate::json::Json;
|
||||
|
||||
/// (name, kind). Order is the discovery order only, not a preference.
|
||||
pub const CANDIDATES: &[&str] = &[
|
||||
"aarch64-w64-mingw32-clang",
|
||||
"x86_64-w64-mingw32-clang",
|
||||
"x86_64-w64-mingw32-gcc",
|
||||
"i686-w64-mingw32-gcc",
|
||||
];
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Compiler {
|
||||
pub name: String,
|
||||
pub path: String,
|
||||
pub version_line: Option<String>,
|
||||
pub target_machine: Option<String>,
|
||||
}
|
||||
|
||||
pub fn probe(search_path: &str) -> Vec<Compiler> {
|
||||
CANDIDATES
|
||||
.iter()
|
||||
.filter_map(|name| {
|
||||
let path = search_path
|
||||
.split(':')
|
||||
.map(|d| std::path::Path::new(d).join(name))
|
||||
.find(|p| p.is_file())?;
|
||||
let p = path.to_str()?.to_string();
|
||||
Some(Compiler {
|
||||
name: name.to_string(),
|
||||
version_line: run(&p, &["--version"])
|
||||
.and_then(|s| s.lines().next().map(String::from)),
|
||||
target_machine: run(&p, &["-dumpmachine"]),
|
||||
path: p,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
impl Compiler {
|
||||
pub fn to_json(&self) -> Json {
|
||||
Json::obj(vec![
|
||||
("name", Json::str(self.name.clone())),
|
||||
("path", Json::str(self.path.clone())),
|
||||
("version", Json::opt_str(self.version_line.clone())),
|
||||
("target_machine", Json::opt_str(self.target_machine.clone())),
|
||||
])
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn empty_path_finds_nothing() {
|
||||
assert!(probe("").is_empty());
|
||||
assert!(probe("/nonexistent-dir").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finds_a_stub_compiler_and_reports_its_output() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = std::env::temp_dir().join(format!("bxhybrid-tc-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let f = dir.join("x86_64-w64-mingw32-gcc");
|
||||
std::fs::write(&f, "#!/bin/sh\nif [ \"$1\" = -dumpmachine ]; then echo x86_64-w64-mingw32; else echo stub 1.0; fi\n").unwrap();
|
||||
std::fs::set_permissions(&f, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let found = probe(dir.to_str().unwrap());
|
||||
assert_eq!(found.len(), 1);
|
||||
assert_eq!(
|
||||
found[0].target_machine.as_deref(),
|
||||
Some("x86_64-w64-mingw32")
|
||||
);
|
||||
assert_eq!(found[0].version_line.as_deref(), Some("stub 1.0"));
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
}
|
||||
+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,33 @@
|
||||
# Upstream provenance: victory-shader
|
||||
|
||||
| | |
|
||||
| --- | --- |
|
||||
| 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()` (test host only).
|
||||
- `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/`. The shader inputs the upstream project was built for are not included; 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,
|
||||
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,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,396 @@
|
||||
// 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::new(false).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::new(false).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::new(false).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");
|
||||
}
|
||||
}
|
||||
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::new(false).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
+21
-7
@@ -8,11 +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.
|
||||
The active plan replaces the former roadmap with workload-based phases, from
|
||||
compiled guest boot to separately admitted Xbox compatibility experiments.
|
||||
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
|
||||
|
||||
@@ -40,6 +45,7 @@ compiled guest boot to separately admitted Xbox compatibility experiments.
|
||||
|
||||
- [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.
|
||||
@@ -51,7 +57,7 @@ compiled guest boot to separately admitted Xbox compatibility experiments.
|
||||
- [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,10 +66,18 @@ compiled guest boot to separately admitted Xbox compatibility experiments.
|
||||
|
||||
## Research and engineering decisions
|
||||
|
||||
- [PortWatch projects and the native macOS plan](research/portwatch-native-macos.md) — Complete pinned tracker screen, native ARM64 gaps, contributor issues and revised phase dependencies; external claims remain unverified.
|
||||
- [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.
|
||||
- [Upstream integration audit](research/upstream-integration-audit.md) — Source-level review of external macOS compatibility projects, licence and provenance decisions, and what was implemented in `crates/hybrid`.
|
||||
- [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 fail under D3DMetal: device capabilities, what is established and what is not.
|
||||
- [CrossOver baseline](research/crossover-baseline-2026-11-25.md) — First executions of original workloads under CrossOver 26.3 on the M4, backend comparison and its limits.
|
||||
- [Windows cross-toolchain](research/hybrid-toolchain.md) — Pinned llvm-mingw release, how original Windows workloads are built, and what was and was not executed.
|
||||
- [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.
|
||||
@@ -0,0 +1,240 @@
|
||||
> **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
|
||||
application or engineering result. The plan is based on the current repository,
|
||||
not on completing an inherited prompt or reaching a compatibility percentage.
|
||||
No phase authorizes a release, publication, or commercial-game compatibility claim.
|
||||
|
||||
## Starting point
|
||||
|
||||
The source review used `19a905c30ea85166c05084da4fba67e356920912` on destination
|
||||
`main`, with the local documentation work starting after the separate CODEOWNERS
|
||||
commit `f02eb2678e76e91876be5706ce91dca25dcc3017`. The latter changes governance,
|
||||
not runtime behavior. Open issues and PRs were inspected on November 24, 2026
|
||||
(America/Chicago). Recheck their current heads and claims before taking work.
|
||||
|
||||
This task performed source inspection and read-only inventories. It did not
|
||||
rerun the Rust, native GPU, application, fuzz, mutation, or performance suites.
|
||||
Historical results below remain evidence for their recorded candidates only.
|
||||
|
||||
| Area | Present in the inspected source | Boundary for this plan |
|
||||
| --- | --- | --- |
|
||||
| Guest CPU | Generated x86-64 decoder, interpreter, ARM64 dynamic binary translator (DBT), integer and vector tests; inventory reports 491 declared forms and 206 operations | Declarations and lowering classifications do not establish independent acceptance or broad application compatibility. |
|
||||
| Runtime | PE loading, import resolution, service handlers, process-exit tests and the compiled-C A1 fixture | The typed registry inventories only 20 services: 7 marked implemented and 13 partial. Many handwritten handlers are outside that inventory; 20 is not the total runtime service count. |
|
||||
| Threads | Deterministic scheduler, guest thread contexts and guarded stacks, thread services and compiled-C thread tests | Guest threads execute serially on one host thread. Blocking synchronization, sleep behavior and thread lifecycle callbacks still have documented gaps. |
|
||||
| Graphics | gfx1030 shader decoder/compiler/reference, native Metal execution paths, texture and draw tests | Synthetic desktop instruction fixtures do not establish Xbox behavior. Acceptance is tracked separately from local readback. |
|
||||
| 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).
|
||||
The read-only shader reconciliation reported zero mismatches during this task;
|
||||
that result is inventory consistency, not new GPU verification.
|
||||
|
||||
## How previous phase names fit
|
||||
|
||||
Keep historical evidence and attribution intact. These records remain useful,
|
||||
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. |
|
||||
| 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.
|
||||
|
||||
## Phase 1 — Establish a trustworthy working baseline
|
||||
|
||||
**Outcome:** contributors can tell what exists on main, what is pending review,
|
||||
and which checks actually ran on the candidate they are using.
|
||||
|
||||
1. Reconcile the current source with the CPU campaign ledger, Gate A document,
|
||||
runtime inventory scope, and QA compatibility ledger. In particular, the QA
|
||||
CPU inventory's intentional-rejection catalog still lists strings and
|
||||
atomics/fences despite source and tests for supported subsets. Correct the
|
||||
catalog through its existing owner; do not remove explicit unsupported forms.
|
||||
2. Preserve all imported attribution. Repair destination links in migrated PRs
|
||||
without recreating sign-offs or treating archived reviews as current approval.
|
||||
3. Reproduce the applicable existing CPU, generator and repository checks for a
|
||||
pinned candidate. Run GPU and app checks separately on an eligible native host.
|
||||
Record errors, unavailable tools and skipped tests separately.
|
||||
4. Review conflicting PR branches with their authors. Changing descriptions
|
||||
cannot resolve source conflicts or provide missing ARM64 build checks.
|
||||
5. Finish BetterXen's active branding where needed. Preserve copyright notices,
|
||||
licenses and accurate historical records. Package names, C symbols, guest ABI
|
||||
names and environment variables require a compatibility migration, not a
|
||||
blanket search-and-replace. Do not rewrite authorship to imply new ownership.
|
||||
|
||||
Existing work: [migration checks #286](https://github.com/MacosPorters/betterxen/issues/286),
|
||||
[QA scope #219](https://github.com/MacosPorters/betterxen/issues/219),
|
||||
[app CI #248](https://github.com/MacosPorters/betterxen/issues/248).
|
||||
|
||||
**Exit criteria:** a candidate SHA, a current capability/blocker inventory,
|
||||
links to retained logs for each executed gate, explicit pending reviews, and
|
||||
usable PR descriptions. Independent acceptance remains a separate decision.
|
||||
No release is required.
|
||||
|
||||
## Phase 2 — Finish a reproducible hosted C application
|
||||
|
||||
**Outcome:** an original hosted C program starts, uses the runtime, reports
|
||||
results and exits through the guest path with checked cleanup.
|
||||
|
||||
Review and integrate existing work rather than creating a competing runtime:
|
||||
|
||||
| Prerequisite | Existing destination work |
|
||||
| --- | --- |
|
||||
| CRT startup calls | [issue #237](https://github.com/MacosPorters/betterxen/issues/237), [PR #273](https://github.com/MacosPorters/betterxen/pull/273) |
|
||||
| Arguments and environment | [issue #242](https://github.com/MacosPorters/betterxen/issues/242), [PR #277](https://github.com/MacosPorters/betterxen/pull/277) |
|
||||
| Normal termination and exit handlers | [issue #243](https://github.com/MacosPorters/betterxen/issues/243), [PR #280](https://github.com/MacosPorters/betterxen/pull/280) |
|
||||
| Formatted standard output | [issue #245](https://github.com/MacosPorters/betterxen/issues/245), [PR #281](https://github.com/MacosPorters/betterxen/pull/281) |
|
||||
| File streams | [issue #246](https://github.com/MacosPorters/betterxen/issues/246), [PR #282](https://github.com/MacosPorters/betterxen/pull/282) |
|
||||
| Integrated hosted-C fixture | [issue #262](https://github.com/MacosPorters/betterxen/issues/262), [PR #283](https://github.com/MacosPorters/betterxen/pull/283) |
|
||||
|
||||
Check dependency order and stacked branches against their actual heads. Audit
|
||||
the compiler and linked CRT's per-file licensing and native ARM64 build tools.
|
||||
An x86-64 guest fixture is permitted; its compiler must run natively on ARM64.
|
||||
|
||||
**Exit criteria:** reproducible original fixture build; checked stdout/stderr,
|
||||
arguments, file contents, exit status, callback order and cleanup; unresolved
|
||||
imports and exhausted budgets fail explicitly. Existing A1 behavior still passes.
|
||||
Independent reviewers derive expected results from public specifications and the
|
||||
fixture contract. No general C++ or Xbox startup claim follows from this result.
|
||||
|
||||
## Phase 3 — Make threaded application behavior coherent
|
||||
|
||||
**Outcome:** an original worker-based application can block and resume without
|
||||
stalling unrelated guest work or leaking per-thread state.
|
||||
|
||||
Extend the existing scheduler under [issue #228](https://github.com/MacosPorters/betterxen/issues/228).
|
||||
Prioritize a small fixture that exposes a documented gap: guest sleep currently
|
||||
delays all guest threads, and critical-section/SRW/condition-variable waits are
|
||||
not fully connected to scheduling. Claim one gap and its paths before editing.
|
||||
|
||||
Then add the thread lifecycle behavior required by that workload, including
|
||||
static thread-local storage (TLS), library attach/detach and fiber-local storage
|
||||
(FLS) cleanup where supported. Keep unsupported callbacks explicit until their
|
||||
semantics and safety are implemented. Preserve Win64 nonvolatile register checks
|
||||
and coordinate with [issue #193 / PR #268](https://github.com/MacosPorters/betterxen/pull/268).
|
||||
|
||||
**Exit criteria:** deterministic results at several scheduling quanta; another
|
||||
worker progresses while one waits; timeouts, cancellation, abandoned objects,
|
||||
thread-local errors, stack bounds and cleanup have negative controls. Repeat
|
||||
runs reclaim thread resources. Serial guest scheduling remains the execution
|
||||
model unless a separately reviewed memory-ordering design replaces it.
|
||||
|
||||
## Phase 4 — Connect resource updates to translated rendering
|
||||
|
||||
**Outcome:** one original guest workload updates a texture and geometry, submits
|
||||
translated rendering, waits for completion and produces an independently checked
|
||||
frame through the existing native Metal backend.
|
||||
|
||||
Start with a bounded scene and its concrete missing features. Do not make all
|
||||
RDNA2 instructions, mesh shaders or ray tracing prerequisites for a first scene.
|
||||
Reuse the semantic registry and distinguish declared, decoded, lowered,
|
||||
reference-tested, locally GPU-tested and independently accepted forms.
|
||||
|
||||
Coordinate [RDNA2 expansion #205](https://github.com/MacosPorters/betterxen/issues/205),
|
||||
[mip footprints #241 / PR #278](https://github.com/MacosPorters/betterxen/pull/278),
|
||||
[graphics fences #224](https://github.com/MacosPorters/betterxen/issues/224),
|
||||
[shared resource lifetime #148](https://github.com/MacosPorters/betterxen/issues/148),
|
||||
and [texture-update workload #147](https://github.com/MacosPorters/betterxen/issues/147).
|
||||
Wave divergence, cross-lane operations and additional formats get separate
|
||||
fixture contracts and claims when this workload needs them.
|
||||
|
||||
**Exit criteria:** actual Metal execution and frame readback against an
|
||||
independently derived expectation; update/submission/retirement order is checked;
|
||||
invalid descriptors, stale handles and unsupported shader forms fail explicitly.
|
||||
Record host capability detection, hardware, validation settings and evidence
|
||||
class. Test counts and tolerances retain their existing definitions. Results
|
||||
remain synthetic desktop-gfx1030 evidence, never Xbox hardware verification.
|
||||
|
||||
## Phase 5 — Run one integrated interactive application reliably
|
||||
|
||||
**Outcome:** a small, original application joins guest execution, rendering,
|
||||
input, bounded audio, filesystem access and lifecycle behavior in one session.
|
||||
|
||||
Start from [multi-module startup #256](https://github.com/MacosPorters/betterxen/issues/256)
|
||||
and the existing app/FFI fixtures. First prove a compiled workload can reach a
|
||||
checked frame. Add C++ language/runtime features only when an independently
|
||||
authored failing fixture demonstrates the need. Audit any linked runtime first.
|
||||
Do not treat the Swift audio/input demonstrations as guest integration evidence.
|
||||
|
||||
Coordinate [audio #227](https://github.com/MacosPorters/betterxen/issues/227),
|
||||
[session errors #250](https://github.com/MacosPorters/betterxen/issues/250),
|
||||
[report schema #254](https://github.com/MacosPorters/betterxen/issues/254),
|
||||
[worker diagnostics #255](https://github.com/MacosPorters/betterxen/issues/255),
|
||||
and [application quick start #247](https://github.com/MacosPorters/betterxen/issues/247).
|
||||
Execution-admission changes remain owned by [issue #212](https://github.com/MacosPorters/betterxen/issues/212).
|
||||
|
||||
**Exit criteria:** scripted input and deterministic checkpoints; start, pause,
|
||||
resume, stop and restart behavior; checked audio sample data before device
|
||||
playback; bounded memory and handle use; sandbox escape attempts rejected;
|
||||
useful failure reports and a repeatable soak protocol. Specify soak duration,
|
||||
resource limits and acceptance conditions before measuring. A fixture worker
|
||||
passing does not certify arbitrary files safe or commercial titles playable.
|
||||
|
||||
## Phase 6 — Improve measured bottlenecks
|
||||
|
||||
**Outcome:** faster or lower-resource execution of workloads whose correctness
|
||||
is already checked, with measurements that another contributor can reproduce.
|
||||
|
||||
Performance analysis can begin earlier; changes must preserve the relevant
|
||||
phase's correctness. Select bottlenecks from actual measurements rather than
|
||||
assuming every shared-semantics call, allocation or cache miss needs replacement.
|
||||
Potential work includes CPU helper lowering, bounded translation-cache policy,
|
||||
Metal startup, texture transfers and frame-loop overhead.
|
||||
|
||||
Reuse [startup measurements #171 / PR #266](https://github.com/MacosPorters/betterxen/pull/266),
|
||||
[TLS optimization #107 / PR #284](https://github.com/MacosPorters/betterxen/pull/284),
|
||||
[DBT comparison #110 / PR #272](https://github.com/MacosPorters/betterxen/pull/272),
|
||||
and [conditional cache prewarming #258](https://github.com/MacosPorters/betterxen/issues/258).
|
||||
|
||||
**Exit criteria:** correctness gates pass on the changed candidate; baseline and
|
||||
candidate use equivalent inputs, toolchains, settings and hardware; idle-machine
|
||||
samples include variance and separate cold/warm startup. Report regressions as
|
||||
well as gains. Run validation-off benchmarks separately from validation-on GPU
|
||||
correctness. Capability differences across Apple Silicon generations remain
|
||||
unknown until measured; runtime detection controls optional paths.
|
||||
|
||||
## Taking the next task
|
||||
|
||||
Begin with Phase 1's evidence reconciliation and review Phase 2's existing PRs.
|
||||
The phase-plan issue does not claim their implementation files. Read every
|
||||
comment on a target issue and inspect linked PRs; never take a live claim.
|
||||
Issue #219's QA paths and subsystem owners remain independent of this plan.
|
||||
|
||||
Each implementation task needs a bounded outcome, permitted files, dependencies,
|
||||
public semantic sources, a failing fixture or other meaningful acceptance check,
|
||||
and the required independent reviewers. Use original code and expectations;
|
||||
never copy another emulator to satisfy a phase. Do not require a fixed number
|
||||
of agents: use available resources only within the repository's LOW-reasoning
|
||||
and independent-review rules.
|
||||
|
||||
Useful existing commands for the candidate record:
|
||||
|
||||
```sh
|
||||
PYTHONPATH=scripts python3 -m qa cpu-inventory --compact
|
||||
PYTHONPATH=scripts python3 -m qa runtime-inventory --compact
|
||||
PYTHONPATH=scripts python3 -m qa rdna2 reconcile --compact
|
||||
python3 scripts/audit/status.py --check
|
||||
scripts/audit/claims.sh
|
||||
scripts/audit/dependencies.sh
|
||||
```
|
||||
|
||||
For implementation, run the applicable checkout commands in `AGENTS.md` and the
|
||||
subsystem acceptance protocol. Keep logs under ignored `artifacts/`. Use at most
|
||||
four Cargo jobs across two CPU-heavy jobs, one GPU job and one fuzz or mutation
|
||||
campaign at a time. New verification must name the exact candidate; skipped
|
||||
tests never count as GPU evidence. Passing a phase does not authorize a release.
|
||||
@@ -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>
|
||||
@@ -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
|
||||
@@ -1,347 +0,0 @@
|
||||
# BetterXen development phases
|
||||
|
||||
BetterXen's objective is to execute supported Xbox Series software through an
|
||||
original native ARM64 runtime and direct Metal on macOS. Commercial game
|
||||
execution, including GTA VI, is currently unsupported. The demonstrated results
|
||||
are bounded, independently authored programs and shaders.
|
||||
|
||||
This is the sole active phase sequence. It replaces the previous phase plan and
|
||||
the README's X1–X25 roadmap. Historical fixture names and acceptance records
|
||||
retain their meaning as evidence for their original candidates; they are not a
|
||||
second development schedule.
|
||||
|
||||
## Starting position
|
||||
|
||||
The reviewed main revision is
|
||||
[`b2654e93a42e74e29570183da1f31bb8cdc6f721`](https://github.com/MacosPorters/betterxen/tree/b2654e93a42e74e29570183da1f31bb8cdc6f721),
|
||||
checked on November 24, 2026 (America/Chicago). Research began from a working
|
||||
tree at `f02eb2678e76e91876be5706ce91dca25dcc3017` and inspected newer main in a
|
||||
separate snapshot. This documentation change is based on the reviewed main
|
||||
revision; it changes no runtime implementation.
|
||||
|
||||
On inspected main, the source contains an x86-64 interpreter, an ARM64 dynamic
|
||||
binary translator (DBT), PE32+ loading, a partial runtime, a deterministic guest
|
||||
scheduler, translated graphics, texture/sampler bindings and a native Swift app.
|
||||
The hosted C fixtures A1 and A2 are implemented and reported locally passing;
|
||||
both still await independent acceptance. These pieces have not established a
|
||||
complete commercial game or one integrated threaded 3D application.
|
||||
|
||||
The [public-project review](research/portwatch-native-macos.md) explains the
|
||||
external comparisons and current-source limits. Windows projects often execute
|
||||
x86-64 instructions directly and use Windows/D3D12 services. The inspected Mac
|
||||
guest-execution projects use Rosetta; native asset renderers demonstrate a
|
||||
different workload. Their progress is a research lead, not BetterXen evidence.
|
||||
No competitor emulator implementation may be copied or adapted.
|
||||
|
||||
No phase is declared complete by this planning task. It ran documentation and
|
||||
inventory checks, not new CPU/GPU execution, fuzzing, mutation or benchmarks.
|
||||
|
||||
## Delivery sequence
|
||||
|
||||
| Phase | Demonstrable result | Principal dependency |
|
||||
| --- | --- | --- |
|
||||
| 1 | A reproducible compiled guest boots and exits on native ARM64 | Existing A1/A2 and native tool evidence |
|
||||
| 2 | One modular guest program runs workers and cleans up correctly | Module startup, scheduling and lifecycle contracts |
|
||||
| 3 | Guest code controls a translated textured Metal scene | Validated guest graphics calls, bindings and completion |
|
||||
| 4 | An original interactive application combines execution, graphics, input, audio and saves | The supported paths from phases 2 and 3 |
|
||||
| 5 | A varied original workload corpus exposes and closes specific compatibility gaps | A repeatable integrated application and diagnostics |
|
||||
| 6 | Sustained execution is measured and verified across native Apple Silicon hosts | Checked workloads, resource bounds and actual host reports |
|
||||
| 7 | A separately admitted Xbox compatibility experiment has documented contracts and reproducible results | Public console evidence and all behavior required by that input |
|
||||
|
||||
Each result has its own admission profile. A simple scene need not wait for all
|
||||
AVX2 instructions, mesh shaders or ray tracing. A workload needing an unsupported
|
||||
feature stops explicitly. Research, diagnostics, CPU expansion and performance
|
||||
measurement can proceed alongside these phases on independently claimed paths.
|
||||
A phase's number does not grant exclusive ownership of a subsystem.
|
||||
|
||||
## Phase 1 — Boot a reproducible compiled guest
|
||||
|
||||
**Deliverable:** a contributor can build an original guest from source, start it
|
||||
through BetterXen's supported test entry point and reproduce its output and exit
|
||||
without an Intel host executable or Windows compatibility runtime.
|
||||
|
||||
Use the existing [Gate A fixtures](testing/gate-a.md). On inspected main,
|
||||
[PR #283](https://github.com/MacosPorters/betterxen/pull/283) already supplies the
|
||||
hosted C program. Reproduce and review that implementation; do not create a
|
||||
competing CRT startup or mark it unimplemented because this checkout is older.
|
||||
|
||||
The candidate record identifies the exact source revision, local modifications,
|
||||
native compiler/linker, linked support-code licenses, execution path and limits.
|
||||
Check host executables/dependencies with `file`, `lipo -archs` and `otool -L`.
|
||||
Guest x86-64 bytes are permitted data; native host tools must support ARM64.
|
||||
Use `aarch64-apple-darwin` for BetterXen.
|
||||
|
||||
**Completion checks:**
|
||||
|
||||
- A1/A2 reproduce the specified stdout/stderr, files, callback order, exit status
|
||||
and cleanup on the named candidate. Missing compilers fail visibly.
|
||||
- Existing wrong-input, unresolved-import and instruction-budget controls still
|
||||
fail for their specified reasons. A trapped stub is not implemented behavior.
|
||||
- The admission profile states which CPU forms, imports and startup features it
|
||||
supports. The test entry point is distinguished from CLI/app execution.
|
||||
- Independent reviewers accept the semantic expectations and the scope of the
|
||||
native evidence. A local pass alone does not close this phase.
|
||||
|
||||
**Contributor work:** [CPU coverage #154](https://github.com/MacosPorters/betterxen/issues/154),
|
||||
[native reports #303](https://github.com/MacosPorters/betterxen/issues/303), and
|
||||
[existing compatibility report #254](https://github.com/MacosPorters/betterxen/issues/254).
|
||||
Use existing audit/test tooling and coordinate schema changes with its owners.
|
||||
|
||||
## Phase 2 — Run a modular program with guest workers
|
||||
|
||||
**Deliverable:** an original executable and companion libraries initialize,
|
||||
start workers, exchange results, block/resume and exit with checked teardown.
|
||||
|
||||
Begin with [the EXE/two-DLL startup contract #301](https://github.com/MacosPorters/betterxen/issues/301)
|
||||
and [worker lifecycle design #305](https://github.com/MacosPorters/betterxen/issues/305).
|
||||
The fixture records dependency initialization, per-module static thread-local
|
||||
storage (TLS), worker-visible values and supported detach/destructor calls.
|
||||
Expected order must be derived before implementing the loader or callbacks.
|
||||
Built-in service-module lookup is not general guest DLL loading.
|
||||
|
||||
Extend the existing serial scheduler under
|
||||
[#228](https://github.com/MacosPorters/betterxen/issues/228). Its documented
|
||||
`Sleep` behavior can stall every worker; [#304](https://github.com/MacosPorters/betterxen/issues/304)
|
||||
owns the narrow yielding fix after parent/runtime ownership coordination.
|
||||
Handle critical sections, condition variables and other waits as separately
|
||||
specified gaps, not incidental additions to that fix.
|
||||
|
||||
Broader CPU behavior is driven by the admitted fixture. Start
|
||||
[AVX/YMM design #299](https://github.com/MacosPorters/betterxen/issues/299) and
|
||||
[unwind design #300](https://github.com/MacosPorters/betterxen/issues/300) in
|
||||
parallel, but do not require their entire future scope for a simpler program.
|
||||
A workload using those features must wait for real support. CPU feature bits
|
||||
must not advertise unsupported behavior. Stack walking, structured exception
|
||||
handling (SEH) and C++ exceptions are separate capabilities.
|
||||
|
||||
**Completion checks:**
|
||||
|
||||
- The source-built module graph has independently derived results and
|
||||
initialization/teardown records, with explicit forwarder/cycle/search policy.
|
||||
- One worker progresses while another waits. Results hold across specified
|
||||
scheduling quanta; the injected clock and timeout units remain consistent.
|
||||
- Static TLS, dynamic TLS, fiber-local storage (FLS), errors, errno and CPU state
|
||||
retain their specified per-thread isolation. Dropping a value does not count
|
||||
as executing its registered guest callback.
|
||||
- Missing exports, failed attach, invalid callback targets, stack faults,
|
||||
timeouts, deadlock and exhausted budgets have precise, bounded outcomes.
|
||||
- Repeated runs reclaim owned modules, handles, stacks and callback state.
|
||||
Unsupported delayed imports or lifecycle paths are rejected explicitly.
|
||||
|
||||
**Contributor work:** reuse [package census #211](https://github.com/MacosPorters/betterxen/issues/211)
|
||||
and the existing scheduler. Runtime PRs #263/#290 overlap; their authors and
|
||||
maintainers must resolve ownership before shared production edits. Parallel
|
||||
host-thread execution remains outside the serial scheduler's ordering claim.
|
||||
|
||||
## Phase 3 — Render a scene controlled by guest code
|
||||
|
||||
**Deliverable:** a compiled original guest creates resources, uploads a texture
|
||||
and geometry, submits translated rendering, waits for completion and checks the
|
||||
resulting frame through its guest-visible interface.
|
||||
|
||||
Use [startup-to-frame integration #256](https://github.com/MacosPorters/betterxen/issues/256)
|
||||
as the integration task. A Rust test calling a host graphics method does not
|
||||
alone prove the compiled guest can call it. Specify the supported service/call
|
||||
boundary and check its Win64 argument/return and nonvolatile-state behavior.
|
||||
Guest addresses must resolve to checked ranges and opaque handles, never host
|
||||
pointers.
|
||||
|
||||
Existing translated `image_sample_lz`, guest descriptor-table bindings, texture
|
||||
upload paths, blend/index/depth tests and packed compressed-texture footprints
|
||||
are starting components. [Binding/entry design #302](https://github.com/MacosPorters/betterxen/issues/302)
|
||||
specifies expansion beyond the bounded texture/sampler contract. Use an original
|
||||
scene with distinguishable textures and resource updates so wrong bindings or
|
||||
stale data change checked pixels.
|
||||
|
||||
**Completion checks:**
|
||||
|
||||
- Actual native Metal execution produces frame readback matching expectations
|
||||
derived independently of the decoder, compiler and production renderer.
|
||||
- Changing one guest texture, transform or binding changes the expected frame;
|
||||
a skipped draw or substituted shader cannot pass as correct rendering.
|
||||
- Update, submit, completion, readback and retirement order are checked.
|
||||
Resources remain valid for in-flight work and stale handles are rejected.
|
||||
- Bad descriptors, overflowing ranges, unsupported shader forms and invalid
|
||||
resource states fail before unsupported work reaches Metal.
|
||||
- The report records device capability queries, validation settings, candidate,
|
||||
commands and hardware. Synthetic gfx1030 success is not Xbox GPU verification.
|
||||
|
||||
**Contributor work:** [resource-update workload #147](https://github.com/MacosPorters/betterxen/issues/147),
|
||||
[shared lifetime #148](https://github.com/MacosPorters/betterxen/issues/148),
|
||||
[fences #224](https://github.com/MacosPorters/betterxen/issues/224), and
|
||||
[format inventory #260](https://github.com/MacosPorters/betterxen/issues/260).
|
||||
Respect the active format claim; do not duplicate its inventory.
|
||||
|
||||
## Phase 4 — Run an original interactive application
|
||||
|
||||
**Deliverable:** one small original game-like application runs through the guest
|
||||
CPU/runtime and native app with translated graphics, scripted input, bounded
|
||||
audio and a save/load cycle in a persistent session.
|
||||
|
||||
Compose the admitted paths from phases 2 and 3. Define the application source,
|
||||
input replay, frame checkpoints, sample-data checks and save format before
|
||||
implementation. Start with the CPU/shader subset already justified by the scene.
|
||||
Add C++ or additional runtime functionality only when an original failing
|
||||
fixture demonstrates the requirement and linked runtime terms are reviewed.
|
||||
|
||||
Wire the application through the existing Swift/Rust interface and worker
|
||||
lifecycle. Existing native audio, controller and filesystem demonstrations are
|
||||
components, not proof that guest code reaches each service. This phase must
|
||||
exercise those guest connections in one session.
|
||||
|
||||
**Completion checks:**
|
||||
|
||||
- A deterministic replay reaches independently specified state/frame checkpoints.
|
||||
- Input reaches guest logic; expected audio samples are checked before device
|
||||
playback; save/load preserves specified state and reports I/O failures.
|
||||
- Start, pause, resume, stop, restart and worker failure have defined outcomes.
|
||||
Commands do not report success after a worker has failed.
|
||||
- Resource/handle counts and cleanup remain bounded across repeated sessions;
|
||||
invalid guest paths and resource requests fail according to the interface.
|
||||
- The native app/CLI provide a reproducible quick start and useful stage-specific
|
||||
failure reports. This fixture still establishes no commercial compatibility.
|
||||
|
||||
**Contributor work:** [audio #227](https://github.com/MacosPorters/betterxen/issues/227),
|
||||
[session errors #250](https://github.com/MacosPorters/betterxen/issues/250),
|
||||
[worker diagnostics #255](https://github.com/MacosPorters/betterxen/issues/255),
|
||||
[app CI #248](https://github.com/MacosPorters/betterxen/issues/248), and
|
||||
[quick start #247](https://github.com/MacosPorters/betterxen/issues/247).
|
||||
Execution-admission policy remains with
|
||||
[#212](https://github.com/MacosPorters/betterxen/issues/212).
|
||||
|
||||
## Phase 5 — Expand compatibility through a varied workload corpus
|
||||
|
||||
**Deliverable:** a versioned set of original source-built workloads exercises
|
||||
meaningfully different CPU, runtime and graphics behavior through the integrated
|
||||
path, with precise accepted/rejected profiles and reproducible regressions.
|
||||
|
||||
Choose additions from actual failures. Examples include another compiler or
|
||||
runtime profile, vector-heavy arithmetic, runtime-dependent shader branches,
|
||||
bounded loops, multiple resource views and streaming texture updates. Each
|
||||
addition must demonstrate a gap not already owned by an existing task.
|
||||
|
||||
Use [CPU design #299](https://github.com/MacosPorters/betterxen/issues/299),
|
||||
[unwind design #300](https://github.com/MacosPorters/betterxen/issues/300),
|
||||
[runtime uniform branches #179](https://github.com/MacosPorters/betterxen/issues/179),
|
||||
[bounded shader loops #180](https://github.com/MacosPorters/betterxen/issues/180),
|
||||
and [RDNA2 expansion #205](https://github.com/MacosPorters/betterxen/issues/205).
|
||||
Wave divergence, cross-lane operations, local data share (LDS), barriers, mesh
|
||||
stages and ray tracing require their own public contracts, fixtures and native
|
||||
capability checks when a selected workload needs them.
|
||||
|
||||
**Completion checks:**
|
||||
|
||||
- Each workload identifies its source/build recipe, required forms/services,
|
||||
original expected outputs, limits and exact independently accepted candidate.
|
||||
- Coverage separates declared, decoded, lowered, CPU-tested, locally GPU-tested
|
||||
and independently accepted behavior. Compilation counts are not compatibility.
|
||||
- Unsupported behavior retains explicit diagnostic controls; expected values do
|
||||
not come from the same implementation being tested.
|
||||
- Targeted mutation/fuzz/regression checks demonstrate sensitivity to the changed
|
||||
behavior without altering tolerances, gate definitions or mutation counting.
|
||||
- Earlier integrated workloads still pass. Failures become bounded tasks with
|
||||
proposed files and dependencies, not a generic rewrite of a subsystem.
|
||||
|
||||
**Contributor work:** [original corpus #150](https://github.com/MacosPorters/betterxen/issues/150),
|
||||
[shader acceptance #225](https://github.com/MacosPorters/betterxen/issues/225),
|
||||
CPU coverage #154 and the existing QA owner #219. Reuse their tools and acceptance
|
||||
rules; do not create another competing status or test framework.
|
||||
|
||||
## Phase 6 — Sustain execution across Apple Silicon
|
||||
|
||||
**Deliverable:** admitted workloads run for a specified duration under bounded
|
||||
memory/resource use, and performance/correctness reports are reproducible on
|
||||
the actual native hosts contributors test.
|
||||
|
||||
Specify soak duration, replay, resource limits and failure conditions before the
|
||||
run. Measure guest execution, translation, service calls, transfers, Metal
|
||||
startup, submission and readback to identify the actual bottleneck. Record
|
||||
cold/warm behavior, variance and regressions as well as improvements.
|
||||
|
||||
Use the existing native audit, GPU tests and benchmarks. Reuse merged startup
|
||||
measurements and DBT comparison tooling; evaluate prewarming/persistence only
|
||||
under [#258](https://github.com/MacosPorters/betterxen/issues/258) when measurements
|
||||
justify it. Guest code-cache lifetime and same-block executable writes remain
|
||||
explicit CPU correctness risks under #95 and #291.
|
||||
|
||||
**Completion checks:**
|
||||
|
||||
- The agreed soak/restart protocol passes on the pinned candidate with recorded
|
||||
resource accounting and no hidden fallback or silent loss of work.
|
||||
- Baseline/candidate measurements use equivalent inputs, toolchains, settings
|
||||
and hardware. Validation-on correctness and validation-off performance are
|
||||
separate runs; benchmarks use an idle host as required by the protocol.
|
||||
- [Native reports #303](https://github.com/MacosPorters/betterxen/issues/303)
|
||||
distinguish host binary architecture, documented capabilities, actual execution,
|
||||
failure, unavailable tools and skipped tests. Skips are never GPU passes.
|
||||
- Runtime capability detection selects optional paths. M1–M5/future-device cells
|
||||
stay unknown until actual reports exist; one machine cannot verify them all.
|
||||
- Contributor preview preparation follows app/native gates. Signing, notarization,
|
||||
redistribution review and publication require their own evidence and explicit
|
||||
release authorization; this phase does not authorize uploads.
|
||||
|
||||
**Contributor work:** [soak #149](https://github.com/MacosPorters/betterxen/issues/149),
|
||||
[memory pressure #204](https://github.com/MacosPorters/betterxen/issues/204),
|
||||
[dependency evidence #158](https://github.com/MacosPorters/betterxen/issues/158),
|
||||
and [preview preparation #259](https://github.com/MacosPorters/betterxen/issues/259).
|
||||
|
||||
## Phase 7 — Attempt documented Xbox compatibility
|
||||
|
||||
**Deliverable:** a separately reviewed compatibility experiment with admissible
|
||||
inputs demonstrates exactly the supported startup/execution/rendering stages,
|
||||
or records a specific unresolved contract that prevents the attempt.
|
||||
|
||||
Begin [public console-contract research #306](https://github.com/MacosPorters/betterxen/issues/306)
|
||||
now, alongside the earlier engineering phases. Maintain evidence for launch and
|
||||
CPU entry state, executable admission, service ABI, shader entry/bindings,
|
||||
resource and command layouts, synchronization and memory aliases. Public PE,
|
||||
AMD desktop ISA and D3D12 documents establish their documented contracts; they
|
||||
do not automatically establish Xbox behavior. Unknown console details remain
|
||||
unknown rather than becoming guessed implementations.
|
||||
|
||||
An actual execution attempt depends on demonstrated technical support for its
|
||||
input, project-permitted authorized/unprotected material, explicit admission
|
||||
and independent review. Do not obtain or use leaked executables, restricted
|
||||
SDKs, confidential headers, proprietary shader collections, firmware or keys;
|
||||
do not implement protection bypasses. A torrent filename or container does not
|
||||
establish a supported executable, launch environment or compatibility result.
|
||||
User files stay outside the repository. File validation concerns technical
|
||||
compatibility and safety; it must not demand receipts, accounts or ownership
|
||||
provenance uploads.
|
||||
|
||||
**Completion checks:**
|
||||
|
||||
- Required contracts have precise public sources and repository evidence classes,
|
||||
or are visible blockers. Restricted/unavailable evidence is not bypassed.
|
||||
- The admitted input profile, candidate, runtime capabilities and expected
|
||||
outcomes are reviewed before execution and precisely bounded.
|
||||
- Actual results separately identify inspection, loading, entry, menu/frame,
|
||||
world simulation, interaction and sustained play. Reaching one does not
|
||||
certify the next; crashes and missing behavior remain in the report.
|
||||
- R1 audits evidence/provenance and R2 independently derives semantic expectations.
|
||||
BetterXen has no Xbox hardware access and must never claim such verification.
|
||||
- No game title is called supported or playable without a demonstrated repeatable
|
||||
result. No date, compatibility percentage or release follows from this plan.
|
||||
|
||||
This phase can remain blocked while earlier original workloads continue to
|
||||
improve. There is currently no demonstrated GTA VI execution in BetterXen.
|
||||
|
||||
## How contributors start
|
||||
|
||||
The [research tracker #298](https://github.com/MacosPorters/betterxen/issues/298)
|
||||
links the eight new bounded tasks #299–#306 and the existing work they depend on.
|
||||
The phase plan claims no implementation files. Research/design tasks can begin
|
||||
on their documented paths; production changes must coordinate subsystem owners
|
||||
and active claims. Read all comments, including imported archived claims, and
|
||||
inspect linked open PRs before claiming one issue in a plain reply.
|
||||
|
||||
Every task needs an outcome, proposed files, dependencies, public semantic
|
||||
sources, meaningful positive/negative checks and independent reviewers. Update
|
||||
the changelog for meaningful changes. Record candidate-specific results and raw
|
||||
logs under ignored `artifacts/`; distinguish implementation, local verification
|
||||
and independent acceptance. Preserve historical evidence and attribution.
|
||||
|
||||
Run the applicable commands from `AGENTS.md`. Across simultaneous work use at
|
||||
most four Cargo jobs across two CPU-heavy jobs, one GPU job and one fuzz or
|
||||
mutation campaign. Never count unrun or skipped checks as passes. No commit,
|
||||
push, merge or release is authorized by a phase or an issue claim.
|
||||
@@ -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,10 @@ 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 |
|
||||
| llvm-mingw | 20261117 (sha256 `98d340bb…446aa`) | Apache-2.0 WITH LLVM-exception, plus component licences in its LICENSE.TXT (mingw-w64 runtime and headers have their own terms; not audited line by line) | External build tool for original Windows test programs, not linked, not distributed |
|
||||
| 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,31 @@
|
||||
# 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. |
|
||||
| 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). |
|
||||
| Host receipt, frame statistics, cross-toolchain probe | `crates/hybrid` | **Build** (original Rust, public system interfaces) | ossover and Whisky are Swift references; no code adapted. See [audit](upstream-integration-audit.md). |
|
||||
| Metal HUD log parsing | ossover `MetalHUDLog` | **Reference only** | Log format is documented only by third-party observation; implement after a real trace is captured (#145). |
|
||||
| Bottle and bundle internals (`cxbottle.conf`, SharedSupport layout) | ossover and others | **Do not depend** | Undocumented, derived from reverse engineering; #350 decides. |
|
||||
| Game-specific XCL layers | MacBox, ScarlettMac | **Rejected** | GPL-2.0-only and game-specific. |
|
||||
|
||||
| Memory-pressure guard for workloads | skakwy/victory-mac `mac/run-victory.sh` | **Adapted** into `crates/hybrid/src/memory.rs` | Contributor-authored, GPL-3.0, permission granted; reimplemented in Rust. |
|
||||
| Windows cross-linker wrapper | skakwy/victory-mac `tools/macos/gnullvm-cc.sh` | **Not used** | Failed with Homebrew `llvm@17`; llvm-mingw covers the need. |
|
||||
| Windows cross toolchain | llvm-mingw 20261117 | **External dependency**, not vendored | Apache-2.0 with LLVM exceptions; checksum recorded in [hybrid-toolchain.md](hybrid-toolchain.md). |
|
||||
| Zero-copy Metal swizzle, D3DMetal state fixes | skakwy/victory-mac `mac/unixlib`, `PROGRESS.md` | **Rejected** | Act on D3DMetal internals; Apple licence forbids reverse engineering. |
|
||||
|
||||
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,59 @@
|
||||
# CrossOver baseline on the M4 reference machine (2026-11-25)
|
||||
|
||||
Evidence class: observed runs on one machine by one person (class B in the sense of [claims.toml](../claims.toml)); **not independently reproduced**, so #355 and #353 stay open. Every result is for original BetterXen workloads, never for a game. Nothing here shows Xbox compatibility.
|
||||
|
||||
## Environment
|
||||
|
||||
| Item | Value (source) |
|
||||
| --- | --- |
|
||||
| Machine | Apple M4, 10 cores (4 performance, 6 efficiency), 24 GiB, macOS 27.0 build 26A428 (`betterxen-hybrid host`) |
|
||||
| CrossOver | `/Applications/CrossOver.app`, 26.3, build 26.3.0.39832, bundle id `com.codeweavers.CrossOver`, main executable universal (x86_64, arm64) (`betterxen-hybrid crossover`). Licence or trial state not inspected; runs worked |
|
||||
| Wine host binaries | `wineloader` and `wineserver` are **x86_64 only** (`lipo -archs`), so CrossOver's Wine runs under Rosetta 2 on this Mac. `arch -x86_64 /usr/bin/true` executes |
|
||||
| Bottle | `betterxen-test`, template `win11_64`, created in 18.7 s with `cxbottle --bottle betterxen-test --create --template win11_64` |
|
||||
| Launch interface | `bin/wine --bottle B program` and `bin/wineserver -k`. `cxbottle --help` and `cxstart --help` exist in the bundle. **None of these command-line interfaces is documented by CodeWeavers for macOS**: the [Mac user guide](https://support.codeweavers.com/en_US/crossover-mac-user-guide) and [advanced configuration page](https://support.codeweavers.com/advanced-crossover-mac-configuration) cover the GUI and hook variables only. They are used here as observed vendor behaviour of this build |
|
||||
| Backend selection | `CX_GRAPHICS_BACKEND=<name>` in the environment. Undocumented (see #350). An unknown value (`bogus`) was **accepted silently** and gave the same result as the default |
|
||||
| Toolchain | llvm-mingw 20261117, Rust 1.100.0; see [hybrid-toolchain.md](hybrid-toolchain.md) |
|
||||
| Host noise | CrossOver's antivirus helper prints `LibClamAV Error` and `Can't open file or directory` because Homebrew's ClamAV has no database in `/opt/homebrew/var/lib/clamav`. Harmless to results; the run record reports it as a diagnostic |
|
||||
|
||||
## Workloads executed
|
||||
|
||||
Run with `betterxen-hybrid run --bottle betterxen-test --expect PASS -- <exe>`, default backend.
|
||||
|
||||
| Workload | x86-64 result | ARM64 result |
|
||||
| --- | --- | --- |
|
||||
| C self-check (CRC-32, four threads) | passed, exit 0, 1.4 s | `cannot_execute` |
|
||||
| Rust self-check (threads, TLS) | passed, exit 0, 0.6 s | `cannot_execute` |
|
||||
| D3D11 clear and readback | passed, exit 0, 1.1 s | `cannot_execute` |
|
||||
| D3D11 indexed triangle, shaders, frame loop | passed, exit 0, 0.8 s | `cannot_execute` |
|
||||
|
||||
CrossOver 26.3 here **rejects Windows ARM64 executables** with `winewrapper.exe:error: cannot execute`. The ARM64 builds exist and have the correct PE type, but cannot be run in this environment. Process memory sampled while running was about 325 MB (CrossOver's persistent processes, identical across workloads, so it says nothing about the workloads themselves); minimum system free memory stayed at 64 to 68 %.
|
||||
|
||||
Negative controls (#365): `d3d11-clear --negative-control` and `d3d11-frameloop --negative-control` expect a deliberately wrong colour and exit 1; the normal runs exit 0.
|
||||
|
||||
### Defects found in BetterXen's own workloads, not in CrossOver
|
||||
|
||||
1. **Clear test required exact bytes.** The first run read green as 127 where the program expected 128 (0.5 × 255 = 127.5, an exact tie). Re-derived from the primary source ([Direct3D data conversion rules](https://learn.microsoft.com/en-us/windows/win32/direct3d10/d3d10-graphics-programming-guide-resources-data-conversion)): the ideal conversion adds 0.5 and drops the fraction (128), but implementations are permitted a tolerance of 0.6 unit-last-place on the integer side (`D3D12_FLOAT32_TO_INTEGER_TOLERANCE_IN_ULP (0.6f)` in the mingw-w64 header; the D3D11 constant is described by the same page). 127 is 0.5 from 127.5 and is within tolerance. The workload now checks that tolerance and prints how many pixels differ from the ideal. This was a correction to match the specification, not a loosening to get a pass: the negative control still fails.
|
||||
2. **Triangle was culled.** The first frame-loop run left the centre black. The index order was counter-clockwise, which Direct3D 11 culls by default. Fixed to clockwise; the centre then read (51, 102, 204, 255) exactly.
|
||||
|
||||
## Graphics backend comparison
|
||||
|
||||
`betterxen-hybrid bench --backends default,d3dmetal,dxmt,dxvk,wined3d --repeat 5`, 2000 frames per run, workload `d3d11-frameloop`: a 640x360 offscreen RGBA8 target, one indexed triangle with a vertex and a pixel shader, an event query waited on every frame. **No window and no presentation.** All 25 runs passed. Medians across five runs:
|
||||
|
||||
| Backend (detected from workload output) | Adapter reported | Median frame | p95 | p99 | Frame rate | Startup + run, median |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| default | AMD Compatibility Mode | 0.281 ms | 0.448 ms | 0.929 ms | 3153 | 1.42 s |
|
||||
| d3dmetal | AMD Compatibility Mode | 0.282 ms | 0.558 ms | 1.805 ms | 2898 | 1.44 s |
|
||||
| dxmt | Apple M4 | 0.158 ms | 0.239 ms | 0.382 ms | 5896 | 1.13 s |
|
||||
| dxvk (via MoltenVK, "cxaddon-1.10.3") | Apple M4 | 0.150 ms | 0.263 ms | 0.478 ms | 5835 | 1.13 s |
|
||||
| wined3d | Apple M4 | 0.150 ms | 0.256 ms | 0.419 ms | 5788 | 1.13 s |
|
||||
|
||||
Observations, with their limits:
|
||||
|
||||
- **The default behaved like D3DMetal** (same adapter identity, same timings) for a bottle made from `win11_64` and an unknown executable. CodeWeavers' Advanced Settings page, as recorded in [primary-source-verification](primary-source-verification-2026-11-25.md), says Auto falls back to wined3d without a per-game database entry. The observation disagrees with that reading; why was not investigated.
|
||||
- D3DMetal's median per-frame submit-and-wait time was about 1.8 times that of the other three, with a larger tail. This is the cost of a trivial draw plus synchronisation, **not rendering throughput**, and shows nothing about real scenes. It identifies a candidate for investigation, not a bottleneck.
|
||||
- Sustained run, 200,000 frames: D3DMetal 64.1 s, median 0.283 ms, p99 0.987 ms, p99.9 2.07 ms, maximum 20.3 ms; DXMT 29.6 s, median 0.135 ms, p99 0.339 ms, p99.9 0.48 ms, maximum 7.4 ms. No failure, no hang, and free memory did not trend downward (minimum 64 % and 66 %).
|
||||
- Not measured: GPU utilization (no unprivileged documented source on this host), memory use of the workload itself, thermal behaviour under load (pmset reported no thermal, performance or CPU-power warning before and after; the workload loads the GPU too lightly for that to mean anything), presentation and frame pacing, texture sampling, depth testing, and Direct3D 12.
|
||||
|
||||
## What this does and does not establish
|
||||
|
||||
Established on this machine and build: CrossOver 26.3 runs original x86-64 console, threaded, Direct3D 11 clear and triangle programs under four graphics backends with correct pixels; it does not run ARM64 Windows programs; BetterXen can detect, supervise, classify and record such runs. Not established: anything about Direct3D 12, real-scene performance, other macOS or CrossOver versions, other machines, or any game. A second contributor still has to reproduce this.
|
||||
@@ -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,36 @@
|
||||
# Windows cross-toolchain for original workloads (issue #364)
|
||||
|
||||
Evidence class B for the build results (commands run on the reference machine, 2026-11-25), class D for licences. The x86-64 programs were later run under CrossOver 26.3; results are in [crossover-baseline-2026-11-25.md](crossover-baseline-2026-11-25.md).
|
||||
|
||||
## Pinned toolchain
|
||||
|
||||
| Item | Value |
|
||||
| --- | --- |
|
||||
| Toolchain | [llvm-mingw](https://github.com/mstorsjo/llvm-mingw) release `20261117`, asset `llvm-mingw-20261117-ucrt-macos-universal.tar.xz` |
|
||||
| SHA-256 | `98d340bbb8d46b09ad6886ffba88bd9d5415e131c316de48e6bd7647377446aa`, equal to the digest GitHub shows for the asset; computed locally with `shasum -a 256` after download |
|
||||
| Host binaries | Mach-O universal (x86_64, arm64); `codesign -dv` shows the clang driver is signed. Runs natively on Apple Silicon |
|
||||
| Targets used | `x86_64-w64-mingw32` and `aarch64-w64-mingw32` (clang), Rust `x86_64-pc-windows-gnullvm` and `aarch64-pc-windows-gnullvm` |
|
||||
| Licence | `LICENSE.TXT` in the release opens with "The LLVM Project is under the Apache License v2.0 with LLVM Exceptions" and then lists further component licences (the mingw-w64 runtime has its own terms). The full file was **not** audited line by line. It is an external build tool: nothing from it is shipped or copied into this repository |
|
||||
| Install | Download, check the digest, unpack outside the repository (for example `~/toolchains/`), pass the directory to the build script. It is not vendored |
|
||||
|
||||
Rust 1.100.0 with `rustup target add x86_64-pc-windows-gnullvm aarch64-pc-windows-gnullvm`.
|
||||
|
||||
## Build and result
|
||||
|
||||
`scripts/hybrid/build-windows-workloads.sh <llvm-mingw-dir>` builds three original programs for both architectures with `-Wall -Wextra -Werror` and then checks each output with `file`; it exits non-zero if a PE has the wrong machine type.
|
||||
|
||||
| Program | Source | x86-64 | ARM64 | Executed under CrossOver 26.3 |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| C self-check: CRC-32 check value, four threads, interlocked counter | `workloads/win-selfcheck-c` | built; passed | built; rejected (`cannot execute`) | x86-64 yes, ARM64 no |
|
||||
| Rust self-check: thread-local storage across four threads | `workloads/win-selfcheck-rust` | built; passed | built; rejected | x86-64 yes, ARM64 no |
|
||||
| Direct3D 11 clear and readback of a 64x64 RGBA8 target (first step of #365) | `workloads/d3d11-clear` | built; passed within the specified tolerance | built; rejected | x86-64 yes, ARM64 no |
|
||||
|
||||
A fourth program, `workloads/d3d11-frameloop` (indexed triangle, shaders, sustained frame loop; needs `-ldxguid -ld3dcompiler`), builds the same way. The D3D11 programs exit 2 ("no device") rather than passing when no hardware device exists, so a missing GPU path cannot be mistaken for success.
|
||||
|
||||
## Alternative evaluated: skakwy's `gnullvm-cc.sh`
|
||||
|
||||
The contributor's `tools/macos/gnullvm-cc.sh` (victory-mac commit `22b3f8e45a59`) links `x86_64-pc-windows-gnullvm` with Homebrew clang and rustup's lld. On the reference machine, with Homebrew `llvm@17` as `LLVM_PREFIX`, it failed at link time: `clang-17` aborted with `dyld: Symbol not found: _LLVMInitializeLanaiAsmParser`, because the script sets `DYLD_LIBRARY_PATH` to the Rust toolchain's `libLLVM`. It probably expects a newer Homebrew LLVM; which version was not asked. llvm-mingw covers the same need without that dependency, so the script was **not integrated**. His note that the plain `x86_64-pc-windows-gnu` target aborts on thread start is unverified here, since no program was run.
|
||||
|
||||
## Reproducibility
|
||||
|
||||
Rebuilding twice on one machine and path gives byte-identical SHA-256 for all eight outputs, after adding `-Wl,--no-insert-timestamp` (the C programs differed before because of the PE timestamp). The Rust outputs were identical without it. A build in a different directory was not tested and may embed paths; the second-contributor reproduction that #364 requires has not happened. The `file` check shows the llvm-mingw host binaries are universal (x86_64 and arm64), so the issue's "arm64 only" criterion is not met by this release asset.
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
> **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
|
||||
@@ -50,8 +52,7 @@ 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.
|
||||
The documentation PR is based on the reviewed newer main revision and changes
|
||||
no runtime implementation.
|
||||
Local documentation edits from this review do not install that newer runtime.
|
||||
|
||||
## Why the PC results do not transfer directly
|
||||
|
||||
@@ -114,7 +115,7 @@ project's title-specific API totals or implementation.
|
||||
| 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 | The inspected README's former X10 description understated this bounded path; the replacement roadmap removes that stale planning row. Broader bindings, control flow and sampling still need contracts. |
|
||||
| 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. |
|
||||
@@ -200,7 +201,7 @@ 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](../development-phases.md) define the sole
|
||||
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.
|
||||
@@ -232,7 +233,7 @@ reuse permission. Descriptions below classify documentation, not executed code.
|
||||
| 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. |
|
||||
| Leonida (`ItsNotRexed/Leonida`) | 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. |
|
||||
@@ -291,9 +292,9 @@ reuse permission. Descriptions below classify documentation, not executed code.
|
||||
| `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 Leonida shader conversion. No implementation reuse. |
|
||||
| `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` | Leonida fork; tool portability on macOS does not establish native guest execution. No implementation reuse. |
|
||||
| `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. |
|
||||
@@ -306,7 +307,7 @@ reuse permission. Descriptions below classify documentation, not executed code.
|
||||
| `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 Leonida; retain only documented failure categories, not code or title-derived inputs. |
|
||||
| `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. |
|
||||
@@ -351,7 +352,5 @@ 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.
|
||||
The research stage installed or executed no upstream project or game content.
|
||||
Documentation publication and the GitHub research/follow-up issues were requested
|
||||
by the user; their delivery status is recorded in the linked PR/tracker. No
|
||||
runtime merge, release or compatibility acceptance is implied.
|
||||
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,61 @@
|
||||
# Shader wave-operation failures under D3DMetal: investigation
|
||||
|
||||
Branch `research/shader-wave-semantics` (PR #392), based on the shader integration branch. 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_f64_4`: a plain `double` add (no wave operation) | low `0x00000000`, high `0x40000000` | **every dword still `0xDEADBEEF`: the shader wrote nothing** |
|
||||
| `sum_f64_4`: `WaveActiveSum` over a `double` | low `0x00000000`, high `0x40140000` | **every dword still `0xDEADBEEF`: the shader wrote nothing** |
|
||||
|
||||
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: **229 passed, 0 failed, 3 ignored** (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 # 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
|
||||
|
||||
Loaded 100 of 128 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user